Compare commits

..
Author SHA1 Message Date
Gwendal Roué 60beb7cd9c DocC: document extensions 2023-06-17 17:03:55 +02:00
343 changed files with 6096 additions and 21573 deletions

No files matched your search

+28 -44
View File
@@ -13,7 +13,6 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
pull_request:
paths:
- 'GRDB/**'
@@ -21,7 +20,6 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
concurrency:
group: ${{ github.ref_name }}
@@ -40,32 +38,24 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=iPhone 14 Pro"
name: "iOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-13
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-13
runsOn: macOS-12
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-13
runsOn: macOS-12
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-13
runsOn: macOS-12
destination: "OS=16.1,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.0.1.app"
@@ -77,7 +67,7 @@ jobs:
destination: "OS=16.0,name=iPhone 14"
name: "iOS"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -90,20 +80,17 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-13
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-13
runsOn: macOS-12
name: "Xcode 14.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -116,14 +103,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
name: "Xcode 14.2"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -136,14 +120,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -156,14 +140,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -176,14 +160,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_universal_xcframework
run: make test_archive_GRDBOSX_xcframework
-132
View File
@@ -7,17 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.26.x` Releases - [6.26.0](#6260)
- `6.25.x` Releases - [6.25.0](#6250)
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
- `6.22.x` Releases - [6.22.0](#6220)
- `6.21.x` Releases - [6.21.0](#6210)
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
- `6.19.x` Releases - [6.19.0](#6190)
- `6.18.x` Releases - [6.18.0](#6180)
- `6.17.x` Releases - [6.17.0](#6170)
- `6.16.x` Releases - [6.16.0](#6160)
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
- `6.14.x` Releases - [6.14.0](#6140)
- `6.13.x` Releases - [6.13.0](#6130)
@@ -124,127 +113,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.26.0
Released March 23, 2024
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
## 6.25.0
Released February 25, 2024
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
## 6.24.2
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
Released January 6, 2024
- **New**: [#1477](https://github.com/groue/GRDB.swift/pull/1477): Remove shadow tables from database dump
## 6.24.0
Released January 6, 2024
- **New**: [#1466](https://github.com/groue/GRDB.swift/pull/1466) by [@barnettben](https://github.com/barnettben): Add schema name option to database introspection methods
## 6.23.0
Released December 1, 2023
- **New**: [#1462](https://github.com/groue/GRDB.swift/pull/1462) Temporary read-only access
## 6.22.0
Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
Released October 29, 2023
- **New**: [#1448](https://github.com/groue/GRDB.swift/pull/1448) by [@groue](https://github.com/groue): Add support for stable ordering and dump of views
- **New**: [#1449](https://github.com/groue/GRDB.swift/pull/1449) by [@groue](https://github.com/groue): Backport temporary copies from GRDBSnapshotTesting
## 6.20.2
Released October 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.1...v6.20.2)
- **Fixed**: [#1442](https://github.com/groue/GRDB.swift/pull/1442) by [@groue](https://github.com/groue): Extend the macOS availability of JSON functions
## 6.20.1
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.0...v6.20.1)
- **Fixed**: Removed a debug print
## 6.20.0
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.19.0...v6.20.0)
- **New**: [#1439](https://github.com/groue/GRDB.swift/pull/1439) by [@groue](https://github.com/groue): Dump requests
- **New**: `QueryInterfaceRequest.withStableOrder()` returns a request with well-defined order, suitable for tests.
## 6.19.0
Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
- **New**: Expose the database path from `DatabaseReader`.
## 6.17.0
Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode
## 6.16.0
Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0)
- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views
- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes
- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
## 6.15.1
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
+2 -2
View File
@@ -61,7 +61,7 @@ How you can Contribute
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
- No Swiftlint warning after a build.
@@ -69,7 +69,7 @@ How you can Contribute
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
+23 -27
View File
@@ -429,13 +429,15 @@ The matching [migration] would look like:
migrator.registerMigration("Employees") { db in
try db.create(table: "employee") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
t.column("managerId", .integer)
.indexed()
.references("employee", onDelete: .restrict)
t.column("name", .text)
}
}
```
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
```swift
struct EmployeeInfo: FetchableRecord, Decodable {
@@ -534,16 +536,20 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", onDelete: .cascade) // (2)
t.column("authorId", .integer) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
2. The `book.authorId` column is used to link a book to the author it belongs to.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -589,16 +595,20 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", onDelete: .cascade) // (2)
t.column("authorId", .integer) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
2. The `book.authorId` column is used to link a book to the author it belongs to.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -644,9 +654,10 @@ migrator.registerMigration("Countries") { db in
}
try db.create(table: "demographics") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("country", onDelete: .cascade) // (2)
t.column("countryCode", .text) // (2)
.notNull() // (3)
.unique() // (4)
.references("country", onDelete: .cascade) // (5)
t.column("population", .integer)
t.column("density", .double)
}
@@ -654,9 +665,10 @@ migrator.registerMigration("Countries") { db in
```
1. The `country` table has a primary key.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -708,22 +720,6 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/AmbiguousForeignKeys.svg)
```swift
// The migration that has created the above schema
migrator.registerMigration("Library") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", inTable: "person")
t.belongsTo("translator", inTable: "person")
t.column("title", .text)
}
}
```
When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person".
Your help is needed. You have to instruct GRDB which foreign key to use:
@@ -2169,7 +2165,7 @@ struct BookInfo: FetchableRecord {
var country: Country?
var coverImage: CoverImage?
init(row: some RowProtocol) throws {
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
@@ -2204,7 +2200,7 @@ struct AuthorInfo: FetchableRecord {
var author: Author
var books: [Book]
init(row: some RowProtocol) throws {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
}
@@ -2661,7 +2657,7 @@ Aggregates can be modified and combined with Swift operators:
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
```
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
<details>
<summary>SQL</summary>
+1 -3
View File
@@ -362,9 +362,7 @@ And we can fetch the data that feeds our application screen:
```swift
let chatInfos: [ChatInfos] = try dbQueue.read { db in
try request.fetchAll(db)
}
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
+1 -1
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -1,7 +1,6 @@
import WatchKit
import Foundation
import GRDB
import SQLite3
class InterfaceController: WKInterfaceController {
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2</string>
<string>com.github.groue.GRDBDemoiOS</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -640,7 +640,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -660,7 +660,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -677,7 +677,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -694,7 +694,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -832,7 +832,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -849,7 +849,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
+1 -3
View File
@@ -397,9 +397,7 @@ let publisher = observation
// NEW: GRDB 5
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read { db in
try query.build(db)
}
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
@@ -29,7 +29,10 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull()
t.belongsTo("author", onDelete: .cascade).notNull()
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
}
}
@@ -75,7 +75,7 @@ struct Place {
// Adopt FetchableRecord
extension Place : FetchableRecord {
init(row: some RowProtocol) {
init(row: Row) {
id = row["id"]
title = row["title"]
favorite = row["favorite"]
@@ -23,7 +23,7 @@ migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.belongsTo("owner", inTable: "person", onDelete: .cascade)
t.column("ownerId", .integer).references("person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
+1 -1
View File
@@ -6,7 +6,7 @@ Release Process
To release a new GRDB version:
- Tests
- `make distclean test`
- `make test`
- Build and run GRDBDemoiOS in Release configuration on a device
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
+5 -7
View File
@@ -112,15 +112,13 @@ let components: [SQL] = [
let query = components.joined(separator: " ")
```
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
Extract the plain SQL string from a literal:
```swift
try dbQueue.read { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try query.build(db)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
}
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.26.0'
s.version = '6.15.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -9,7 +9,7 @@ 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.10']
s.swift_versions = ['5.7']
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.13'
s.watchos.deployment_target = '4.0'
+11 -183
View File
@@ -13,10 +13,6 @@
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
@@ -58,9 +54,6 @@
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
@@ -75,8 +68,6 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; };
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */; };
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
@@ -103,7 +94,6 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
@@ -125,7 +115,6 @@
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
@@ -157,7 +146,6 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
@@ -186,7 +174,7 @@
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
566BE71E2342542F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; };
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
@@ -206,24 +194,14 @@
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
56781B0B243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */; };
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE12AD3284100629622 /* DumpFormat.swift */; };
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */; };
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */; };
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */; };
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE62AD3284100629622 /* Database+Dump.swift */; };
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */; };
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */; };
567DAF1C1EAB61ED00FC0928 /* 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 */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; };
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; };
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; };
@@ -256,8 +234,6 @@
569BBA3622905FFA00478429 /* InflectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA3522905FFA00478429 /* InflectionsTests.swift */; };
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */ = {isa = PBXBuildFile; fileRef = 569BBA4522906A8200478429 /* InflectionsTests.json */; };
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA482291707D00478429 /* Inflections+English.swift */; };
569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */; };
569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D55332BBAFEC700B57CA5 /* StatementRow.swift */; };
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
@@ -269,6 +245,7 @@
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2FA3524424D2A00E97D23 /* Export.swift */; };
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
@@ -285,7 +262,6 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA65B2B79246300B3A7F8 /* Mutex.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
@@ -403,17 +379,8 @@
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; };
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */; };
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */; };
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */; };
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */; };
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */; };
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */; };
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; };
56FA0C3028B1F2DC00B2DFF7 /* 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 */; };
56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
@@ -441,10 +408,6 @@
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -485,9 +448,6 @@
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -495,8 +455,6 @@
5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = "<group>"; };
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
@@ -535,7 +493,6 @@
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
@@ -557,7 +514,6 @@
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
@@ -631,7 +587,7 @@
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
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 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.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>"; };
@@ -656,25 +612,15 @@
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = "<group>"; };
567B5BE12AD3284100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = "<group>"; };
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = "<group>"; };
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = "<group>"; };
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = "<group>"; };
567B5BE62AD3284100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.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>"; };
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>"; };
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
@@ -724,8 +670,6 @@
569BBA4522906A8200478429 /* InflectionsTests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = InflectionsTests.json; sourceTree = "<group>"; };
569BBA482291707D00478429 /* Inflections+English.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Inflections+English.swift"; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetachedRow.swift; sourceTree = "<group>"; };
569D55332BBAFEC700B57CA5 /* StatementRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementRow.swift; sourceTree = "<group>"; };
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = "<group>"; };
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
@@ -760,6 +704,7 @@
56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = "<group>"; };
56A2FA3524424D2A00E97D23 /* Export.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Export.swift; sourceTree = "<group>"; };
56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = "<group>"; };
56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = "<group>"; };
56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = "<group>"; };
@@ -787,7 +732,6 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA65B2B79246300B3A7F8 /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = "<group>"; };
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
@@ -841,17 +785,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>"; };
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = "<group>"; };
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = "<group>"; };
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = "<group>"; };
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = "<group>"; };
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = "<group>"; };
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = "<group>"; };
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = "<group>"; };
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; 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>"; };
56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowProtocol.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>"; };
@@ -859,7 +794,6 @@
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
@@ -888,25 +822,6 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5603CEB52AC862EC00CF097D /* JSON */ = {
isa = PBXGroup;
children = (
5603CEB82AC862EC00CF097D /* JSONColumn.swift */,
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */,
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */,
);
path = JSON;
sourceTree = "<group>";
};
5603CEC82AC8630300CF097D /* JSON */ = {
isa = PBXGroup;
children = (
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */,
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */,
);
name = JSON;
sourceTree = "<group>";
};
5605F1471C672E4000235C62 /* Support */ = {
isa = PBXGroup;
children = (
@@ -986,7 +901,6 @@
isa = PBXGroup;
children = (
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -1014,15 +928,12 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56BCA65B2B79246300B3A7F8 /* Mutex.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567B5BDA2AD3281B00629622 /* Dump */,
56677C14241D14450050755D /* FailureTestCase.swift */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5603CEC82AC8630300CF097D /* JSON */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
@@ -1098,7 +1009,6 @@
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
@@ -1138,10 +1048,8 @@
5687359E1CEDE16C009B9116 /* Betty.jpeg */,
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */,
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */,
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */,
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */,
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */,
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */,
);
name = DatabaseQueue;
@@ -1264,11 +1172,6 @@
5656A8142295AF75001FF3FF /* Schema */ = {
isa = PBXGroup;
children = (
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */,
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */,
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */,
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */,
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */,
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */,
5698AC771DA37DCB0056AF8C /* VirtualTableModule.swift */,
);
@@ -1278,12 +1181,8 @@
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
isa = PBXGroup;
children = (
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */,
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */,
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1325,7 +1224,7 @@
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */,
563EF4492161F179007DAACD /* Inflections.swift */,
569BBA482291707D00478429 /* Inflections+English.swift */,
566BE7172342542F00A8254B /* Mutex.swift */,
566BE7172342542F00A8254B /* LockedBox.swift */,
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
@@ -1349,7 +1248,6 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1357,38 +1255,6 @@
name = FetchableRecord;
sourceTree = "<group>";
};
567B5BDA2AD3281B00629622 /* Dump */ = {
isa = PBXGroup;
children = (
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */,
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */,
);
name = Dump;
sourceTree = "<group>";
};
567B5BDF2AD3284100629622 /* Dump */ = {
isa = PBXGroup;
children = (
567B5BE62AD3284100629622 /* Database+Dump.swift */,
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */,
567B5BE12AD3284100629622 /* DumpFormat.swift */,
567B5BE22AD3284100629622 /* DumpFormats */,
);
path = Dump;
sourceTree = "<group>";
};
567B5BE22AD3284100629622 /* DumpFormats */ = {
isa = PBXGroup;
children = (
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */,
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */,
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */,
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */,
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */,
);
path = DumpFormats;
sourceTree = "<group>";
};
569530FA1C9067CC00CF1A2B /* Crash */ = {
isa = PBXGroup;
children = (
@@ -1591,15 +1457,13 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
569D55312BBAFE9E00B57CA5 /* DetachedRow.swift */,
569D55332BBAFEC700B57CA5 /* StatementRow.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56FA602E2BB96AA50085DEB7 /* RowProtocol.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
@@ -1609,7 +1473,6 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1747,12 +1610,10 @@
DC37742D19C8CC90004FCF85 /* GRDB */ = {
isa = PBXGroup;
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEB52AC862EC00CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
56300B6D1C53F592005A543B /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1885,7 +1746,6 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1938,7 +1798,6 @@
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */,
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
@@ -1950,7 +1809,6 @@
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
@@ -1965,7 +1823,6 @@
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */,
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
@@ -2025,7 +1882,6 @@
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */,
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
@@ -2044,7 +1900,6 @@
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */,
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
@@ -2055,7 +1910,6 @@
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C5124A51998004967E1 /* Finished.swift in Sources */,
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
@@ -2072,7 +1926,6 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
@@ -2100,7 +1953,6 @@
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */,
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
@@ -2110,9 +1962,7 @@
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56BCA65C2B79246300B3A7F8 /* Mutex.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */,
@@ -2168,7 +2018,6 @@
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
@@ -2202,7 +2051,6 @@
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2217,13 +2065,11 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
@@ -2232,13 +2078,11 @@
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
569D55322BBAFE9E00B57CA5 /* DetachedRow.swift in Sources */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
@@ -2246,7 +2090,6 @@
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
@@ -2255,12 +2098,10 @@
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */,
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
@@ -2273,13 +2114,9 @@
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
56FA602F2BB96AA50085DEB7 /* RowProtocol.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
566BE71E2342542F00A8254B /* Mutex.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
@@ -2287,10 +2124,8 @@
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
56894FB72606589700268F4D /* Decimal.swift in Sources */,
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */,
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
@@ -2307,14 +2142,10 @@
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */,
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */,
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
@@ -2327,10 +2158,7 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
569D55342BBAFEC700B57CA5 /* StatementRow.swift in Sources */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+28 -72
View File
@@ -1,17 +1,7 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Dispatch
import Foundation
// TODO: remove @unchecked when DispatchQoS is Sendable
public struct Configuration: @unchecked Sendable {
public struct Configuration {
// MARK: - Misc options
@@ -196,7 +186,7 @@ public struct Configuration: @unchecked Sendable {
// MARK: - Managing SQLite Connections
private var setups: [@Sendable (Database) throws -> Void] = []
private var setups: [(Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -233,12 +223,34 @@ public struct Configuration: @unchecked Sendable {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
setups.append(setup)
}
// MARK: - Transactions
/// The default kind of write transactions.
///
/// The default is ``Database/TransactionKind/deferred``.
///
/// You can change the default transaction kind. For example, you can force
/// all write transactions to be `IMMEDIATE`:
///
/// ```swift
/// var config = Configuration()
/// config.defaultTransactionKind = .immediate
/// let dbQueue = try DatabaseQueue(configuration: config)
///
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
/// try dbQueue.write { db in ... }
/// ```
///
/// This property is ignored for read-only transactions. Those always open
/// `DEFERRED` SQLite transactions.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
public var defaultTransactionKind: Database.TransactionKind = .deferred
/// A boolean value indicating whether it is valid to leave a transaction
/// opened at the end of a database access method.
///
@@ -276,46 +288,6 @@ public struct Configuration: @unchecked Sendable {
/// of a read access.
public var allowsUnsafeTransactions = false
// MARK: - Journal Mode
/// Defines how the journal mode is configured when the database
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public enum JournalModeConfiguration: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
/// ``wal`` case).
case `default`
/// The journal mode is set to WAL (plus extra configurations that
/// make life easier with WAL databases).
case wal
}
/// Defines how the journal mode is configured when the database
/// connection is opened.
///
/// This configuration is ignored when ``readonly`` is true.
///
/// The default value has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool`` configure
/// the database for the WAL mode.
///
/// Applications that need to open a WAL database with a
/// ``DatabaseQueue`` should set the `journalMode` to `wal`:
///
/// ```swift
/// // Open a WAL database with DatabaseQueue
/// var config = Configuration()
/// config.journalMode = .wal
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public var journalMode = JournalModeConfiguration.default
// MARK: - Concurrency
/// Defines the how `SQLITE_BUSY` errors are handled.
@@ -433,25 +405,9 @@ public struct Configuration: @unchecked Sendable {
/// through a `SerializedDatabase`.
var threadingMode = Database.ThreadingMode.default
private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)?
private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)?
private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)?
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidOpen = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) {
SQLiteConnectionWillClose = callback
}
// Workaround https://github.com/apple/swift/issues/72727
mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) {
SQLiteConnectionDidClose = callback
}
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteOpenFlags: CInt {
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
if sqlite3_libversion_number() >= 3037000 {
+188 -121
View File
@@ -14,9 +14,14 @@
extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
/// ```
///
/// - parameter cursor: The cursor whose elements feed the collection.
public init(_ cursor: some Cursor<Element>) throws {
@@ -26,9 +31,14 @@ extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
/// ```
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// - parameter minimumCapacity: Prepares the returned collection to store
@@ -41,8 +51,8 @@ extension RangeReplaceableCollection {
/// 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.
/// - Important: If an error is thrown, 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 {
@@ -58,9 +68,13 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
/// ```
///
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
@@ -81,12 +95,16 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
/// ```
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -112,9 +130,13 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
/// ```
///
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
@@ -137,11 +159,15 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
/// ```
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -165,9 +191,13 @@ extension Dictionary {
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
/// ```
///
/// - parameter cursor: A cursor of values to gather into a set.
public init(_ cursor: some Cursor<Element>) throws {
@@ -180,9 +210,13 @@ extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
/// ```
///
/// - parameter cursor: A cursor of values to gather into a set.
/// - parameter minimumCapacity: The minimum number of elements that the
@@ -240,6 +274,75 @@ extension Sequence {
///
/// ## Topics
///
/// ### Iterating Over a Cursor’s Elements
///
/// - ``next()``
/// - ``forEach(_:)-4ib2m``
/// - ``enumerated()``
/// - ``isEmpty``
///
/// ### Finding Elements
///
/// - ``contains(_:)``
/// - ``contains(where:)``
/// - ``first(where:)``
/// - ``min()``
/// - ``min(by:)``
/// - ``max()``
/// - ``max(by:)``
///
/// ### Selecting Elements
///
/// - ``prefix(_:)``
/// - ``prefix(while:)``
/// - ``suffix(_:)``
///
/// ### Excluding Elements
///
/// - ``dropFirst()``
/// - ``dropFirst(_:)``
/// - ``dropLast()``
/// - ``dropLast(_:)``
/// - ``drop(while:)``
/// - ``filter(_:)``
///
/// ### Transforming a Cursor
///
/// - ``map(_:)``
/// - ``compactMap(_:)``
/// - ``flatMap(_:)-5ci2v``
/// - ``flatMap(_:)-8jxlj``
/// - ``reduce(_:_:)``
/// - ``reduce(into:_:)``
///
/// ### Transforming a Sequence into a Cursor
///
/// - ``Swift/Sequence/flatMap(_:)``
///
/// ### Joining Elements
///
/// - ``joined()-5r5ja``
/// - ``joined()-7bnrx``
/// - ``joined(separator:)``
///
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
///
/// - ``Swift/RangeReplaceableCollection/init(_:)``
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
///
/// ### Creating a Dictionary from the contents of a Cursor
///
/// - ``Swift/Dictionary/init(grouping:by:)``
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
///
/// ### Creating a Set from the contents of a Cursor
///
/// - ``Swift/Set/init(_:)``
/// - ``Swift/Set/init(_:minimumCapacity:)``
///
/// ### Supporting Types
///
/// - ``AnyCursor``
@@ -269,7 +372,7 @@ extension Cursor {
/// Returns a Boolean value indicating whether the cursor does not contain
/// any element.
///
/// - important: This property may consume elements.
/// - important: This property consumes an element.
public var isEmpty: Bool {
get throws { try next() == nil }
}
@@ -294,13 +397,17 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
/// ```swift
/// let cursor = try String.fetchCursor(db, sql: """
/// SELECT 'foo' UNION ALL SELECT 'bar'
/// """)
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
/// ```
public func enumerated() -> EnumeratedCursor<Self> {
EnumeratedCursor(self)
}
@@ -346,11 +453,13 @@ extension Cursor {
/// If the number of elements to drop exceeds the number of elements in
/// the cursor, the result is an empty cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
/// ```
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the cursor. `n` must be greater than or equal to zero.
@@ -364,9 +473,11 @@ extension Cursor {
///
/// The following example drops the first element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
/// ```
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -381,11 +492,13 @@ extension Cursor {
/// The cursor must be finite. If the number of elements to drop exceeds
/// the number of elements in the cursor, the result is an empty array.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
/// ```
///
/// - Parameter n: The number of elements to drop off the end of the
/// cursor. `n` must be greater than or equal to zero.
@@ -414,9 +527,11 @@ extension Cursor {
///
/// The following example drops the last element from a cursor of integers.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
/// ```
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -502,11 +617,13 @@ extension Cursor {
/// If the maximum length exceeds the number of elements in the cursor,
/// the result contains all the elements in the cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -562,11 +679,13 @@ extension Cursor {
/// elements in the cursor, the result contains all the elements in the
/// cursor.
///
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -620,24 +739,16 @@ extension Cursor where Element: Equatable {
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's maximum element. If the cursor has no
/// elements, returns `nil`.
public func max() throws -> Element? {
try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
/// - Returns: The cursor's minimum element. If the cursor has no
/// elements, returns `nil`.
public func min() throws -> Element? {
try min(by: <)
}
@@ -733,11 +844,6 @@ public final class AnyCursor<Element>: Cursor {
}
}
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
// sendable than non-sendable cursors (such as `DatabaseCursor`).
@available(*, unavailable)
extension AnyCursor: Sendable { }
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
/// cursor before possibly returning the first available element.
public final class DropFirstCursor<Base: Cursor> {
@@ -752,11 +858,6 @@ public final class DropFirstCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropFirstCursor: Sendable { }
extension DropFirstCursor: Cursor {
public func next() throws -> Base.Element? {
while dropped < limit {
@@ -783,11 +884,6 @@ public final class DropWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropWhileCursor: Sendable { }
extension DropWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if predicateHasFailed {
@@ -833,11 +929,6 @@ public final class EnumeratedCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension EnumeratedCursor: Sendable { }
extension EnumeratedCursor: Cursor {
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
@@ -865,10 +956,6 @@ public final class FilterCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable.
@available(*, unavailable)
extension FilterCursor: Sendable { }
extension FilterCursor: Cursor {
public func next() throws -> Base.Element? {
while let element = try base.next() {
@@ -899,11 +986,6 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FlattenCursor: Sendable { }
extension FlattenCursor: Cursor {
public func next() throws -> Base.Element.Element? {
while true {
@@ -930,11 +1012,6 @@ public final class MapCursor<Base: Cursor, Element> {
}
}
// Explicit non-conformance to Sendable: There is no known reason for making
// it thread-safe (`transform` a Sendable closure).
@available(*, unavailable)
extension MapCursor: Sendable { }
extension MapCursor: Cursor {
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
@@ -961,11 +1038,6 @@ public final class PrefixCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixCursor: Sendable { }
extension PrefixCursor: Cursor {
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
@@ -993,11 +1065,6 @@ public final class PrefixWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixWhileCursor: Sendable { }
extension PrefixWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
+69 -251
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
/// A cache for the available database schemas.
struct SchemaCache {
@@ -66,14 +57,6 @@ extension Database {
case let .attached(name): return "\(name).sqlite_master"
}
}
/// The name of the master sqlite table, without the schema name.
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main, .attached: return "sqlite_master"
case .temp: return "sqlite_temp_master"
}
}
}
/// The identifier of a database table or view.
@@ -163,19 +146,6 @@ extension Database {
return schemaIdentifiers
}
/// The `SchemaIdentifier` named `schemaName` if it exists.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if no such schema exists.
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
let allIdentifiers = try schemaIdentifiers()
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return result
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns information about a table or a view
func table(_ tableName: String) throws -> TableInfo? {
@@ -232,19 +202,10 @@ extension Database {
return tableInfo
}
/// Returns whether a table exists
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .table, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
/// 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)
}
}
@@ -277,57 +238,20 @@ extension Database {
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .view, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
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, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .trigger, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
public func triggerExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .trigger, name: name, in: $0)
}
}
/// Checks if an entity exists in a given schema
///
/// This is checking for the existence of the entity specified by
/// `type` and `name`. It is assumed that the existence of a schema
/// named `schemaName` is already known and will throw an error if it
/// cannot be found.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return try exists(type: type, name: name, in: schemaID)
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
// SQLite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
@@ -340,17 +264,10 @@ extension Database {
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table exists in
/// the main or temp schema, or in an attached database.
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -437,13 +354,13 @@ extension Database {
// FIXME: We ignore the exception, and consider all INTEGER primary
// keys as aliases for the rowid:
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn)
primaryKey = .rowID(pkColumn.name)
} else {
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
}
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
@@ -509,18 +426,10 @@ extension Database {
/// the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func indexes(on tableName: String) throws -> [IndexInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -609,18 +518,10 @@ extension Database {
/// Returns the foreign keys defined on table named `tableName`.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -701,27 +602,10 @@ extension Database {
/// Returns a cursor over foreign key violations in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeyViolations(
in tableName: String,
in schemaName: String? = nil)
throws -> RecordCursor<ForeignKeyViolation>
{
if let schemaName {
let schemaID = try schemaIdentifier(named: schemaName)
if try exists(type: .table, name: tableName, in: schemaID) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
for schemaIdentifier in try schemaIdentifiers() {
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
@@ -750,21 +634,14 @@ extension Database {
/// Throws an error if there exists a foreign key violation in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// On the first foreign key violation found in the table, this method
/// throws a ``DatabaseError`` with extended code
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
///
/// If you are looking for the list of foreign key violations, prefer
/// ``foreignKeyViolations(in:in:)`` instead.
///
/// - throws: A ``DatabaseError`` as described above; when a
/// specified schema does not exist; if no such table or view with this
/// name exists in the main or temp schema or in an attached database.
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
/// ``foreignKeyViolations(in:)`` instead.
public func checkForeignKeys(in tableName: String) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
}
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
@@ -781,17 +658,9 @@ extension Database {
/// attached database.
func canonicalTableName(_ tableName: String) throws -> String? {
for schemaIdentifier in try schemaIdentifiers() {
// Regular tables
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
return result
}
// Master table (sqlite_master, sqlite_temp_master)
// swiftlint:disable:next inclusive_language
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
if tableName.lowercased() == masterTableName.lowercased() {
return masterTableName
}
}
return nil
}
@@ -804,44 +673,16 @@ extension Database {
schemaCache[schemaID].schemaInfo = schemaInfo
return schemaInfo
}
/// Attempts to perform a table introspection function on a given
/// table and schema
///
/// - parameter tableName: The name of the table to examine
/// - parameter schemaName: The name of the schema to check
/// - parameter introspector: An introspection function taking a
/// `TableIdentifier` as the only parameter
private func introspect<T>(
tableNamed tableName: String,
inSchemaNamed schemaName: String,
using introspector: (TableIdentifier) throws -> T?
) throws -> T {
let schemaIdentifier = try schemaIdentifier(named: schemaName)
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
}
extension Database {
/// Returns the columns in a table or a view.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table or view with this name exists in the main or temp schema, or
/// in an attached database.
public func columns(in tableName: String) throws -> [ColumnInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -999,14 +840,14 @@ extension Database {
/// Information about a column of a database table.
///
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord, Sendable {
public struct ColumnInfo: FetchableRecord {
let cid: Int
let hidden: Int?
@@ -1017,22 +858,8 @@ public struct ColumnInfo: FetchableRecord, Sendable {
///
/// The casing of this string depends on the SQLite version: make sure you
/// process this string in a case-insensitive way.
///
/// The type is the empty string when the column has no declared type.
public let type: String
/// The column data type (nil when the column has no declared type).
///
/// The casing of the raw value depends on the SQLite version: make sure
/// you process the result in a case-insensitive way.
var columnType: Database.ColumnType? {
if type.isEmpty {
return nil
} else {
return Database.ColumnType(rawValue: type)
}
}
/// A boolean value indicating if the column is constrained to be not null.
public let isNotNull: Bool
@@ -1072,7 +899,7 @@ public struct ColumnInfo: FetchableRecord, Sendable {
/// For columns that are not part of the primary key, it is zero.
public let primaryKeyIndex: Int
public init(row: some RowProtocol) {
public init(row: Row) {
cid = row["cid"]
name = row["name"]
type = row["type"]
@@ -1085,16 +912,16 @@ public struct ColumnInfo: FetchableRecord, Sendable {
/// Information about an index.
///
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo: Sendable{
public struct IndexInfo {
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public var rawValue: String
public init(rawValue: String) {
@@ -1128,7 +955,7 @@ public struct IndexInfo: Sendable{
///
/// You get instances of `ForeignKeyViolation` from the `Database` methods
/// ``Database/foreignKeyViolations()`` and
/// ``Database/foreignKeyViolations(in:in:)`` methods.
/// ``Database/foreignKeyViolations(in:)`` methods.
///
/// For example:
///
@@ -1167,7 +994,7 @@ public struct IndexInfo: Sendable{
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation: Sendable {
public struct ForeignKeyViolation {
/// The name of the table that contains the foreign key.
public var originTable: String
@@ -1182,7 +1009,7 @@ public struct ForeignKeyViolation: Sendable {
/// The id of the foreign key constraint that failed.
///
/// This id matches the ``ForeignKeyInfo/id`` property in
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:in:)``.
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
public var foreignKeyId: Int
/// A precise description of the foreign key violation.
@@ -1238,7 +1065,7 @@ public struct ForeignKeyViolation: Sendable {
}
extension ForeignKeyViolation: FetchableRecord {
public init(row: some RowProtocol) {
public init(row: Row) {
originTable = row[0]
originRowID = row[1]
destinationTable = row[2]
@@ -1272,7 +1099,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// Information about a primary key.
///
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
/// `Database` method.
///
/// When the table's primary key is the rowid:
@@ -1316,29 +1143,29 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo: Sendable {
public struct PrimaryKeyInfo {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
/// Associated string is the column name.
case rowID(ColumnInfo)
case rowID(String)
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
case regular(columns: [String], tableHasRowID: Bool)
}
private let impl: Impl
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(columnInfo))
static func rowID(_ column: String) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(column))
}
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columnInfos.isEmpty)
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
@@ -1348,34 +1175,21 @@ public struct PrimaryKeyInfo: Sendable {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case let .rowID(columnInfo):
return [columnInfo.name]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos.map(\.name)
case let .rowID(column):
return [column]
case let .regular(columns: columns, tableHasRowID: _):
return columns
}
}
/// The columns in the primary key. Nil if the primary key is the
/// hidden rowID. Never empty otherwise.
var columnInfos: [ColumnInfo]? {
switch impl {
case .hiddenRowID:
return nil
case let .rowID(columnInfo):
return [columnInfo]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos
}
}
/// When not nil, the name of the column that contains the
/// `INTEGER PRIMARY KEY`.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
return nil
case .rowID(let columnInfo):
return columnInfo.name
case .rowID(let column):
return column
case .regular:
return nil
}
@@ -1402,7 +1216,7 @@ public struct PrimaryKeyInfo: Sendable {
return true
case .rowID:
return true
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
case let .regular(columns: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
@@ -1438,11 +1252,11 @@ public struct PrimaryKeyInfo: Sendable {
/// Information about a foreign key.
///
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
/// `Database` method.
///
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
public struct ForeignKeyInfo: Sendable {
public struct ForeignKeyInfo {
/// The first column in the output of the `foreign_key_list` pragma.
public var id: Int
@@ -1481,7 +1295,7 @@ struct TableInfo: FetchableRecord {
var hasRowID: Bool
var strict: Bool
init(row: some RowProtocol) throws {
init(row: Row) throws {
switch row[0] as String {
case "main":
schemaID = .main
@@ -1502,6 +1316,10 @@ struct TableInfo: FetchableRecord {
/// A value in the `type` column of `sqlite_master`.
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
var rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
static let index = SchemaObjectType(rawValue: "index")
static let table = SchemaObjectType(rawValue: "table")
static let trigger = SchemaObjectType(rawValue: "trigger")
@@ -1515,7 +1333,7 @@ struct SchemaObject: Hashable, FetchableRecord {
var tbl_name: String?
var sql: String?
init(row: some RowProtocol) throws {
init(row: Row) throws {
// "rootpage" column is not always there: avoid using numerical indexes
type = row["type"]
name = row["name"]
@@ -1526,7 +1344,7 @@ struct SchemaObject: Hashable, FetchableRecord {
/// All objects in a database schema (tables, views, indexes, triggers).
struct SchemaInfo: Equatable {
let objects: Set<SchemaObject>
private var objects: Set<SchemaObject>
/// Returns whether there exists a object of given type with this name
/// (case-insensitive).
+2 -16
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension Database {
@@ -370,11 +361,6 @@ public class SQLStatementCursor {
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension SQLStatementCursor: Sendable { }
extension SQLStatementCursor: Cursor {
public func next() throws -> Statement? {
guard offset < cString.count - 1 /* trailing \0 */ else {
@@ -387,7 +373,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<Int8>? = nil
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
@@ -547,7 +533,7 @@ struct StatementCache {
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
#else
let statement: Statement
if #available(macOS 10.14, *) { // SQLite 3.20+
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
} else {
statement = try db.makeStatement(sql: sql)
+127 -299
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -15,7 +6,7 @@ public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// An SQLite connection.
///
@@ -69,28 +60,16 @@ nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPatter
/// - ``inSavepoint(_:)``
/// - ``inTransaction(_:_:)``
/// - ``isInsideTransaction``
/// - ``readOnly(_:)``
/// - ``rollback()``
/// - ``transactionDate``
/// - ``TransactionCompletion``
/// - ``TransactionKind``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Database Observation
///
/// - ``add(transactionObserver:extent:)``
/// - ``remove(transactionObserver:)``
/// - ``afterNextTransaction(onCommit:onRollback:)``
/// - ``notifyChanges(in:)``
/// - ``registerAccess(to:)``
///
/// ### Collations
@@ -122,15 +101,8 @@ nonisolated(unsafe) let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPatter
/// - ``logError``
/// - ``releaseMemory()``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
///
/// - ``BusyCallback``
/// - ``BusyMode``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``LogErrorFunction``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
@@ -139,6 +111,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - SQLite C API
// TODO: make it non optional, since one can't get a `Database` instance
// after `close()`.
/// The raw SQLite connection, suitable for the SQLite C API.
///
/// The result is nil after the database has been successfully closed with
@@ -149,26 +123,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// SQLite can be configured to invoke a callback function containing
/// an error code and a terse error message whenever anomalies occur.
///
/// This global error callback must be configured early in the lifetime
/// of your application:
///
/// ```swift
/// Database.logError = { (resultCode, message) in
/// NSLog("%@", "SQLite error \(resultCode): \(message)")
/// }
/// ```
///
/// - warning: Database.logError must be set before any database
/// connection is opened. This includes the connections that your
/// application opens with GRDB, but also connections opened by
/// other tools, such as third-party libraries. Setting it after a
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -316,7 +272,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
var isInsideTransactionBlock = false
/// Support for `checkForSuspensionViolation(from:)`
let isSuspendedMutex = Mutex(false)
@LockedBox var isSuspended = false
/// Support for `checkForSuspensionViolation(from:)`
/// This cache is never cleared: we assume journal mode never changes.
@@ -465,41 +421,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
configuration.SQLiteConnectionDidOpen?()
}
/// Performs ``Configuration/JournalModeConfiguration/wal``.
func setUpWALMode() throws {
let journalMode = try String.fetchOne(self, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try execute(sql: "PRAGMA synchronous = NORMAL")
// Make sure a non-empty wal file exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// The non-empty wal file avoids an SQLITE_ERROR (1) error
// when the user opens a pool and creates a wal snapshot
// (which happens when starting a ValueObservation).
// See <https://github.com/groue/GRDB.swift/issues/1383>.
let walPath = path + "-wal"
if try FileManager.default.fileExists(atPath: walPath) == false
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
{
try inSavepoint {
try execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
return .commit
}
}
}
private func setupDoubleQuotedStringLiterals() {
if configuration.acceptsDoubleQuotedStringLiterals {
_enableDoubleQuotedStringLiterals(sqliteConnection)
@@ -806,38 +727,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Executes read-only database operations, and returns their result
/// after they have finished executing.
///
/// Attempts to write throw a ``DatabaseError`` with
/// resultCode `SQLITE_READONLY`.
///
/// For example:
///
/// ```swift
/// try dbQueue.write do { db in
/// // Write OK
/// try Player(...).insert(db)
///
/// try db.readOnly {
/// // Read OK
/// let players = try Player.fetchAll(db)
///
/// // Throws SQLITE_READONLY
/// try Player(...).insert(db)
/// }
/// }
/// ```
///
/// This method is reentrant.
///
/// - parameter value: A closure that reads from the database.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `value`.
public func readOnly<T>(_ value: () throws -> T) throws -> T {
/// Grants read-only access in the wrapped closure.
func readOnly<T>(_ block: () throws -> T) throws -> T {
try beginReadOnly()
return try throwingFirstError(
execute: value,
execute: block,
finally: endReadOnly)
}
@@ -882,65 +776,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Notifies that some changes were performed in the provided
/// database region.
///
/// This method makes it possible to notify undetected changes, such as
/// changes performed by another process, changes performed by
/// direct calls to SQLite C functions, or changes to the
/// database schema.
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// for a detailed list of undetected database modifications.
///
/// It triggers active transaction observers (``TransactionObserver``).
/// In particular, ``ValueObservation`` that observe the input `region`
/// will fetch and notify a fresh value.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // Notify observers that some changes were performed in the database
/// try db.notifyChanges(in: .fullDatabase)
///
/// // Notify observers that some changes were performed in the player table
/// try db.notifyChanges(in: Player.all())
///
/// // Equivalent alternative
/// try db.notifyChanges(in: Table("player"))
/// }
/// ```
///
/// This method has no effect when called from a read-only
/// database access.
///
/// > Caveat: Individual rowids in the input region are ignored.
/// > Notifying a change to a specific rowid is the same as notifying a
/// > change in the whole table:
/// >
/// > ```swift
/// > try dbQueue.write { db in
/// > // Equivalent
/// > try db.notifyChanges(in: Player.all())
/// > try db.notifyChanges(in: Player.filter(id: 1))
/// > }
/// > ```
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
// Don't do anything when read-only, because read-only transactions
// are not notified. We don't want to notify transactions observers
// of changes, and have them wait for a commit notification that
// will never come.
if !isReadOnly, let observationBroker {
let eventKinds = try region
.databaseRegion(self)
// Use canonical table names for case insensitivity of the input.
.canonicalTables(self)
.impactfulEventKinds(self)
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
}
}
/// Extends the `region` argument with the database region selected by all
/// statements executed by the closure, and all regions explicitly tracked
/// with the ``registerAccess(to:)`` method.
@@ -1025,16 +860,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
self.trace = trace
if options.isEmpty || trace == nil {
#if os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
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
#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
}
// Precondition: configuration.trace != nil
@@ -1042,7 +892,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
_ mask: CInt,
_ p: UnsafeMutableRawPointer?,
_ x: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?)
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
{
guard let trace else { return }
@@ -1050,22 +900,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if !os(Linux)
trace(TraceEvent.profile(statement: statement, duration: duration))
#endif
}
default:
break
@@ -1147,25 +1001,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// Suspension ends with `resume()`.
func suspend() {
let needsInterrupt = isSuspendedMutex.withLock { isSuspended in
$isSuspended.update { isSuspended in
if isSuspended {
return false
return
}
// Prevent future lock acquisition
isSuspended = true
return true
}
if needsInterrupt {
// Interrupting the database can trigger an SQLITE_INTERRUPT
// error which may itself abort a transaction and
// release a database lock, which is our goal.
// See <https://www.sqlite.org/c3ref/interrupt.html>
//
// Maybe interrupt will not release any lock. To address this,
// we'll issue a rollback on next database access which requires
// a lock. See `checkForSuspensionViolation(from:).`
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
interrupt()
// Now what about the eventual remaining lock? We'll issue a
// rollback on next database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
@@ -1177,7 +1028,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See suspend().
func resume() {
isSuspendedMutex.value = false
isSuspended = false
}
/// Support for `checkForSuspensionViolation(from:)`
@@ -1207,9 +1058,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
func checkForSuspensionViolation(from statement: Statement) throws {
let needsAbort = try isSuspendedMutex.withLock { isSuspended in
try $isSuspended.read { isSuspended in
guard isSuspended else {
return false
return
}
if try journalMode() == "wal" && statement.isReadonly {
@@ -1220,7 +1071,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return false
return
}
if statement.releasesDatabaseLock {
@@ -1229,14 +1080,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return false
return
}
// Assume statement can acquire a write lock: abort.
return true
}
if needsAbort {
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.suspend().
//
@@ -1294,7 +1140,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// For example:
///
/// ```swift
/// try dbQueue.writeWithoutTransaction do { db in
/// try dbQueue.writeWithoutTransaction do {
/// try db.inTransaction {
/// try db.execute(sql: "INSERT ...")
/// return .commit
@@ -1312,10 +1158,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Use ``inSavepoint(_:)`` instead.
///
/// - parameters:
/// - kind: The transaction type.
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// - operations: A function that executes SQL statements and returns
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
@@ -1439,7 +1289,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// By default, top level SQLite savepoints open a
// deferred transaction.
//
// But GRDB prefers immediate transactions for writes.
// But GRDB database configuration mandates a default transaction
// kind that we have to honor.
//
// Besides, starting some (?) SQLCipher/SQLite version, SQLite has a
// bug. Returning 1 from `sqlite3_commit_hook` does not leave the
@@ -1529,20 +1380,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// If nil, and the database connection is read-only, the transaction
/// kind is ``TransactionKind/deferred``.
///
/// If nil, and the database connection is not read-only, the
/// transaction kind is the ``Configuration/defaultTransactionKind``
/// of the ``configuration``.
/// - 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.
// We prefer immediate transactions for writes, so that write
// transactions can not overlap. This reduces the opportunity for
// SQLITE_BUSY, which is immediately thrown whenever a transaction
// is upgraded after an initial read and a concurrent processes
// has acquired the write lock beforehand. This SQLITE_BUSY error
// can not be avoided with a busy timeout.
//
// See <https://github.com/groue/GRDB.swift/issues/1483>.
let kind = kind ?? (isReadOnly ? .deferred : .immediate)
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
}
@@ -1769,11 +1616,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
@@ -1852,8 +1694,8 @@ extension Database {
// MARK: - Database-Related Types
/// See ``BusyMode`` and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
@@ -1881,7 +1723,7 @@ extension Database {
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode: Sendable {
public enum BusyMode {
/// The `SQLITE_BUSY` error is immediately returned to the connection
/// that tries to access the locked database.
case immediateError
@@ -1899,7 +1741,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt, Sendable {
public enum CheckpointMode: CInt {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1918,7 +1760,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable, Sendable {
public struct CollationName: RawRepresentable, Hashable {
public let rawValue: String
/// Creates a collation name.
@@ -1955,7 +1797,7 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable, Sendable {
public struct ColumnType: RawRepresentable, Hashable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
@@ -1967,14 +1809,6 @@ extension Database {
/// The `TEXT` column type.
public static let text = ColumnType(rawValue: "TEXT")
/// The `TEXT` column type, suitable for JSON columns.
///
/// SQLite JSON functions and operators are
/// [documented](https://www.sqlite.org/json1.html#interface_overview)
/// to throw errors if any of their arguments are binary blobs.
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
@@ -2006,7 +1840,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String, Sendable {
public enum ConflictResolution: String {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -2026,7 +1860,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String, Sendable {
public enum ForeignKeyAction: String {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -2041,33 +1875,7 @@ extension Database {
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct StorageClass: RawRepresentable, Hashable, Sendable {
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
public let rawValue: String
/// Creates an SQL storage class.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `INTEGER` storage class.
public static let integer = StorageClass(rawValue: "INTEGER")
/// The `REAL` storage class.
public static let real = StorageClass(rawValue: "REAL")
/// The `TEXT` storage class.
public static let text = StorageClass(rawValue: "TEXT")
/// The `BLOB` storage class.
public static let blob = StorageClass(rawValue: "BLOB")
}
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for the SQLite tracing feature.
///
@@ -2075,7 +1883,7 @@ extension Database {
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet, Sendable {
public struct TracingOptions: OptionSet {
/// The raw trace event code.
public let rawValue: CInt
@@ -2089,11 +1897,13 @@ extension Database {
/// Trace event code: `SQLITE_TRACE_STMT`.
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if !os(Linux)
/// The option that reports executed statements and the estimated
/// duration that the statement took to run.
///
/// Trace event code: `SQLITE_TRACE_PROFILE`.
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// A trace event.
@@ -2104,11 +1914,17 @@ extension Database {
/// Information about an executed statement.
public struct Statement: CustomStringConvertible {
var sqliteStatement: SQLiteStatement
var unexpandedSQL: UnsafePointer<CChar>?
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
}
var impl: Impl
#if !os(Linux)
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
@@ -2116,11 +1932,21 @@ extension Database {
/// ```sql
/// SELECT * FROM player WHERE email = ?
/// ```
public var sql: String {
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug: this api is not supposed to be available
fatalError("Unavailable statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
}
}
@@ -2136,18 +1962,30 @@ extension Database {
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
}
public var description: String {
if publicStatementArguments {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
} else {
return sql
case let .trace_v2(_, _, _, publicStatementArguments):
if publicStatementArguments {
return expandedSQL
} else {
return _sql
}
}
}
}
@@ -2208,7 +2046,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion: Sendable {
public enum TransactionCompletion {
case commit
case rollback
}
@@ -2216,7 +2054,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String, Sendable {
public enum TransactionKind: String {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
@@ -2249,13 +2087,3 @@ extension Database {
}
}
}
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent: Sendable { }
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent.Statement: Sendable { }
+1 -1
View File
@@ -1,7 +1,7 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress: Sendable {
public struct DatabaseBackupProgress {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
+3 -12
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
@@ -29,10 +20,10 @@ import Foundation
/// - ``localizedCompare``
/// - ``localizedStandardCompare``
/// - ``unicodeCompare``
public final class DatabaseCollation: Sendable {
public final class DatabaseCollation {
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -49,7 +40,7 @@ public final class DatabaseCollation: Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
+2 -19
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// An SQLite result code.
@@ -405,20 +396,12 @@ public struct DatabaseError: Error {
static func noSuchTable(_ tableName: String) -> Self {
DatabaseError(message: "no such table: \(tableName)")
}
static func noSuchSchema(_ schemaName: String) -> Self {
DatabaseError(message: "no such schema: \(schemaName)")
}
}
extension DatabaseError {
static func connectionIsClosed() -> Self {
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
}
static func snapshotIsLost() -> Self {
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
@@ -566,7 +549,7 @@ extension DatabaseError: CustomStringConvertible {
description += ": \(message)"
}
if let sql {
description += " - while executing `\(sql.trimmedSQLStatement)`"
description += " - while executing `\(sql)`"
}
if publicStatementArguments, let arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
@@ -594,7 +577,7 @@ extension DatabaseError: CustomStringConvertible {
description += ": \(message)"
}
if let sql {
description += " - while executing `\(sql.trimmedSQLStatement)`"
description += " - while executing `\(sql)`"
}
if let arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
+14 -34
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A custom SQL function or aggregate.
///
/// ## Topics
@@ -29,7 +20,7 @@ import SQLite3
/// - ``localizedUppercase``
/// - ``lowercase``
/// - ``uppercase``
public final class DatabaseFunction: Hashable, Sendable {
public final class DatabaseFunction: Hashable {
// SQLite identifies functions by (name + argument count)
private struct Identity: Hashable {
let name: String
@@ -39,9 +30,9 @@ public final class DatabaseFunction: Hashable, Sendable {
/// The name of the SQL function
public var name: String { identity.name }
private let identity: Identity
let isPure: Bool
let pure: Bool
private let kind: Kind
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Creates an SQL function.
///
@@ -82,11 +73,11 @@ public final class DatabaseFunction: Hashable, Sendable {
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function { (argc, argv) in
self.pure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
@@ -149,11 +140,10 @@ public final class DatabaseFunction: Hashable, Sendable {
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.pure = pure
self.kind = .aggregate { Aggregate() }
}
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
/// Returns an SQL expression that applies the function.
///
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
@@ -181,23 +171,13 @@ public final class DatabaseFunction: Hashable, Sendable {
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
switch kind {
case .function:
return .simpleFunction(
name,
arguments.map(\.sqlExpression),
isPure: isPure,
isJSONValue: false)
case .aggregate:
return .aggregateFunction(
name,
arguments.map(\.sqlExpression),
isDistinct: false,
ordering: nil,
filter: nil,
isJSONValue: false)
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
}
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: Database) {
@@ -274,12 +254,12 @@ public final class DatabaseFunction: Hashable, Sendable {
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
private enum Kind {
/// A regular function: SELECT f(1)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
case aggregate(() -> any DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
+96 -44
View File
@@ -11,10 +11,7 @@ public final class DatabasePool {
/// It is constant, until close() sets it to nil.
private var readerPool: Pool<SerializedDatabase>?
let databaseSnapshotCountMutex = Mutex(0)
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@LockedBox var databaseSnapshotCount = 0
// MARK: - Database Information
@@ -62,23 +59,52 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [readerConfiguration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(index)")
purpose: "reader.\(readerCount)")
})
// Set up journal mode unless readonly
// Activate WAL Mode unless readonly
if !configuration.readonly {
switch configuration.journalMode {
case .default, .wal:
try writer.sync {
try $0.setUpWALMode()
try writer.sync { db in
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try db.execute(sql: "PRAGMA synchronous = NORMAL")
// Make sure a non-empty wal file exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// The non-empty wal file avoids an SQLITE_ERROR (1) error
// when the user opens a pool and creates a wal snapshot
// (which happens when starting a ValueObservation).
// See <https://github.com/groue/GRDB.swift/issues/1383>.
let walPath = path + "-wal"
if try FileManager.default.fileExists(atPath: walPath) == false
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
{
try db.inSavepoint {
try db.execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
return .commit
}
}
}
}
@@ -95,9 +121,6 @@ public final class DatabasePool {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -116,6 +139,10 @@ public final class DatabasePool {
configuration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
@@ -142,7 +169,7 @@ public final class DatabasePool {
}
}
// @unchecked because of readerPool and suspensionObservers
// @unchecked because of databaseSnapshotCount and readerPool
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -251,9 +278,7 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
application.endBackgroundTask(task)
}
}
}
@@ -320,21 +345,29 @@ extension DatabasePool: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
center.addObserver(
self,
selector: #selector(DatabasePool.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.resume(_:)),
name: Database.resumeNotification,
object: nil)
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@@ -353,7 +386,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -397,7 +430,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -442,7 +475,25 @@ extension DatabasePool: DatabaseReader {
}
}
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, Error>? = nil
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -483,7 +534,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -622,7 +673,8 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
@@ -642,7 +694,7 @@ extension DatabasePool: DatabaseReader {
///
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void) {
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -733,7 +785,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -765,10 +817,9 @@ extension DatabasePool: DatabaseWriter {
///
/// - precondition: This method is not reentrant.
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
@@ -787,7 +838,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
}
@@ -845,10 +896,11 @@ extension DatabasePool {
path: path,
configuration: DatabasePool.readerConfiguration(writer.configuration),
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
purpose: "snapshot.\($databaseSnapshotCount.increment())")
}
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+1 -1
View File
@@ -1,5 +1,5 @@
#if canImport(Combine)
/// A namespace for database Combine publishers.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public enum DatabasePublishers { }
#endif
+45 -138
View File
@@ -7,15 +7,15 @@ import UIKit
public final class DatabaseQueue {
private let writer: SerializedDatabase
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Configuration
public var configuration: Configuration {
writer.configuration
}
/// The path to the database file.
///
/// The path is `:memory:` for in-memory databases.
public var path: String {
writer.path
}
@@ -47,18 +47,6 @@ public final class DatabaseQueue {
configuration: configuration,
defaultLabel: "GRDB.DatabaseQueue")
// Set up journal mode unless readonly
if !configuration.readonly {
switch configuration.journalMode {
case .default:
break
case .wal:
try writer.sync {
try $0.setUpWALMode()
}
}
}
setupSuspension()
// Be a nice iOS citizen, and don't consume too much memory
@@ -112,9 +100,6 @@ public final class DatabaseQueue {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -123,9 +108,6 @@ public final class DatabaseQueue {
}
}
// @unchecked because of suspensionObservers
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueue {
// MARK: - Memory management
@@ -169,9 +151,7 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
application.endBackgroundTask(task)
}
}
}
@@ -209,21 +189,29 @@ extension DatabaseQueue: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
center.addObserver(
self,
selector: #selector(DatabaseQueue.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.resume(_:)),
name: Database.resumeNotification,
object: nil)
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@@ -235,7 +223,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -260,7 +248,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -268,7 +256,20 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(_ value: (Result<Database, Error>) -> Void) {
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
// Check that we're on the writer queue, as documented
try writer.execute { db in
try db.isolated(readOnly: true) {
try value(db)
}
}
})
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -341,10 +342,9 @@ extension DatabaseQueue: DatabaseWriter {
/// ```
///
/// - parameters:
/// - kind: The transaction type (default nil).
///
/// If nil, the transaction kind is DEFERRED when the database
/// connection is read-only, and IMMEDIATE otherwise.
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is the ``Configuration/defaultTransactionKind`` of the
/// the ``configuration``.
/// - updates: A function that updates the database.
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
@@ -369,7 +369,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -415,100 +415,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
}
// MARK: - Temp Copy
extension DatabaseQueue {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The database memory is released when the returned connection
/// is deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.inMemoryCopy(fromPath: path)
/// ```
public static func inMemoryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. And SQLITE_OPEN_READONLY has no effect on in-memory
// databases anyway.
//
// So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
/// Returns a connection to a private, temporary, on-disk copy of the
/// database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The on-disk copy will be automatically deleted from disk as soon as
/// the returned connection is closed or deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.temporaryCopy(fromPath: path)
/// ```
public static func temporaryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
// <https://www.sqlite.org/c3ref/open.html>
// > If the filename is an empty string, then a private, temporary
// > on-disk database will be created. This private database will be
// > automatically deleted as soon as the database connection
// > is closed.
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(path: "", configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
}
+22 -41
View File
@@ -17,7 +17,6 @@ import Dispatch
/// ### Database Information
///
/// - ``configuration``
/// - ``path``
///
/// ### Reading from the Database
///
@@ -33,16 +32,6 @@ import Dispatch
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Other Database Operations
///
/// - ``backup(to:pagesPerStep:progress:)``
@@ -57,12 +46,6 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// The database configuration.
var configuration: Configuration { get }
/// The path to the database file.
///
/// In-memory databases also have a path:
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
var path: String { get }
/// Closes the database connection.
///
/// - note: You do not have to call this method, and you should not call
@@ -214,7 +197,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -285,7 +268,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -458,8 +441,8 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
@@ -504,8 +487,8 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -549,15 +532,17 @@ extension DatabaseReader {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter value: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping @Sendable (Database) throws -> Output)
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
}
.receiveValues(on: scheduler)
@@ -565,7 +550,7 @@ extension DatabaseReader {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that reads from the database.
///
@@ -584,7 +569,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
.init(upstream: eraseToAnyPublisher())
@@ -618,16 +603,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
let cancellable = AnyDatabaseCancellable()
var isCancelled = false
asyncRead { dbResult in
if cancellable.isCancelled { return }
guard !isCancelled else { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
if cancellable.isCancelled { return }
guard !isCancelled else { return }
do {
try onChange(result.get())
} catch {
@@ -635,7 +620,7 @@ extension DatabaseReader {
}
}
}
return cancellable
return AnyDatabaseCancellable(cancel: { isCancelled = true })
}
}
}
@@ -659,10 +644,6 @@ extension AnyDatabaseReader: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
@@ -676,7 +657,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -685,7 +666,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -756,7 +737,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
asyncRead(value)
}
}
+6 -44
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion: Sendable {
public struct DatabaseRegion {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
@@ -169,16 +169,16 @@ public struct DatabaseRegion: Sendable {
// the observed region, we optimize database observation.
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods. (TODO: is this comment still accurate?
// Isn't it about providing TransactionObserver.observes() with
// real tables names, instead?)
// `isModified` methods.
try ignoringInternalSQLiteTables().canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
/// Canonical names help the `isModified` methods.
///
/// This method removes views.
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
/// 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 else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
@@ -233,44 +233,6 @@ extension DatabaseRegion {
}
return tableRegion.contains(rowID: event.rowID)
}
/// Returns an array of all event kinds that can impact this region.
///
/// - precondition: the region is canonical.
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
if let tableRegions {
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
let tableName = table.rawValue // canonical table name
let columnNames: Set<String>
if let columns = tableRegion.columns {
columnNames = Set(columns.map(\.rawValue))
} else {
columnNames = try Set(db.columns(in: tableName).map(\.name))
}
return [
DatabaseEventKind.delete(tableName: tableName),
DatabaseEventKind.insert(tableName: tableName),
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
]
}
} else {
// full database
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
let columnNames = try Set(db.columns(in: table.name).map(\.name))
return [
DatabaseEventKind.delete(tableName: table.name),
DatabaseEventKind.insert(tableName: table.name),
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
]
}
}
}
}
}
extension DatabaseRegion: Equatable {
+8 -13
View File
@@ -89,16 +89,16 @@ extension DatabaseRegionObservation {
onChange: @escaping (Database) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@LockedBox var state = ObservationState.pending
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
writer.unsafeReentrantWrite { db in
do {
let region = try observedRegion(db).observableRegion(db)
stateMutex.withLock { state in
$state.update {
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = stateMutex.value {
if case .cancelled = state {
return
}
onChange($0)
@@ -111,7 +111,7 @@ extension DatabaseRegionObservation {
// the observer.
db.add(transactionObserver: observer, extent: .observerLifetime)
state = .started(observer)
$0 = .started(observer)
}
} catch {
onError(error)
@@ -122,13 +122,13 @@ extension DatabaseRegionObservation {
// Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent.
stateMutex.value = .cancelled
state = .cancelled
}
}
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabaseRegionObservation {
// MARK: - Publishing Impactful Transactions
@@ -140,7 +140,7 @@ extension DatabaseRegionObservation {
///
/// Do not reschedule the publisher with `receive(on:options:)` or any
/// `Publisher` method that schedules publisher elements.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
DatabasePublishers.DatabaseRegion(self, in: writer)
}
@@ -161,11 +161,6 @@ private class DatabaseRegionObserver: TransactionObserver {
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange() {
isChanged = true
stopObservingDatabaseChangesUntilNextTransaction()
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
isChanged = true
@@ -186,7 +181,7 @@ private class DatabaseRegionObserver: TransactionObserver {
}
#if canImport(Combine)
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that tracks transactions that modify a database region.
///
+8 -8
View File
@@ -59,14 +59,10 @@ import Dispatch
/// let snapshot2 = try dbPool.makeSnapshot()
///
/// // Guaranteed to be zero
/// let count1 = try snapshot1.read { db in
/// try Player.fetchCount(db)
/// }
/// let count1 = try snapshot1.read(Player.fetchCount)
///
/// // Could be anything
/// let count2 = try snapshot2.read { db in
/// try Player.fetchCount(db)
/// }
/// let count2 = try snapshot2.read(Player.fetchCount)
/// ```
///
/// `DatabaseSnapshot` inherits its database access methods from the
@@ -126,6 +122,10 @@ public final class DatabaseSnapshot {
// DatabaseSnapshot is read-only.
configuration.readonly = true
// DatabaseSnapshot uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshot keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -150,7 +150,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -158,7 +158,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
reader.async { value(.success($0)) }
}
+20 -23
View File
@@ -1,13 +1,5 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
///
@@ -112,9 +104,7 @@ public final class DatabaseSnapshotPool {
///
/// // Later... Maybe some players have been created.
/// // The snapshot is guaranteed to see an empty table of players, though:
/// let count = try snapshot.read { db in
/// try Player.fetchCount(db)
/// }
/// let count = try snapshot.read(Player.fetchCount)
/// assert(count == 0)
/// ```
///
@@ -130,7 +120,6 @@ public final class DatabaseSnapshotPool {
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
// Acquire and hold WAL snapshot
@@ -139,7 +128,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -159,18 +148,20 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = path
self.path = db.path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [configuration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
path: db.path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(index)")
purpose: "snapshot.\(readerCount)")
})
}
@@ -218,15 +209,17 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: { [configuration] index in
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(index)")
purpose: "snapshot.\(readerCount)")
})
}
@@ -239,6 +232,10 @@ public final class DatabaseSnapshotPool {
// DatabaseSnapshotPool is read-only.
configuration.readonly = true
// DatabaseSnapshotPool uses deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
configuration.defaultTransactionKind = .deferred
// DatabaseSnapshotPool keeps a long-lived transaction.
configuration.allowsUnsafeTransactions = true
@@ -293,7 +290,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -318,7 +315,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return try reader.reentrantSync { db in
let result = try value(db)
if snapshotIsLost(db) {
throw DatabaseError.snapshotIsLost()
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
}
return result
}
+1 -11
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A value stored in a database table.
@@ -53,7 +44,6 @@ import Foundation
/// ### Creating a DatabaseValue
///
/// - ``init(value:)``
/// - ``init(sqliteStatement:index:)``
/// - ``null``
///
/// ### Accessing the SQLite storage
@@ -159,7 +149,7 @@ public struct DatabaseValue: Hashable {
}
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
init(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
+39 -67
View File
@@ -1,5 +1,3 @@
import Foundation
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
// `DatabaseValueConvertible`, on purpose.
//
@@ -61,18 +59,6 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
///
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromMissingColumn() -> Self?
/// Returns the `JSONDecoder` that decodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Decodable` protocol.
static func databaseJSONDecoder() -> JSONDecoder
/// Returns the `JSONEncoder` that encodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Encodable` protocol.
static func databaseJSONEncoder() -> JSONEncoder
}
extension DatabaseValueConvertible {
@@ -89,60 +75,50 @@ extension DatabaseValueConvertible {
public static func fromMissingColumn() -> Self? {
nil // failure.
}
/// Returns the `JSONDecoder` that decodes the value.
///
/// The default implementation returns a `JSONDecoder` with the
/// following properties:
///
/// - `dataDecodingStrategy`: `.base64`
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatDecodingStrategy`: `.throw`
public static func databaseJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return decoder
}
/// Returns the `JSONEncoder` that encodes the value.
///
/// The default implementation returns a `JSONEncoder` with the
/// following properties:
///
/// - `dataEncodingStrategy`: `.base64`
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatEncodingStrategy`: `.throw`
/// - `outputFormatting`: `.sortedKeys`
public static func databaseJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
return encoder
}
}
// MARK: - Conversions
extension DatabaseValueConvertible {
@inlinable
public static func _decode(
databaseValue: DatabaseValue,
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
if let value = fromDatabaseValue(databaseValue) {
static func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromDatabaseValue(dbValue) {
return value
} else {
throw RowDecodingError.valueMismatch(
Self.self,
context: context(),
databaseValue: databaseValue)
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
}
}
static func decode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
return try decode(fromDatabaseValue: dbValue, context: context())
}
@usableFromInline
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
if let sqliteStatement = row.sqliteStatement {
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
@usableFromInline
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
try Optional<Self>.decode(fromRow: row, atUncheckedIndex: index)
}
}
// MARK: - Cursors
@@ -190,17 +166,13 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value._decode(
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex),
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
try Value.decode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension DatabaseValueCursor: Sendable { }
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
+126 -61
View File
@@ -38,7 +38,9 @@ import Dispatch
///
/// ### Reading from the Latest Committed Database State
///
/// - ``concurrentRead(_:)``
/// - ``spawnConcurrentRead(_:)``
/// - ``DatabaseFuture``
///
/// ### Unsafe Methods
///
@@ -179,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -211,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -249,6 +251,49 @@ public protocol DatabaseWriter: DatabaseReader {
// MARK: - Reading from Database
/// Schedules read-only database operations for execution, and returns a
/// future value.
///
/// This method must be called from the writer dispatch queue, outside of
/// any transaction. You'll get a fatal error otherwise.
///
/// Database operations performed by the `value` closure are isolated in a
/// transaction: they do not see changes performed by eventual concurrent
/// writes (even writes performed by other processes).
///
/// They see the database in the state left by the last updates performed
/// by the database writer.
///
/// To access the fetched results, you call the ``DatabaseFuture/wait()``
/// method of the returned future, on any dispatch queue.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet the future is guaranteed to return zero:
///
/// ```swift
/// try writer.writeWithoutTransaction { db in
/// // Delete all players
/// try Player.deleteAll()
///
/// // Count players concurrently
/// let future = writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
///
/// // Insert a player
/// try Player(...).insert(db)
///
/// // Guaranteed to be zero
/// let count = try future.wait()
/// }
/// ```
///
/// - note: Usage of this method is discouraged, because waiting on the
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
///
@@ -295,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
}
extension DatabaseWriter {
@@ -381,8 +426,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -400,21 +445,10 @@ extension DatabaseWriter {
// MARK: - Transaction Observers
/// Adds a transaction observer to the writer connection, so that it
/// gets notified of database changes and transactions.
/// Adds a transaction observer, so that it gets notified of
/// database changes and transactions.
///
/// This method waits until all currently executing database accesses
/// performed by the writer dispatch queue finish executing.
/// At that point, database observation begins.
///
/// It has no effect on read-only database connections.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.add(transactionObserver: myObserver)
/// ```
/// 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
@@ -427,18 +461,7 @@ extension DatabaseWriter {
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Removes a transaction observer from the writer connection.
///
/// This method waits until all currently executing database accesses
/// performed by the writer dispatch queue finish executing.
/// At that point, database observation stops.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.remove(transactionObserver: myObserver)
/// ```
/// Removes a transaction observer.
public func remove(transactionObserver: some TransactionObserver) {
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
}
@@ -496,7 +519,7 @@ extension DatabaseWriter {
///
/// - Parameter filePath: file path for new database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@available(iOS 14, macOS 10.16, tvOS 14, *)
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -562,8 +585,8 @@ extension DatabaseWriter {
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
/// would happen while establishing the database access or committing
/// the transaction.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -600,8 +623,8 @@ extension DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -652,9 +675,9 @@ extension DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @escaping @Sendable (Database) throws -> T)
_ updates: @Sendable @escaping (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -667,7 +690,7 @@ extension DatabaseWriter {
/// Erase the database: delete all content, drop all tables, etc.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func erase() async throws {
try await writeWithoutTransaction { try $0.erase() }
}
@@ -678,7 +701,7 @@ extension DatabaseWriter {
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum() async throws {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
@@ -695,7 +718,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -710,7 +733,7 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
@@ -755,10 +778,10 @@ extension DatabaseWriter {
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which accesses the database.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> Output)
updates: @escaping (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -772,7 +795,6 @@ extension DatabaseWriter {
.eraseToWritePublisher()
}
// TODO: GRDB7 Can SE-0430 avoid the T: Sendable constraint?
/// Returns a publisher that publishes one value and completes.
///
/// The database is not accessed until subscription. Value and completion
@@ -821,13 +843,13 @@ extension DatabaseWriter {
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler, T: Sendable
where S: Scheduler
{
OnDemandFuture { fulfill in
self.asyncWriteWithoutTransaction { db in
@@ -841,7 +863,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { [updatesValue] dbResult in
self.spawnConcurrentRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -853,7 +875,7 @@ extension DatabaseWriter {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that writes into the database.
///
@@ -872,7 +894,7 @@ extension DatabasePublishers {
}
}
@available(iOS 13, macOS 10.15, tvOS 13, *)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
.init(upstream: self.eraseToAnyPublisher())
@@ -880,6 +902,49 @@ extension Publisher where Failure == Error {
}
#endif
/// A future database value.
///
/// You get instances of `DatabaseFuture` from the `DatabaseWriter`
/// ``DatabaseWriter/concurrentRead(_:)`` method. For example:
///
/// ```swift
/// let futureCount: Future<Int> = try writer.writeWithoutTransaction { db in
/// try Player(...).insert()
///
/// // Count players concurrently
/// return writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
/// }
///
/// let count: Int = try futureCount.wait()
/// ```
public class DatabaseFuture<Value> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
_wait = wait
}
init(_ result: Result<Value, Error>) {
_wait = result.get
}
/// Blocks the current thread until the value is available, and returns it.
///
/// It is a programmer error to call this method several times.
///
/// - throws: Any error that prevented the value from becoming available.
public func wait() throws -> Value {
// Not thread-safe and quick and dirty.
// Goal is that users learn not to call this method twice.
GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once")
consumed = true
return try _wait()
}
}
/// A type-erased database writer.
///
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
@@ -899,10 +964,6 @@ extension AnyDatabaseWriter: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
@@ -916,7 +977,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncRead(value)
}
@@ -925,7 +986,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -957,11 +1018,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -969,7 +1030,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
-8
View File
@@ -1,8 +0,0 @@
//#warning("TODO: document")
//struct DetachedRow {
//
//}
//
//extension DetachedRow: Row {
//
//}
+2 -30
View File
@@ -107,28 +107,6 @@ extension FetchRequest {
// MARK: - PreparedRequest
/// A closure executed before a supplementary fetch is performed.
///
/// Support for `Database.dumpRequest`.
///
/// - parameter request: The supplementary request
/// - parameter keyPath: The key path target of the supplementary fetch.
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
/// A closure that performs supplementary fetches.
///
/// Support for eager loading of hasMany associations.
///
/// - parameter db: A database connection.
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch = (
_ db: Database,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
/// A prepared statement with bound parameters.
@@ -137,14 +115,13 @@ public struct PreparedRequest {
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
init(
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
{
self.statement = statement
self.adapter = adapter
@@ -152,11 +129,6 @@ public struct PreparedRequest {
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
// MARK: - AdaptedFetchRequest
+976 -141
View File
File diff suppressed because it is too large. Load diff
+10 -10
View File
@@ -83,7 +83,7 @@ import Foundation
/// }
///
/// extension PlayerInfo: FetchableRecord {
/// init(row: some RowProtocol) {
/// init(row: Row) {
/// player = row["player"]
/// team = row["team"]
/// }
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter: Sendable {
public protocol RowAdapter {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -378,7 +378,7 @@ extension RowAdapter {
///
/// This limit adapter may turn out useful in some narrow use cases. You'll
/// be happy to find it when you need it.
public struct EmptyRowAdapter: RowAdapter, Sendable {
public struct EmptyRowAdapter: RowAdapter {
/// Creates an `EmptyRowAdapter`.
public init() { }
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter, Sendable {
///
/// Note that columns that are not present in the dictionary are not present
/// in the resulting adapted row.
public struct ColumnMapping: RowAdapter, Sendable {
public struct ColumnMapping: RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter, Sendable {
/// // [c:2, d: 3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
/// ```
public struct SuffixRowAdapter: RowAdapter, Sendable {
public struct SuffixRowAdapter: RowAdapter {
/// The suffix index
let index: Int
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter, Sendable {
/// // [b:1 c:2]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
/// ```
public struct RangeRowAdapter: RowAdapter, Sendable {
public struct RangeRowAdapter: RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: @Sendable (String) -> String
let transform: (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping @Sendable (String) -> String) {
public init(_ transform: @escaping (String) -> String) {
self.transform = transform
}
@@ -698,7 +698,7 @@ struct AdaptedRowImpl: RowImpl {
var count: Int { mapping._layoutColumns.count }
var isFetched: Bool { base._isFetched }
var isFetched: Bool { base.isFetched }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
Row.ScopesView(row: base, scopes: adapter._scopes, prefetchedRows: prefetchedRows)
@@ -720,7 +720,7 @@ struct AdaptedRowImpl: RowImpl {
throws -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try base._fastDecode(Value.self, atUncheckedIndex: mappedIndex)
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
}
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
+33 -23
View File
@@ -1,14 +1,6 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A key that is used to decode a value in a row
public enum _RowKey: Hashable, Sendable {
@usableFromInline
enum RowKey: Hashable, Sendable {
/// A column name
case columnName(String)
@@ -37,7 +29,7 @@ enum RowDecodingError: Error {
var row: Row { Row(impl: rowImpl) }
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
let key: _RowKey?
let key: RowKey?
/// The SQL query
let sql: String?
@@ -45,7 +37,7 @@ enum RowDecodingError: Error {
/// The SQL query arguments
let statementArguments: StatementArguments?
init(decodingContext: _RowDecodingContext, debugDescription: String) {
init(decodingContext: RowDecodingContext, debugDescription: String) {
self.debugDescription = debugDescription
self.rowImpl = ArrayRowImpl(columns: decodingContext.row)
self.key = decodingContext.key
@@ -54,7 +46,7 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(_RowKey, Context)
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var context: Context {
@@ -67,10 +59,9 @@ enum RowDecodingError: Error {
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
@usableFromInline
static func valueMismatch(
_ type: Any.Type,
context: _RowDecodingContext,
context: RowDecodingContext,
databaseValue: DatabaseValue)
-> Self
{
@@ -88,7 +79,7 @@ enum RowDecodingError: Error {
_ type: Any.Type,
sqliteStatement: SQLiteStatement,
index: CInt,
context: _RowDecodingContext)
context: RowDecodingContext)
-> Self
{
valueMismatch(
@@ -107,14 +98,14 @@ enum RowDecodingError: Error {
{
valueMismatch(
type,
context: _RowDecodingContext(statement: statement, index: index),
context: RowDecodingContext(statement: statement, index: index),
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: CInt(index)))
}
/// Convenience method that builds the `column not found: <column>`
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: _RowDecodingContext) -> Self {
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
@@ -123,20 +114,39 @@ enum RowDecodingError: Error {
}
}
public struct _RowDecodingContext {
@usableFromInline
struct RowDecodingContext {
/// The row that is decoded
let row: Row
let key: _RowKey?
let key: RowKey?
/// The SQL query
let sql: String?
/// The SQL query arguments
let statementArguments: StatementArguments?
}
extension _RowDecodingContext {
@usableFromInline
init(row: Row, key: RowKey? = nil) {
if let statement = row.statement {
self.key = key
self.row = row.copy()
self.sql = statement.sql
self.statementArguments = statement.arguments
} else if let sqliteStatement = row.sqliteStatement {
self.key = key
self.row = row.copy()
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
self.statementArguments = nil // Can't rebuild them
} else {
self.key = key
self.row = row.copy()
self.sql = nil
self.statementArguments = nil
}
}
/// Convenience initializer
@usableFromInline
init(statement: Statement, index: Int) {
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -39,7 +39,9 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
public struct SQL: Sendable {
/// - ``Swift/Collection/joined(separator:)``
/// - ``Swift/Sequence/joined(separator:)``
public struct SQL {
/// `SQL.Element` is a component of an `SQL` literal.
///
/// Elements can be qualified with table aliases, and this is how `SQL`
@@ -316,12 +318,12 @@ extension SQL: SQLOrderingTerm {
}
extension Sequence where Element == SQL {
/// Returns the concatenated `SQL` literal of this sequence of literals,
/// Concatenates the sequence elements into a new `SQL` literal,
/// inserting the given raw SQL separator between each element.
///
/// For example:
///
/// ```
/// ```swift
/// let components: [SQL] = [
/// "UPDATE player",
/// "SET name = \(name)",
@@ -341,7 +343,7 @@ extension Sequence where Element == SQL {
}
extension Collection where Element == SQL {
/// Returns the concatenated `SQL` literal of this collection of literals,
/// Concatenates the collection elements into a new `SQL` literal,
/// inserting the given raw SQL separator between each element.
///
/// For example:
+1 -1
View File
@@ -22,7 +22,7 @@ import Dispatch
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
nonisolated(unsafe) private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
var databaseObservationBroker: DatabaseObservationBroker?
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping @Sendable (Database) -> Void) {
func async(_ block: @escaping (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+9 -24
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -51,15 +42,14 @@ public final class Statement {
public var sql: String {
SchedulingWatchdog.preconditionValidQueue(database)
// trim white space and semicolon for homogeneous output
// trim white space and semicolumn for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
// swiftlint:disable:next redundant_self_in_closure
let sqliteStatement = self.sqliteStatement
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
return (0..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
// The database region is reported by `sqlite3_set_authorizer`, and maybe
@@ -100,8 +90,8 @@ public final class Statement {
sqlite3_stmt_readonly(sqliteStatement) != 0
}
/// A boolean value indicating if the statement can delete some rows.
var canDeleteRows: Bool {
/// A boolean value indicating if the statement deletes some rows.
var isDeleteStatement: Bool {
authorizerEventKinds.contains(where: \.isDelete)
}
@@ -111,7 +101,7 @@ public final class Statement {
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
Dictionary(
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
@@ -128,8 +118,8 @@ public final class Statement {
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<CChar>,
statementEnd: UnsafeMutablePointer<UnsafePointer<CChar>?>,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: CUnsignedInt) throws
{
SchedulingWatchdog.preconditionValidQueue(database)
@@ -146,7 +136,7 @@ public final class Statement {
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
#else
if #available(macOS 10.14, *) { // SQLite 3.20+
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -232,7 +222,7 @@ public final class Statement {
private var _arguments = StatementArguments()
lazy var sqliteArgumentCount: Int = {
Int(sqlite3_bind_parameter_count(sqliteStatement))
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
}()
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
@@ -632,11 +622,6 @@ public final class Statement {
}
}
// Explicit non-conformance to Sendable: statements must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension Statement: Sendable { }
extension Statement: CustomStringConvertible {
public var description: String {
SchedulingWatchdog.allows(database) ? sql : "Statement"
+4 -13
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if os(Linux)
import Glibc
#endif
@@ -66,10 +57,10 @@ final class StatementAuthorizer {
private func authorize(
_ actionCode: CInt,
_ cString1: UnsafePointer<CChar>?,
_ cString2: UnsafePointer<CChar>?,
_ cString3: UnsafePointer<CChar>?,
_ cString4: UnsafePointer<CChar>?)
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
-> CInt
{
// Uncomment when debugging
+58 -31
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
///
@@ -32,7 +23,7 @@ import SQLite3
/// var name: String
/// var score: Int
///
/// init(row: some RowProtocol) {
/// init(row: Row) {
/// // Optimized
/// name = row["name"]
/// score = row["score"]
@@ -136,21 +127,62 @@ extension StatementColumnConvertible {
// MARK: - Conversions
extension StatementColumnConvertible {
@inlinable
public static func _fastDecode(
sqliteStatement: SQLiteStatement,
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@usableFromInline
/* private */ static func _valueMismatch(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> _RowDecodingContext
) throws -> Self {
guard let value = fromStatement(sqliteStatement, atUncheckedIndex: index) else {
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
context: @autoclosure () -> RowDecodingContext)
throws -> Never
{
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
@inline(__always)
@inlinable
static func fastDecode(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return value
// Support for fast decoding from adapted rows
return try row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(__always)
@inlinable
static func fastDecode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) {
return value
} else {
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
}
// Support for Decodable
@inline(__always)
@inlinable
static func fastDecodeIfPresent(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self?
{
try Optional<Self>.fastDecode(fromRow: row, atUncheckedIndex: index)
}
}
@@ -202,18 +234,13 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@inlinable
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value._fastDecode(
sqliteStatement: sqliteStatement,
try Value.fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: _RowDecodingContext(statement: _statement, index: Int(columnIndex)))
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension FastDatabaseValueCursor: Sendable { }
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
-152
View File
@@ -1,152 +0,0 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#warning("TODO: document")
final class StatementRow {
private let statement: Statement
private let sqliteStatement: SQLiteStatement
private let lowercaseColumnIndexes: [String: Int]
init(statement: Statement) {
let sqliteStatement = statement.sqliteStatement
self.statement = statement
self.sqliteStatement = sqliteStatement
// Optimize index(forColumn:)
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
.map { ($0.element, $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
}
extension StatementRow: RowProtocol {
typealias Index = RowIndex
typealias Element = (String, DatabaseValue)
var prefetchedRows: Row.PrefetchedRowsView {
Row.PrefetchedRowsView()
}
#warning("TODO: wrong return type")
func copy() -> Row {
Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
}
func _decode<Strategy: _RowDecodingStrategy>(
with strategy: Strategy,
atUncheckedIndex index: Int
) throws -> Strategy._RowDecodingOutput
{
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Strategy._RowDecodingOutput.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
return try strategy._decode(
sqliteStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
func _decode<Value: DatabaseValueConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int
) throws -> Value
{
try Value._decode(
databaseValue: _databaseValue(atUncheckedIndex: index),
context: _makeRowDecodingContext(forKey: .columnIndex(index)))
}
func _fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int
) throws -> Value
{
try Value._fastDecode(
sqliteStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: _RowDecodingContext(statement: statement, index: index))
}
var _isFetched: Bool {
true
}
func _scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
Row.ScopesView()
}
func _columnName(atUncheckedIndex index: Int) -> String {
statement.columnNames[index]
}
func _hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL
}
func _databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
}
func _withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else {
return try body(nil)
}
guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else {
return try body(Data())
}
let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index)))
let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
return try body(data)
}
#warning("TODO: wrong return type")
var _unscopedRow: Row {
copy()
}
#warning("TODO: wrong return type")
var _unadaptedRow: Row {
copy()
}
#warning("TODO: wrong return type")
var _copiedRow: Row {
copy()
}
func _makeRowDecodingContext(forKey key: _RowKey?) -> _RowDecodingContext {
_RowDecodingContext(
row: copy(),
key: key,
sql: statement.sql,
statementArguments: statement.arguments)
}
func index(forColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercased()]
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
#if canImport(CoreGraphics)
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
/// `CGFloat` is a database value.
extension CGFloat: DatabaseValueConvertible {
/// Returns a REAL database value.
public var databaseValue: DatabaseValue {
+25 -10
View File
@@ -1,15 +1,6 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
/// `Data` is a database value.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
@@ -69,3 +60,27 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
}
}
// MARK: - Conversions
extension Data {
static func fastDecodeNoCopy(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
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, index) else {
return Data()
}
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
}
@@ -1,19 +1,10 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A database value that holds date components.
public struct DatabaseDateComponents: Sendable {
public struct DatabaseDateComponents {
/// The SQLite formats for date components.
public enum Format: String, Sendable {
public enum Format: String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -84,7 +75,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let components = cString.withMemoryRebound(
to: CChar.self,
to: Int8.self,
capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
}
+2 -13
View File
@@ -1,17 +1,7 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
/// `NSDate` is a database value.
extension NSDate: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -40,8 +30,6 @@ extension NSDate: DatabaseValueConvertible {
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -124,6 +112,7 @@ extension Date: DatabaseValueConvertible {
}
}
/// `Date` is a database value.
extension Date: StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+1 -10
View File
@@ -1,16 +1,7 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Decimal adopts DatabaseValueConvertible
/// `Decimal` is a database value.
extension Decimal: DatabaseValueConvertible {
/// Returns a TEXT decimal value.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
/// `NSData` is a database value.
extension NSData: DatabaseValueConvertible {
/// Returns a BLOB database value.
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// NSNull adopts DatabaseValueConvertible
/// `NSDate` is a database value.
extension NSNull: DatabaseValueConvertible {
/// Returns the NULL database value.
+1 -1
View File
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
/// NSNumber adopts DatabaseValueConvertible
/// `NSNumber` is a database value.
extension NSNumber: DatabaseValueConvertible {
/// A database value.
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
/// `NSString` is a database value.
extension NSString: DatabaseValueConvertible {
/// Returns a TEXT database value.
@@ -4,7 +4,6 @@ import Foundation
@usableFromInline
struct SQLiteDateParser {
// swiftlint:disable:next unneeded_synthesized_initializer
@usableFromInline
init() { }
+6 -2
View File
@@ -1,7 +1,9 @@
import Foundation
#if !os(Linux)
/// NSURL stores its absoluteString in the database.
/// `NSURL` is a database value.
///
/// `NSURL` stores its `absoluteString` in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
@@ -18,5 +20,7 @@ extension NSURL: DatabaseValueConvertible {
}
#endif
/// URL stores its absoluteString in the database.
/// `URL` is a database value.
///
/// `URL` stores its `absoluteString` in the database.
extension URL: DatabaseValueConvertible { }
+2 -11
View File
@@ -1,16 +1,7 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
#if !os(Linux)
/// NSUUID adopts DatabaseValueConvertible
/// `NSUUID` is a database value.
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -44,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
}
#endif
/// UUID adopts DatabaseValueConvertible
/// `UUID` is a database value.
extension UUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -179,7 +179,11 @@ extension DatabaseValueConvertible where Self: Decodable {
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
return try? databaseJSONDecoder().decode(Self.self, from: data)
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return try? decoder.decode(Self.self, from: data)
} catch {
return nil
}
@@ -2,7 +2,6 @@ import Foundation
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var codingPath: [any CodingKey] { [] }
@@ -43,21 +42,16 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue)
} else {
try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value)
try DatabaseValueEncoder(encode: encode).encode(value)
}
}
}
private class DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var requiresJSON = false
init(
jsonEncoder: JSONEncoder,
encode: @escaping (DatabaseValue) -> Void
) {
self.jsonEncoder = jsonEncoder
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
}
@@ -110,7 +104,7 @@ private class DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
DatabaseValueEncodingContainer(encode: encode)
}
func encode<T: Encodable>(_ value: T) throws {
@@ -121,7 +115,13 @@ private class DatabaseValueEncoder: Encoder {
throw JSONRequiredError()
}
} catch is JSONRequiredError {
let jsonData = try jsonEncoder.encode(value)
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// 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
// database inspection. Thanks to SQLite weak typing, we won't
@@ -138,11 +138,7 @@ private class DatabaseValueEncoder: Encoder {
extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
try! DatabaseValueEncoder(
jsonEncoder: Self.databaseJSONEncoder(),
encode: { dbValue = $0 }
)
.encode(self)
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
return dbValue
}
}
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch self {
@@ -53,6 +44,7 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
/// `Optional` is a database value when it wrapped type is.
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
switch self {
@@ -1,15 +1,6 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Bool` is a database value.
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -104,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int` is a database value.
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -143,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int8` is a database value.
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -182,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int16` is a database value.
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -221,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int32` is a database value.
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -260,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Int64` is a database value.
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -303,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt` is a database value.
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -342,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt8` is a database value.
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -381,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt16` is a database value.
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -420,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt32` is a database value.
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -459,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `UInt64` is a database value.
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -498,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Double` is a database value.
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -538,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `Float` is a database value.
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -578,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
/// `String` is a database value.
extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock: Sendable {
public protocol TransactionClock {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: @Sendable (Database) throws -> Date
let _now: (Database) throws -> Date
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
public init(_ now: @escaping (Database) throws -> Date) {
self._now = now
}
+24 -108
View File
@@ -1,30 +1,12 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
/// Adds a transaction observer on the database connection, so that it
/// gets notified of database changes and transactions.
/// Adds a transaction observer, so that it gets notified of
/// database changes and transactions.
///
/// This method has no effect on read-only database connections.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.write { db in
/// db.add(transactionObserver: myObserver)
/// }
/// ```
///
/// - parameter transactionObserver: A transaction observer.
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
@@ -38,30 +20,21 @@ extension Database {
// Drop cached statements that delete, because the addition of an
// observer may change the need for truncate optimization prevention.
publicStatementCache.removeAll { $0.canDeleteRows }
internalStatementCache.removeAll { $0.canDeleteRows }
publicStatementCache.removeAll { $0.isDeleteStatement }
internalStatementCache.removeAll { $0.isDeleteStatement }
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
}
/// Removes a transaction observer from the database connection.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.write { db in
/// db.remove(transactionObserver: myObserver)
/// }
/// ```
/// Removes a transaction observer.
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.canDeleteRows }
internalStatementCache.removeAll { $0.canDeleteRows }
publicStatementCache.removeAll { $0.isDeleteStatement }
internalStatementCache.removeAll { $0.isDeleteStatement }
observationBroker.remove(transactionObserver: transactionObserver)
}
@@ -144,7 +117,7 @@ extension Database {
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent: Sendable {
public enum TransactionObservationExtent {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
@@ -291,20 +264,6 @@ class DatabaseObservationBroker {
}
}
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
// Support for stopObservingDatabaseChangesUntilNextTransaction()
SchedulingWatchdog.current!.databaseObservationBroker = self
defer {
SchedulingWatchdog.current!.databaseObservationBroker = nil
}
for observation in transactionObservations where observation.isEnabled {
if eventKinds.contains(where: { observation.observes(eventsOfKind: $0) }) {
observation.databaseDidChange()
}
}
}
// MARK: - Statement execution
/// Returns true if there exists some transaction observer interested in
@@ -589,11 +548,6 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
//
// 2023-11-26: I'm glad we did, because that's how we support calls
// to `Database.notifyChanges(in:)` from an empty transaction, as a
// way to tell transaction observers about changes performed by some
// external connection.
do {
try databaseWillCommit()
@@ -810,16 +764,6 @@ public protocol TransactionObserver: AnyObject {
/// from being applied on the observed tables.
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// Called when the database was modified in some unspecified way.
///
/// This method allows a transaction observer to handle changes that are
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// and ``Database/notifyChanges(in:)`` for more information.
///
/// The exact nature of changes is unknown, but they comply to the
/// ``observes(eventsOfKind:)`` test.
func databaseDidChange()
/// Called when the database is changed by an insert, update, or
/// delete event.
///
@@ -834,8 +778,7 @@ public protocol TransactionObserver: AnyObject {
/// - note: The event is only valid for the duration of this method call.
/// If you need to keep it longer, store a copy: `event.copy()`.
///
/// - precondition: This method must not access the observed writer
/// database connection.
/// - precondition: This method must not access the database.
func databaseDidChange(with event: DatabaseEvent)
/// Called when a transaction is about to be committed.
@@ -843,8 +786,7 @@ public protocol TransactionObserver: AnyObject {
/// The transaction observer has an opportunity to rollback pending changes
/// by throwing an error from this method.
///
/// - precondition: This method must not access the observed writer
/// database connection.
/// - precondition: This method must not access the database.
/// - throws: The eventual error that rollbacks pending changes.
func databaseWillCommit() throws
@@ -895,15 +837,11 @@ extension TransactionObserver {
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// The default implementation does nothing.
public func databaseDidChange() { }
/// Prevents the observer from receiving further change notifications
/// until the next transaction.
/// Prevents the observer from receiving further change notifications until
/// the next transaction.
///
/// After this method has been called, the ``databaseDidChange(with:)``
/// and ``databaseDidChange()-7olv7`` methods won't be called until the
/// next transaction.
/// method won't be called until the next transaction.
///
/// For example:
///
@@ -916,13 +854,6 @@ extension TransactionObserver {
/// return eventKind.tableName == "player"
/// }
///
/// func databaseDidChange() {
/// playerTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playerTableWasModified = true
///
@@ -933,12 +864,12 @@ extension TransactionObserver {
/// ```
///
/// - precondition: This method must be called from
/// ``databaseDidChange(with:)`` or ``databaseDidChange()-7olv7``.
/// ``databaseDidChange(with:)``.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("""
stopObservingDatabaseChangesUntilNextTransaction must be called \
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
from the databaseDidChange method
""")
}
broker.disableUntilNextTransaction(transactionObserver: self)
@@ -991,11 +922,6 @@ final class TransactionObservation {
}
#endif
func databaseDidChange() {
guard isEnabled else { return }
observer?.databaseDidChange()
}
func databaseDidChange(with event: DatabaseEvent) {
guard isEnabled else { return }
observer?.databaseDidChange(with: event)
@@ -1065,7 +991,7 @@ struct StatementObservation {
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
/// ``TransactionObserver`` protocol for more information.
@frozen
public enum DatabaseEventKind: Sendable {
public enum DatabaseEventKind {
/// The insertion of a row in a database table.
case insert(tableName: String)
@@ -1118,7 +1044,7 @@ protocol DatabaseEventProtocol {
/// ``TransactionObserver`` protocol for more information.
public struct DatabaseEvent {
/// An event kind.
public enum Kind: CInt, Sendable {
public enum Kind: CInt {
/// An insertion event
case insert = 18 // SQLITE_INSERT
@@ -1167,12 +1093,7 @@ public struct DatabaseEvent {
self.impl = impl
}
init(
kind: Kind,
rowID: Int64,
databaseNameCString: UnsafePointer<CChar>?,
tableNameCString: UnsafePointer<CChar>?)
{
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(
kind: kind,
rowID: rowID,
@@ -1182,11 +1103,6 @@ public struct DatabaseEvent {
}
}
// Explicit non-conformance to Sendable: this type can't be made Sendable
// until GRDB7 where we can distinguish between a transient event and its copy.
@available(*, unavailable)
extension DatabaseEvent: Sendable { }
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
@@ -1213,8 +1129,8 @@ private protocol DatabaseEventImpl {
/// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName.
private struct MetalDatabaseEventImpl: DatabaseEventImpl {
let databaseNameCString: UnsafePointer<CChar>?
let tableNameCString: UnsafePointer<CChar>?
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
@@ -1349,8 +1265,8 @@ public struct DatabasePreUpdateEvent {
kind: Kind,
initialRowID: Int64,
finalRowID: Int64,
databaseNameCString: UnsafePointer<CChar>?,
tableNameCString: UnsafePointer<CChar>?)
databaseNameCString: UnsafePointer<Int8>?,
tableNameCString: UnsafePointer<Int8>?)
{
self.init(
kind: kind,
@@ -1406,8 +1322,8 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<CChar>?
let tableNameCString: UnsafePointer<CChar>?
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
+3 -13
View File
@@ -1,13 +1,5 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
@@ -29,9 +21,7 @@ import SQLite3
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
final class WALSnapshot: Sendable {
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
+27 -60
View File
@@ -1,30 +1,12 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
func commitAndRelease() {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
// TODO: consider using the serialized DispatchQueue of reader instead of a lock.
/// nil when closed
private let databaseAccessMutex: Mutex<DatabaseAccess?>
class WALSnapshotTransaction {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -55,71 +37,56 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
release: @escaping (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
let databaseAccess = DatabaseAccess(reader: reader, release: release)
do {
// Open a long-lived transaction, and enter snapshot isolation
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
return try WALSnapshot(db)
}
self.databaseAccessMutex = Mutex(databaseAccess)
self.reader = reader
self.release = release
} catch {
// self is not initialized, so deinit will not run.
databaseAccess.commitAndRelease()
Self.commitAndRelease(reader: reader, release: release)
throw error
}
}
deinit {
close()
Self.commitAndRelease(reader: reader, release: release)
}
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
}
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
return try databaseAccess.reader.sync(value)
}
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
try reader.sync(value)
}
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
return
}
databaseAccess.reader.async { db in
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
// At least check if self was closed:
if self.databaseAccessMutex.value == nil {
value(.failure(DatabaseError.snapshotIsLost()))
}
value(.success(db))
}
}
func asyncRead(_ value: @escaping (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
}
func close() {
databaseAccessMutex.withLock { databaseAccess in
databaseAccess?.commitAndRelease()
databaseAccess = nil
private static func commitAndRelease(
reader: SerializedDatabase,
release: (_ isInsideTransaction: Bool) -> Void)
{
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
}
}
#endif
+27 -2
View File
@@ -277,7 +277,31 @@ let newPlayerCount = try dbPool.write { db in
}
```
🔀 The solution is ``DatabasePool/asyncConcurrentRead(_:)``. It must be called from within a write access, outside of any transaction:
➡️ The synchronous solution is the ``DatabaseWriter/concurrentRead(_:)`` method. It must be called from within a write access, outside of any transaction. It returns a ``DatabaseFuture`` which you consume any time later, with the ``DatabaseFuture/wait()`` method:
```swift
let future: DatabaseFuture<Int> = try dbPool.writeWithoutTransaction { db in
// Increment the number of players
try db.inTransaction {
try Player(...).insert(db)
return .commit
}
// <- Not in a transaction here
return dbPool.concurrentRead { db
try Player.fetchCount(db)
}
}
do {
// Handle the new player count - guaranteed greater than zero
let newPlayerCount = try future.wait()
} catch {
// Handle error
}
```
🔀 The asynchronous version of `concurrentRead` is ``DatabasePool/asyncConcurrentRead(_:)``:
```swift
try dbPool.writeWithoutTransaction { db in
@@ -300,10 +324,11 @@ try dbPool.writeWithoutTransaction { db in
}
```
The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure.
Both ``DatabaseWriter/concurrentRead(_:)`` and ``DatabasePool/asyncConcurrentRead(_:)`` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure.
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
![DatabasePool Concurrent Read](DatabasePoolConcurrentRead.png)
Types that conform to ``TransactionObserver`` can also use those methods in their ``TransactionObserver/databaseDidCommit(_:)`` method, in order to process database changes without blocking other threads that want to write into the database.
@@ -20,20 +20,14 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas
- ``ValueObservation``
- ``SharedValueObservation``
- ``AsyncValueObservation``
- ``Database/registerAccess(to:)``
### Observing Database Transactions
- ``DatabaseRegionObservation``
- ``Database/afterNextTransaction(onCommit:onRollback:)``
### Low-Level Transaction Observers
- ``TransactionObserver``
- ``Database/add(transactionObserver:extent:)``
- ``Database/remove(transactionObserver:)``
- ``DatabaseWriter/add(transactionObserver:extent:)``
- ``DatabaseWriter/remove(transactionObserver:)``
- ``Database/TransactionObservationExtent``
### Database Regions
+21 -30
View File
@@ -1,7 +1,5 @@
# The Database Schema
Define or query the database schema.
## Overview
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
@@ -18,7 +16,7 @@ try db.create(table: "player") { t in
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
@@ -26,9 +24,7 @@ When a schema change is not directly supported by SQLite, or not available on th
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
### Table names should be English, singular, and camelCased
@@ -139,8 +135,8 @@ try db.create(table: "team") { t in
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.belongsTo("player")
t.belongsTo("team")
t.column("playerId", .integer).references("player")
t.column("teamId", .text).references("team")
}
t.column("role", .text).notNull()
}
@@ -167,6 +163,11 @@ struct Player: Codable {
var score: Int
}
extension Player: Identifiable {
// Required because the primary key column is not 'id'
var id: Int64? { rowid }
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
@@ -240,10 +241,10 @@ Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
t.column("teamId", .integer).notNull().references("team")
t.column("position", .integer).notNull()
}
// One single player at any given position in a team
@@ -306,7 +307,7 @@ try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.belongsTo("team").notNull()
t.column("teamId", .integer).notNull().references("team")
}
// REQUIRES EXTRA CONFIGURATION
@@ -318,8 +319,6 @@ try db.create(table: "player") { t in
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
@@ -373,35 +372,27 @@ extension Team: TableRecord {
- ``TableOptions``
- ``VirtualTableModule``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Querying the Database Schema
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/columns(in:)``
- ``Database/foreignKeys(on:)``
- ``Database/indexes(on:)``
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:in:)``
- ``Database/primaryKey(_:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
- ``Database/tableExists(_:)``
- ``Database/triggerExists(_:)``
- ``Database/viewExists(_:)``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -410,9 +401,9 @@ extension Team: TableRecord {
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/checkForeignKeys(in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``Database/foreignKeyViolations(in:)``
- ``ForeignKeyViolation``
### Sunsetted Methods
+7 -11
View File
@@ -21,13 +21,11 @@ We'll address all of those challenges below.
>
> Always consider sharing plain files, or any other inter-process communication technique, before sharing an SQLite database.
## Use the WAL mode
## Use a Database Pool
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently.
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database.
It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``.
Since several processes may open the database at the same time, protect the creation of the database connection with an [NSFileCoordinator].
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
@@ -156,9 +154,7 @@ configuration.busyMode = .timeout(/* a TimeInterval */)
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
The busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing. GRDB automatically opens all write transactions with the IMMEDIATE kind, preventing write transactions from overlapping.
With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
```swift
do {
@@ -230,7 +226,9 @@ In applications that use the background modes supported by iOS, post `resumeNoti
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter]. You can trigger those notifications automatically with ``DatabaseRegionObservation``:
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
```swift
// Notify all changes made to the database
@@ -246,8 +244,6 @@ let observer = try observation.start(in: dbPool) { db in
}
```
The processes that observe the database can catch those notifications, and deal with the notified changes. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> for some related techniques.
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[WAL mode]: https://www.sqlite.org/wal.html
@@ -83,13 +83,12 @@ do {
- ``acceptsDoubleQuotedStringLiterals``
- ``busyMode``
- ``foreignKeysEnabled``
- ``journalMode``
- ``readonly``
- ``JournalModeConfiguration``
### Configuring GRDB Connections
- ``allowsUnsafeTransactions``
- ``defaultTransactionKind``
- ``label``
- ``maximumReaderCount``
- ``observesSuspensionNotifications``
@@ -78,7 +78,8 @@ A `DatabasePool` needs your application to follow rules in order to deliver its
### Accessing the Database
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
access methods.
- ``asyncConcurrentRead(_:)``
- ``writeInTransaction(_:_:)``
@@ -88,12 +88,11 @@ A `DatabaseQueue` needs your application to follow rules in order to deliver its
- ``init(named:configuration:)``
- ``init(path:configuration:)``
- ``inMemoryCopy(fromPath:configuration:)``
- ``temporaryCopy(fromPath:configuration:)``
### Accessing the Database
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
access methods.
- ``inDatabase(_:)``
- ``inTransaction(_:_:)``
@@ -6,7 +6,11 @@
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
The only changes that are not notified are:
- Changes performed by external database connections.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
@@ -74,30 +78,6 @@ let observation = DatabaseRegionObservation(
tracking: .fullDatabase)
```
## Dealing with Undetected Changes
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify such undetected changes, applications can take explicit action: call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
## Topics
### Creating DatabaseRegionObservation
@@ -74,14 +74,7 @@ extension Color: DatabaseValueConvertible { }
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
```swift
protocol DatabaseValueConvertible {
static func databaseJSONDecoder() -> JSONDecoder
static func databaseJSONEncoder() -> JSONEncoder
}
```
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
### Adding support for the Tagged library
@@ -151,11 +144,6 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``databaseValue-1ob9k``
### Configuring the JSON format for the standard Decodable protocol
- ``databaseJSONDecoder()-7zou9``
- ``databaseJSONEncoder()-37sff``
### Fetching Values from Raw SQL
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
@@ -177,6 +165,38 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``fetchSet(_:_:)-1foke``
- ``fetchOne(_:_:)-o6yj``
### Supported Value Types
- ``Swift/Bool``
- ``CoreFoundation/CGFloat``
- ``Foundation/Data``
- ``DatabaseDateComponents``
- ``Foundation/Date``
- ``Swift/Double``
- ``Foundation/Decimal``
- ``Swift/Float``
- ``Swift/Int``
- ``Swift/Int8``
- ``Swift/Int16``
- ``Swift/Int32``
- ``Swift/Int64``
- ``Foundation/NSData``
- ``Foundation/NSDate``
- ``Foundation/NSNull``
- ``Foundation/NSNumber``
- ``Foundation/NSString``
- ``Foundation/NSURL``
- ``Foundation/NSUUID``
- ``Swift/Optional``
- ``Swift/UInt``
- ``Swift/UInt8``
- ``Swift/UInt16``
- ``Swift/UInt32``
- ``Swift/UInt64``
- ``Swift/String``
- ``Foundation/URL``
- ``Foundation/UUID``
### Supporting Types
- ``DatabaseValueCursor``
@@ -25,7 +25,13 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
The only changes and transactions that are not notified are:
- Read-only transactions.
- Changes and transactions performed by external database connections.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
@@ -91,7 +97,7 @@ do {
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
## Filtering Database Events
@@ -183,7 +189,7 @@ class PlayerObserver: TransactionObserver {
}
```
## Support for SQLite Pre-Update Hooks
### Support for SQLite Pre-Update Hooks
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
@@ -229,41 +235,6 @@ This extra API can be activated in two ways:
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
## Dealing with Undetected Changes
The changes and transactions that are not automatically notified to transaction observers are:
- Read-only transactions.
- Changes and transactions performed by external database connections.
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
To notify undetected changes to transaction observers, perform an explicit call to the ``Database/notifyChanges(in:)`` `Database` method. The ``databaseDidChange()-7olv7`` callback will be called accordingly. For example:
```swift
try dbQueue.write { db in
// Notify observers that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observers that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
To notify a change in the database schema, notify a change to the `sqlite_master` table:
```swift
try dbQueue.write { db in
// Notify all observers of the sqlite_master table
try db.notifyChanges(in: Table("sqlite_master"))
}
```
## Topics
### Filtering Database Changes
@@ -273,7 +244,6 @@ try dbQueue.write { db in
### Handling Database Changes
- ``databaseDidChange()-7olv7``
- ``databaseDidChange(with:)``
- ``stopObservingDatabaseChangesUntilNextTransaction()``
- ``DatabaseEvent``
@@ -6,7 +6,11 @@
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
The only changes that are not notified are:
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
## ValueObservation Usage
@@ -170,30 +174,6 @@ let observation = ValueObservation.tracking(
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
## Dealing with Undetected Changes
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
## ValueObservation Performance
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
@@ -260,7 +240,7 @@ When needed, you can help GRDB optimize observations and reduce database content
- ``publisher(in:scheduling:)``
- ``start(in:scheduling:onError:onChange:)``
- ``values(in:bufferingPolicy:)``
- ``values(in:scheduling:bufferingPolicy:)``
- ``DatabaseCancellable``
- ``ValueObservationScheduler``
+11 -8
View File
@@ -6,6 +6,10 @@ A toolkit for SQLite databases, with a focus on application development
![GRDB Logo](GRDBLogo.png)
- [GitHub Repository](http://github.com/groue/GRDB.swift)
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
## Overview
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
@@ -67,12 +71,6 @@ let players: [Player] = try dbQueue.read { db in
}
```
## Links and Companion Libraries
- [GitHub Repository](http://github.com/groue/GRDB.swift)
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
- [GRDBQuery](https://github.com/groue/GRDBQuery): the SwiftUI companion for GRDB.
- [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting): Test your database.
## Topics
@@ -95,9 +93,14 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Application Tools
### Responding to Database Changes
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
- <doc:JSON>
### Combine Publishers
- ``DatabasePublishers``
-150
View File
@@ -1,150 +0,0 @@
# JSON Support
Store and use JSON values in SQLite databases.
## Overview
SQLite and GRDB can store and fetch JSON values in database columns. Starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+, JSON values can be manipulated at the database level.
## Store and fetch JSON values
### JSON columns in the database schema
It is recommended to store JSON values in text columns. In the example below, we create a ``Database/ColumnType/jsonText`` column with ``Database/create(table:options:body:)``:
```swift
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.column("address", .jsonText).notNull() // A JSON column
}
```
> Note: `.jsonText` and `.text` are equivalent, because both build a TEXT column in SQL. Yet the former better describes the intent of the column.
>
> Note: SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. That's the reason why it is recommended to store JSON as text.
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
>
> ```swift
> // CREATE INDEX "player_on_country"
> // ON "player"("address" ->> 'country')
> try db.create(
> index: "player_on_country",
> on: "player",
> expressions: [
> JSONColumn("address")["country"],
> ])
>
> // SELECT * FROM player
> // WHERE "address" ->> 'country' = 'DE'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .fetchAll(db)
> ```
### Strict and flexible JSON schemas
[Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) handle both strict and flexible JSON schemas.
**For strict schemas**, use `Codable` properties. They will be stored as JSON strings in the database:
```swift
struct Address: Codable {
var street: String
var city: String
var country: String
}
struct Player: Codable {
var id: String
var name: String
// Stored as a JSON string
// {"street": "...", "city": "...", "country": "..."}
var address: Address
}
extension Player: FetchableRecord, PersistableRecord { }
```
**For flexible schemas**, use `String` or `Data` properties.
In the specific case of `Data` properties, it is recommended to store them as text in the database, because SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. This encoding is automatic with ``DatabaseDataEncodingStrategy/text``:
```swift
// JSON String property
struct Player: Codable {
var id: String
var name: String
var address: String // JSON string
}
extension Player: FetchableRecord, PersistableRecord { }
// JSON Data property, saved as text in the database
struct Team: Codable {
var id: String
var color: String
var info: Data // JSON UTF8 data
}
extension Team: FetchableRecord, PersistableRecord {
// Support SQLite JSON functions and operators
// by storing JSON data as database text:
static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
}
```
## Manipulate JSON values at the database level
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc.
See the full list below.
## JSON table-valued functions
The JSON table-valued functions `json_each` and `json_tree` are not supported.
## Topics
### JSON Values
- ``SQLJSONExpressible``
- ``JSONColumn``
### Access JSON subcomponents, and query JSON values, at the SQL level
The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` protocol.
- ``Database/jsonArrayLength(_:)``
- ``Database/jsonArrayLength(_:atPath:)``
- ``Database/jsonExtract(_:atPath:)``
- ``Database/jsonExtract(_:atPaths:)``
- ``Database/jsonType(_:)``
- ``Database/jsonType(_:atPath:)``
### Build new JSON values at the SQL level
- ``Database/json(_:)``
- ``Database/jsonArray(_:)-8xxe3``
- ``Database/jsonArray(_:)-469db``
- ``Database/jsonObject(_:)``
- ``Database/jsonQuote(_:)``
- ``Database/jsonGroupArray(_:filter:)``
- ``Database/jsonGroupObject(key:value:filter:)``
### Modify JSON values at the SQL level
- ``Database/jsonInsert(_:_:)``
- ``Database/jsonPatch(_:with:)``
- ``Database/jsonReplace(_:_:)``
- ``Database/jsonRemove(_:atPath:)``
- ``Database/jsonRemove(_:atPaths:)``
- ``Database/jsonSet(_:_:)``
### Validate JSON values at the SQL level
- ``Database/jsonIsValid(_:)``
+5 -2
View File
@@ -26,7 +26,10 @@ migrator.registerMigration("Create authors") { db in
migrator.registerMigration("Add books and author.birthYear") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author").notNull()
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.column("title", .text).notNull()
}
@@ -233,7 +236,7 @@ To prevent a migration from committing foreign key violations on disk, you can:
}
```
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
```swift
// SQLite error 19: FOREIGN KEY constraint violation - from book(authorId) to author(id),
+4 -12
View File
@@ -17,22 +17,16 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
- ``PersistableRecord``
- ``TableRecord``
### Expressions
### Associations
- ``Column``
- ``JSONColumn``
- ``SQLExpression``
- ``Association``
### Requests
### Query Interface Requests
- ``CommonTableExpression``
- ``QueryInterfaceRequest``
- ``Table``
### Associations
- ``Association``
### Errors
- ``RecordError``
@@ -40,11 +34,9 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
### Supporting Types
- ``ColumnExpression``
- ``DerivableRequest``
- ``SQLExpressible``
- ``SQLJSONExpressible``
- ``SQLSpecificExpressible``
- ``SQLSubqueryable``
- ``SQLOrderingTerm``
- ``SQLSelectable``
- ``SQLSubqueryable``
@@ -31,8 +31,10 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.belongsTo("author", onDelete: .cascade) // (6)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
@@ -44,8 +46,10 @@ try migrator.migrate(dbQueue)
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
@@ -61,16 +65,16 @@ Thanks to this database schema, the application will always process *consistent
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable {
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable {
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
@@ -129,7 +133,7 @@ let books = try dbQueue.read { db in
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable {
> struct Author: Codable, Identifiable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
@@ -150,25 +154,6 @@ let books = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
>
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
>
> ```swift
> struct Player: Codable {
> var id: Int64? // Optional ids are not suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
### Record Types Hide Intimate Database Details
+4 -4
View File
@@ -25,7 +25,7 @@ try db.create(table: "player") { t in
t.column("score", .integer).notNull()
}
struct Player {
struct Player: Identifiable {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
@@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to
```swift
let player = try dbQueue.read { db
try Player.find(db, key: 1)
try Player.find(db, id: 1)
}
player.creationDate // optional 😕
player.modificationDate // optional 😕
@@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players
```swift
/// `Player` deals with unsaved players
struct Player {
struct Player: Identifiable {
var id: Int64? // optional
var creationDate: Date? // optional
var modificationDate: Date? // optional
@@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
```swift
// The base Player type
struct Player {
struct Player: Identifiable {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
-1
View File
@@ -81,7 +81,6 @@ For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swi
### Database Values
- ``DatabaseDateComponents``
- ``DatabaseValueConvertible``
- ``StatementColumnConvertible``
+17 -4
View File
@@ -1,7 +1,5 @@
# Transactions and Savepoints
Precise transaction handling.
## Transactions and Safety
**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB <doc:Concurrency> guarantees.
@@ -214,8 +212,6 @@ SQLite savepoints are more than nested transactions, though. For advanced uses,
SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive.
By default, GRDB opens DEFERRED transaction for reads, and IMMEDIATE transactions for writes.
The transaction kind can be chosen for individual transaction:
```swift
@@ -224,3 +220,20 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// BEGIN EXCLUSIVE TRANSACTION ...
try dbQueue.inTransaction(.exclusive) { db in ... }
```
It is also possible to configure the ``Configuration/defaultTransactionKind``:
```swift
var config = Configuration()
config.defaultTransactionKind = .immediate
let dbQueue = try DatabaseQueue(
path: "/path/to/database.sqlite",
configuration: config)
// BEGIN IMMEDIATE TRANSACTION ...
try dbQueue.write { db in ... }
// BEGIN IMMEDIATE TRANSACTION ...
try dbQueue.inTransaction { db in ... }
```
-357
View File
@@ -1,357 +0,0 @@
import Foundation
// MARK: - Dump
extension Database {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
/// }
/// ```
///
/// - Parameters:
/// - sql: The executed SQL.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSQL(
_ sql: SQL,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSQL(sql, format: format, to: &dumpStream)
}
/// Prints the results of a request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpRequest(Player.orderByPrimaryKey())
/// }
/// ```
///
/// - Parameters:
/// - request : The executed request.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpRequest(request, format: format, to: &dumpStream)
}
/// Prints the contents of the provided tables and views.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// try db.dumpTables(["player", "team"])
/// }
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - stableOrder: A boolean value that controls the ordering of
/// rows fetched from views. If false (the default), rows are
/// printed in the order specified by the view (which may be
/// undefined). It true, outputted rows are always printed in the
/// same stable order. The purpose of this stable order is to make
/// the output suitable for testing.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpTables(
_ tables: [String],
format: some DumpFormat = .debug(),
tableHeader: DumpTableHeaderOptions = .automatic,
stableOrder: Bool = false,
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: &dumpStream)
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpContent()
/// }
/// ```
///
/// This prints the database schema as well as the content of all
/// tables. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
///
/// player
/// 1,'Arthur',500
/// 2,'Barbara',1000
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpContent(
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpContent(format: format, to: &dumpStream)
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpSchema()
/// }
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSchema(to: &dumpStream)
}
}
// MARK: -
extension Database {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
while let statement = try statements.next() {
var stepFormat = format
let cursor = try statement.makeCursor()
while try cursor.next() != nil {
try stepFormat.writeRow(self, statement: statement, to: &stream)
}
stepFormat.finalize(self, statement: statement, to: &stream)
}
}
func _dumpSQL(
_ sql: SQL,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpStatements(allStatements(literal: sql), format: format, to: &stream)
}
func _dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
let preparedRequest = try request.makePreparedRequest(self, forSingleResult: false)
try _dumpStatements(AnyCursor([preparedRequest.statement]), format: format, to: &stream)
if let supplementaryFetch = preparedRequest.supplementaryFetch {
let rows = try Row.fetchAll(self, request)
try withoutActuallyEscaping(
{ request, keyPath in
stream.write("\n")
stream.writeln(keyPath.joined(separator: "."))
try self._dumpRequest(request, format: format, to: &stream)
},
do: { willExecuteSupplementaryRequest in
try supplementaryFetch(self, rows, willExecuteSupplementaryRequest)
})
}
}
func _dumpTables(
_ tables: [String],
format: some DumpFormat,
tableHeader: DumpTableHeaderOptions,
stableOrder: Bool,
to stream: inout DumpStream)
throws
{
let header: Bool
switch tableHeader {
case .always: header = true
case .automatic: header = tables.count > 1
}
var first = true
for table in tables {
if first {
first = false
} else {
stream.write("\n")
}
if header {
stream.writeln(table)
}
if try tableExists(table) {
// Always sort tables by primary key
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
} else if stableOrder {
// View with stable order
try _dumpRequest(Table(table).all().withStableOrder(), format: format, to: &stream)
} else {
// Use view ordering, if any (no guarantee of stable order).
try _dumpRequest(Table(table).all(), format: format, to: &stream)
}
}
}
func _dumpContent(
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpSchema(to: &stream)
stream.margin()
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
try !ignoresObject(named: $0)
}
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
}
func _dumpSchema(
to stream: inout DumpStream)
throws
{
stream.writeln("sqlite_master")
let sqlRows = try Row.fetchAll(self, sql: """
SELECT sql || ';', name
FROM sqlite_master
WHERE sql IS NOT NULL
ORDER BY
tbl_name COLLATE NOCASE,
CASE type WHEN 'table' THEN 'a' WHEN 'index' THEN 'aa' ELSE type END,
name COLLATE NOCASE,
sql
""")
for row in sqlRows {
let name: String = row[1]
if try ignoresObject(named: name) {
continue
}
stream.writeln(row[0])
}
}
private func ignoresObject(named name: String) throws -> Bool {
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
}
return table.kind == .shadow
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
guard let table = try table(tableName) else {
// Not a table
return false
}
return table.kind == .shadow
}
#endif
// Don't know
return false
}
}
/// Options for printing table names.
public enum DumpTableHeaderOptions: Sendable {
/// Table names are only printed when several tables are printed.
case automatic
/// Table names are always printed.
case always
}
-173
View File
@@ -1,173 +0,0 @@
extension DatabaseReader {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
///
/// ```swift
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
/// ```
///
/// - Parameters:
/// - sql: The executed SQL.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSQL(
_ sql: SQL,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpSQL(sql, format: format, to: stream)
}
}
/// Prints the results of a request.
///
/// For example:
///
/// ```swift
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
/// ```
///
/// - Parameters:
/// - request : The executed request.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpRequest(request, format: format, to: stream)
}
}
/// Prints the contents of the provided tables and views.
///
/// For example:
///
/// ```swift
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// try dbQueue.dumpTables(["player", "team"])
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - stableOrder: A boolean value that controls the ordering of
/// rows fetched from views. If false (the default), rows are
/// printed in the order specified by the view (which may be
/// undefined). It true, outputted rows are always printed in the
/// same stable order. The purpose of this stable order is to make
/// the output suitable for testing.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpTables(
_ tables: [String],
format: some DumpFormat = .debug(),
tableHeader: DumpTableHeaderOptions = .automatic,
stableOrder: Bool = false,
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: stream)
}
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.dumpContent()
/// ```
///
/// This prints the database schema as well as the content of all
/// tables. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
///
/// player
/// 1,'Arthur',500
/// 2,'Barbara',1000
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpContent(
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpContent(format: format, to: stream)
}
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.dumpSchema()
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpSchema(to: stream)
}
}
}
-112
View File
@@ -1,112 +0,0 @@
/// A type that prints database rows.
///
/// Types that conform to `DumpFormat` feed the printing methods such as
/// ``DatabaseReader/dumpContent(format:to:)`` and
/// ``Database/dumpSQL(_:format:to:)``.
///
/// Most built-in formats are inspired from the
/// [output formats of the SQLite command line tool](https://sqlite.org/cli.html#changing_output_formats).
///
/// ## Topics
///
/// ### Built-in Formats
///
/// - ``debug(header:separator:nullValue:)``
/// - ``json(encoder:)``
/// - ``line(nullValue:)``
/// - ``list(header:separator:nullValue:)``
/// - ``quote(header:separator:)``
///
/// ### Supporting Types
///
/// - ``DebugDumpFormat``
/// - ``JSONDumpFormat``
/// - ``LineDumpFormat``
/// - ``ListDumpFormat``
/// - ``QuoteDumpFormat``
/// - ``DumpStream``
///
/// ### Implementing a custom format
///
/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// - ``writeRow(_:statement:to:)``
/// - ``finalize(_:statement:to:)``
public protocol DumpFormat {
/// Writes a row from the given statement.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The iterated statement
/// - stream: A stream for text output.
mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream) throws
/// All rows from the statement have been printed.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The statement that was iterated.
/// - stream: A stream for text output.
mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
}
/// A TextOutputStream that prints to standard output
struct StandardOutputStream: TextOutputStream {
func write(_ string: String) {
print(string, terminator: "")
}
}
/// A text output stream suited for printing database content.
///
/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public struct DumpStream {
var base: any TextOutputStream
var needsMarginLine = false
init(_ base: (any TextOutputStream)?) {
self.base = base ?? StandardOutputStream()
}
/// Will write `"\n"` before the next non-empty string.
public mutating func margin() {
needsMarginLine = true
}
}
extension DumpStream: TextOutputStream {
public mutating func write(_ string: String) {
if needsMarginLine && !string.isEmpty {
needsMarginLine = false
if string.first != "\n" {
base.write("\n")
}
}
base.write(string)
}
}
extension TextOutputStream {
mutating func writeln(_ string: String) {
write(string)
write("\n")
}
}
extension String {
func leftPadding(toLength newLength: Int, withPad padString: String) -> String {
precondition(padString.count == 1)
if count < newLength {
return String(repeating: padString, count: newLength - count) + self
} else {
let startIndex = index(startIndex, offsetBy: count - newLength)
return String(self[startIndex...])
}
}
}
-162
View File
@@ -1,162 +0,0 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database row, suitable
/// for debugging.
///
/// This format may change in future releases. It is not suitable for
/// processing by other programs, or testing.
///
/// On each line, database values are separated by a separator (`|`
/// by default).
///
/// For example:
///
/// ```swift
/// // Arthur|500
/// // Barbara|1000
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .debug())
/// ```
public struct DebugDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
/// The separator between values.
public var separator: String
/// The string to print for NULL values.
public var nullValue: String
private var firstRow = true
/// Creates a `DebugDumpFormat`.
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
/// - nullValue: The string to print for NULL values.
public init(
header: Bool = false,
separator: String = "|",
nullValue: String = "")
{
self.header = header
self.separator = separator
self.nullValue = nullValue
}
}
extension DebugDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
firstRow = false
if header {
stream.writeln(statement.columnNames.joined(separator: separator))
}
}
let sqliteStatement = statement.sqliteStatement
var first = true
for index in 0..<sqlite3_column_count(sqliteStatement) {
// Don't log GRDB columns
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
if column.starts(with: "grdb_") { continue }
if first {
first = false
} else {
stream.write(separator)
}
stream.write(formattedValue(db, in: sqliteStatement, at: index))
}
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
case SQLITE_INTEGER:
return Int64(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_FLOAT:
return Double(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_BLOB:
let data = Data(sqliteStatement: sqliteStatement, index: index)
if let string = String(data: data, encoding: .utf8) {
return string
} else if data.count == 16, let blob = sqlite3_column_blob(sqliteStatement, index) {
let uuid = UUID(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
return uuid.uuidString
} else {
return try! data.sqlExpression.quotedSQL(db)
}
case SQLITE_TEXT:
return String(sqliteStatement: sqliteStatement, index: index)
default:
return ""
}
}
}
extension DumpFormat where Self == DebugDumpFormat {
/// A format that prints one line per database row, suitable
/// for debugging.
///
/// This format may change in future releases. It is not suitable for
/// processing by other programs, or testing.
///
/// On each line, database values are separated by a separator (`|`
/// by default).
///
/// For example:
///
/// ```swift
/// // Arthur|500
/// // Barbara|1000
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .debug())
/// ```
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
/// - nullValue: The string to print for NULL values.
public static func debug(
header: Bool = false,
separator: String = "|",
nullValue: String = "")
-> Self
{
DebugDumpFormat(header: header, separator: separator, nullValue: nullValue)
}
}
-213
View File
@@ -1,213 +0,0 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints database rows as a JSON array.
///
/// For example:
///
/// ```swift
/// // [{"name":"Arthur","score":500},
/// // {"name":"Barbara","score":1000}]
/// try db.dumpRequest(Player.all(), format: .json())
/// ```
///
/// For a pretty-printed output, customize the JSON encoder:
///
/// ```swift
/// // [
/// // {
/// // "name": "Arthur",
/// // "score": 500
/// // },
/// // {
/// // "name": "Barbara",
/// // "score": 1000
/// // }
/// // ]
/// let encoder = JSONDumpFormat.defaultEncoder
/// encoder.outputFormatting = .prettyPrinted
/// try db.dumpRequest(Player.all(), format: .json(encoder))
/// ```
public struct JSONDumpFormat: Sendable {
/// The default `JSONEncoder` for database values.
///
/// It is configured so that blob values (`Data`) are encoded in the
/// base64 format, and Non-conforming floats are encoded as "inf",
/// "-inf" and "nan".
///
/// It uses the output formatting option
/// `JSONEncoder.OutputFormatting.withoutEscapingSlashes` when available.
///
/// Modifying the returned encoder does not affect any encoder returned
/// by future calls to this method. It is always safe to use the
/// returned encoder as a starting point for additional customization.
public static var defaultEncoder: JSONEncoder {
// This encoder MUST NOT CHANGE, because some people rely on this format.
let encoder = JSONEncoder()
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, *) {
encoder.outputFormatting = .withoutEscapingSlashes
}
encoder.nonConformingFloatEncodingStrategy = .convertToString(
positiveInfinity: "inf",
negativeInfinity: "-inf",
nan: "nan")
encoder.dataEncodingStrategy = .base64
return encoder
}
/// The JSONEncoder that formats individual database values.
public var encoder: JSONEncoder
var firstRow = true
/// Creates a `JSONDumpFormat`.
///
/// - Parameter encoder: The JSONEncoder that formats individual
/// database values. If the outputFormatting` options contain
/// `.prettyPrinted`, the printed array has one value per line.
public init(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) {
self.encoder = encoder
}
}
extension JSONDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
throws {
if firstRow {
firstRow = false
stream.write("[")
if encoder.outputFormatting.contains(.prettyPrinted) {
stream.write("\n")
}
} else {
stream.write(",\n")
}
if encoder.outputFormatting.contains(.prettyPrinted) {
stream.write(" ")
}
stream.write("{")
let sqliteStatement = statement.sqliteStatement
var first = true
for index in 0..<sqlite3_column_count(sqliteStatement) {
// Don't log GRDB columns
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
if column.starts(with: "grdb_") {
continue
}
if first {
first = false
} else {
stream.write(",")
}
if encoder.outputFormatting.contains(.prettyPrinted) {
stream.write("\n ")
}
try stream.write(formattedValue(column))
stream.write(":")
try stream.write(formattedValue(db, in: sqliteStatement, at: index))
}
if encoder.outputFormatting.contains(.prettyPrinted) {
stream.write("\n ")
}
stream.write("}")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
if !statement.columnNames.isEmpty {
stream.writeln("[]")
}
} else {
if encoder.outputFormatting.contains(.prettyPrinted) {
stream.write("\n")
}
stream.writeln("]")
}
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return "null"
case SQLITE_INTEGER:
return try formattedValue(Int64(sqliteStatement: sqliteStatement, index: index))
case SQLITE_FLOAT:
return try formattedValue(Double(sqliteStatement: sqliteStatement, index: index))
case SQLITE_BLOB:
return try formattedValue(Data(sqliteStatement: sqliteStatement, index: index))
case SQLITE_TEXT:
return try formattedValue(String(sqliteStatement: sqliteStatement, index: index))
default:
return ""
}
}
private func formattedValue(_ value: some Encodable) throws -> String {
let data = try encoder.encode(value)
guard let string = String(data: data, encoding: .utf8) else {
throw EncodingError.invalidValue(data, .init(codingPath: [], debugDescription: "Invalid JSON data"))
}
return string
}
}
extension DumpFormat where Self == JSONDumpFormat {
/// A format that prints database rows as a JSON array.
///
/// For example:
///
/// ```swift
/// // [{"name":"Arthur","score":500},
/// // {"name":"Barbara","score":1000}]
/// try db.dumpRequest(Player.all(), format: .json())
/// ```
///
/// For a pretty-printed output, customize the JSON encoder:
///
/// ```swift
/// // [
/// // {
/// // "name": "Arthur",
/// // "score": 500
/// // },
/// // {
/// // "name": "Barbara",
/// // "score": 1000
/// // }
/// // ]
/// let encoder = JSONDumpFormat.defaultEncoder
/// encoder.outputFormatting = .prettyPrinted
/// try db.dumpRequest(Player.all(), format: .json(encoder))
/// ```
///
/// - Parameter encoder: The JSONEncoder that formats individual
/// database values. If the outputFormatting` options contain
/// `.prettyPrinted`, the printed array has one value per line.
public static func json(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) -> Self {
JSONDumpFormat(encoder: encoder)
}
}
-138
View File
@@ -1,138 +0,0 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database value. All blob values
/// are interpreted as strings.
///
/// For example:
///
/// ```swift
/// // name = Arthur
/// // score = 500
/// //
/// // name = Barbara
/// // score = 1000
/// try db.dumpRequest(Player.all(), format: .line())
/// ```
public struct LineDumpFormat: Sendable {
/// The string to print for NULL values.
public var nullValue: String
var firstRow = true
/// Creates a `LineDumpFormat`.
///
/// - Parameters:
/// - nullValue: The string to print for NULL values.
public init(
nullValue: String = "")
{
self.nullValue = nullValue
}
}
extension LineDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
var lines: [(column: String, value: String)] = []
let sqliteStatement = statement.sqliteStatement
for index in 0..<sqlite3_column_count(sqliteStatement) {
// Don't log GRDB columns
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
if column.starts(with: "grdb_") { continue }
lines.append((
column: column,
value: formattedValue(db, in: sqliteStatement, at: index)))
}
if lines.isEmpty { return }
if firstRow {
firstRow = false
} else {
stream.write("\n")
}
let columnWidth = lines.map(\.column.count).max()!
for line in lines {
stream.write(line.column.leftPadding(toLength: columnWidth, withPad: " "))
stream.write(" = ")
stream.writeln(line.value)
}
}
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow == false {
stream.margin()
}
firstRow = true
}
func formattedValue(
_ db: Database,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
{
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
case SQLITE_INTEGER:
return Int64(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_FLOAT:
return Double(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_BLOB, SQLITE_TEXT:
return String(sqliteStatement: sqliteStatement, index: index)
default:
return ""
}
}
}
extension DumpFormat where Self == LineDumpFormat {
/// A format that prints one line per database value. All blob values
/// are interpreted as strings.
///
/// On each line, database values are separated by a separator (`|`
/// by default). Blob values are interpreted as UTF8 strings.
///
/// For example:
///
/// ```swift
/// // name = Arthur
/// // score = 500
/// //
/// // name = Barbara
/// // score = 1000
/// try db.dumpRequest(Player.all(), format: .line())
/// ```
///
/// - Parameters:
/// - nullValue: The string to print for NULL values.
public static func line(
nullValue: String = "")
-> Self
{
LineDumpFormat(nullValue: nullValue)
}
}
-150
View File
@@ -1,150 +0,0 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A format that prints one line per database row. All blob values
/// are interpreted as strings.
///
/// On each line, database values are separated by a separator (`|`
/// by default). Blob values are interpreted as UTF8 strings.
///
/// For example:
///
/// ```swift
/// // Arthur|500
/// // Barbara|1000
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .list())
/// ```
public struct ListDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
/// The separator between values.
public var separator: String
/// The string to print for NULL values.
public var nullValue: String
private var firstRow = true
/// Creates a `ListDumpFormat`.
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
/// - nullValue: The string to print for NULL values.
public init(
header: Bool = false,
separator: String = "|",
nullValue: String = "")
{
self.header = header
self.separator = separator
self.nullValue = nullValue
}
}
extension ListDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
firstRow = false
if header {
stream.writeln(statement.columnNames.joined(separator: separator))
}
}
let sqliteStatement = statement.sqliteStatement
var first = true
for index in 0..<sqlite3_column_count(sqliteStatement) {
// Don't log GRDB columns
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
if column.starts(with: "grdb_") { continue }
if first {
first = false
} else {
stream.write(separator)
}
stream.write(formattedValue(db, in: sqliteStatement, at: index))
}
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
}
func formattedValue(
_ db: Database,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
{
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
case SQLITE_INTEGER:
return Int64(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_FLOAT:
return Double(sqliteStatement: sqliteStatement, index: index).description
case SQLITE_BLOB, SQLITE_TEXT:
return String(sqliteStatement: sqliteStatement, index: index)
default:
return ""
}
}
}
extension DumpFormat where Self == ListDumpFormat {
/// A format that prints one line per database row. All blob values
/// are interpreted as strings.
///
/// On each line, database values are separated by a separator (`|`
/// by default). Blob values are interpreted as UTF8 strings.
///
/// For example:
///
/// ```swift
/// // Arthur|500
/// // Barbara|1000
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .list())
/// ```
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
/// - nullValue: The string to print for NULL values.
public static func list(
header: Bool = false,
separator: String = "|",
nullValue: String = "")
-> Self
{
ListDumpFormat(header: header, separator: separator, nullValue: nullValue)
}
}
-110
View File
@@ -1,110 +0,0 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A format that prints one line per database row, formatting values
/// as SQL literals.
///
/// For example:
///
/// ```swift
/// // 'Arthur',500
/// // 'Barbara',1000
/// // 'Craig',200
/// try db.dumpRequest(Player.all(), format: .quote())
/// ```
public struct QuoteDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
/// The separator between values.
public var separator: String
var firstRow = true
/// Creates a `QuoteDumpFormat`.
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
public init(
header: Bool = false,
separator: String = ",")
{
self.header = header
self.separator = separator
}
}
extension QuoteDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
firstRow = false
if header {
stream.writeln(statement.columnNames
.map { try! $0.sqlExpression.quotedSQL(db) }
.joined(separator: separator))
}
}
let sqliteStatement = statement.sqliteStatement
var first = true
for index in 0..<sqlite3_column_count(sqliteStatement) {
// Don't log GRDB columns
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
if column.starts(with: "grdb_") { continue }
if first {
first = false
} else {
stream.write(separator)
}
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
try! stream.write(dbValue.sqlExpression.quotedSQL(db))
}
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
}
}
extension DumpFormat where Self == QuoteDumpFormat {
/// A format that prints one line per database row, formatting values
/// as SQL literals.
///
/// For example:
///
/// ```swift
/// // 'Arthur',500
/// // 'Barbara',1000
/// // 'Craig',200
/// try db.dumpRequest(Player.all(), format: .quote())
/// ```
///
/// - Parameters:
/// - header: A boolean value indicating if column labels are printed
/// as the first line of output.
/// - separator: The separator between values.
public static func quote(header: Bool = false, separator: String = ",") -> Self {
QuoteDumpFormat(header: header, separator: separator)
}
}
+8
View File
@@ -0,0 +1,8 @@
// Export the underlying SQLite library
#if SWIFT_PACKAGE
@_exported import CSQLite
#elseif GRDBCIPHER
@_exported import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@_exported import SQLite3
#endif
+2 -7
View File
@@ -29,7 +29,7 @@
/// - ``tokenize(_:withTokenizer:)``
public struct FTS3 {
/// Options for Latin script characters.
public enum Diacritics: Sendable {
public enum Diacritics {
/// Do not remove diacritics from Latin script characters. This option
/// matches the `remove_diacritics=0` tokenizer argument.
///
@@ -47,7 +47,7 @@ public struct FTS3 {
#elseif !GRDBCIPHER
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
case remove
#endif
}
@@ -183,8 +183,3 @@ public final class FTS3TableDefinition {
columns.append(name)
}
}
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS3TableDefinition: Sendable { }
Loaded 100 of 343 files, more files were not shown because too many files have changed in this diff. Show more