Compare commits

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

No files matched your search

+29 -70
View File
@@ -13,7 +13,6 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
pull_request:
paths:
- 'GRDB/**'
@@ -21,14 +20,12 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
concurrency:
group: ${{ github.ref_name }}
cancel-in-progress: true
permissions:
contents: read
checks: write
jobs:
Framework:
@@ -41,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"
@@ -78,15 +67,9 @@ 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 }}" -resultBundlePath TestResults.xcresult 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
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: TestResults.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
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:
name: SPM
runs-on: ${{ matrix.runsOn }}
@@ -97,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:
@@ -123,22 +103,13 @@ 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
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: Tests/CocoaPods/SQLCipher3/TestResults_encrypted.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
SQLCipher4:
name: SQLCipher4
runs-on: ${{ matrix.runsOn }}
@@ -149,22 +120,16 @@ 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
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: Tests/CocoaPods/SQLCipher4/TestResults_encrypted.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
CustomSQLite:
name: CustomSQLite
runs-on: ${{ matrix.runsOn }}
@@ -175,22 +140,16 @@ 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
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: TestResults.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
XCFramework:
name: XCFramework
runs-on: ${{ matrix.runsOn }}
@@ -201,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
-3
View File
@@ -115,6 +115,3 @@ Tests/SPM/Packages
# Test products
Tests/products
# CI
*.xcresult
-67
View File
@@ -7,11 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `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)
@@ -118,68 +113,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 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.
+20 -24
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:
+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.42.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).
@@ -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)
}
}
@@ -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
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.20.2'
s.version = '6.15.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+2 -150
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 */; };
@@ -101,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 */; };
@@ -123,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 */; };
@@ -203,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 */; };
@@ -398,14 +379,6 @@
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 */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
@@ -435,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>"; };
@@ -479,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>"; };
@@ -527,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>"; };
@@ -549,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>"; };
@@ -648,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>"; };
@@ -831,14 +785,6 @@
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>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
@@ -876,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 = (
@@ -974,7 +901,6 @@
isa = PBXGroup;
children = (
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -1002,14 +928,12 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.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 */,
@@ -1085,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 */,
@@ -1249,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 */,
);
@@ -1263,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>";
@@ -1334,7 +1248,6 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1342,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 = (
@@ -1732,9 +1613,7 @@
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEB52AC862EC00CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
56300B6D1C53F592005A543B /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1919,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 */,
@@ -1931,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 */,
@@ -1946,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 */,
@@ -2024,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 */,
@@ -2035,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 */,
@@ -2052,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 */,
@@ -2090,7 +1963,6 @@
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.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 */,
@@ -2146,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 */,
@@ -2180,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 */,
@@ -2195,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 */,
@@ -2215,8 +2083,6 @@
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 */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
@@ -2224,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 */,
@@ -2233,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 */,
@@ -2252,11 +2115,8 @@
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
567B5BE82AD3284100629622 /* DumpFormat.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 */,
@@ -2264,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 */,
@@ -2284,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 */,
@@ -2304,9 +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 */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
-40
View File
@@ -288,46 +288,6 @@ public struct Configuration {
/// 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 {
/// 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.
+188 -77
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: <)
}
+21 -44
View File
@@ -354,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)
@@ -858,22 +858,8 @@ public struct ColumnInfo: FetchableRecord {
///
/// 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
@@ -1164,22 +1150,22 @@ public struct PrimaryKeyInfo {
/// 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)
@@ -1189,34 +1175,21 @@ public struct PrimaryKeyInfo {
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
}
@@ -1243,7 +1216,7 @@ public struct PrimaryKeyInfo {
return true
case .rowID:
return true
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
case let .regular(columns: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
@@ -1343,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")
+1 -1
View File
@@ -373,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,
+74 -78
View File
@@ -65,15 +65,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``TransactionCompletion``
/// - ``TransactionKind``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Database Observation
///
/// - ``add(transactionObserver:extent:)``
@@ -430,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)
@@ -904,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
@@ -921,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 }
@@ -929,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
@@ -1826,7 +1801,6 @@ extension Database {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
@@ -1835,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")
@@ -1931,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.
@@ -1946,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:
@@ -1958,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
}
}
}
@@ -1978,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
}
}
}
}
+2 -2
View File
@@ -549,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)"
@@ -577,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)"
+10 -18
View File
@@ -30,22 +30,9 @@ public final class DatabaseFunction: Hashable {
/// 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)) }
var functionFlags: SQLFunctionFlags {
var flags = SQLFunctionFlags(isPure: isPure)
switch kind {
case .function:
break
case .aggregate:
flags.isAggregate = true
}
return flags
}
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Creates an SQL function.
///
@@ -89,7 +76,7 @@ public final class DatabaseFunction: Hashable {
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.pure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
@@ -153,7 +140,7 @@ public final class DatabaseFunction: Hashable {
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.pure = pure
self.kind = .aggregate { Aggregate() }
}
@@ -183,7 +170,12 @@ public final class DatabaseFunction: Hashable {
/// }
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
.function(name, arguments.map(\.sqlExpression), flags: functionFlags)
switch kind {
case .aggregate:
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
}
/// Calls sqlite3_create_function_v2
+53 -24
View File
@@ -13,9 +13,6 @@ public final class DatabasePool {
@LockedBox var databaseSnapshotCount = 0
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Database Information
public var configuration: Configuration {
@@ -75,12 +72,39 @@ public final class DatabasePool {
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
}
}
}
}
@@ -97,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
@@ -148,7 +169,7 @@ public final class DatabasePool {
}
}
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
// @unchecked because of databaseSnapshotCount and readerPool
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -324,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
+23 -33
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
@@ -207,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
-20
View File
@@ -17,7 +17,6 @@ import Dispatch
/// ### Database Information
///
/// - ``configuration``
/// - ``path``
///
/// ### Reading from the Database
///
@@ -33,15 +32,6 @@ import Dispatch
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Other Database Operations
///
/// - ``backup(to:pagesPerStep:progress:)``
@@ -56,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
@@ -660,10 +644,6 @@ extension AnyDatabaseReader: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+1 -2
View File
@@ -44,7 +44,6 @@ import Foundation
/// ### Creating a DatabaseValue
///
/// - ``init(value:)``
/// - ``init(sqliteStatement:index:)``
/// - ``null``
///
/// ### Accessing the SQLite storage
@@ -150,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
-49
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,41 +75,6 @@ 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
+4 -30
View File
@@ -445,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
@@ -472,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) }
}
@@ -986,10 +964,6 @@ extension AnyDatabaseWriter: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+2 -25
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
+3 -3
View File
@@ -1739,7 +1739,7 @@ extension Row {
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
try request.supplementaryFetch?(db, rows)
return rows
}
@@ -1772,7 +1772,7 @@ extension Row {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows, nil)
try supplementaryFetch(db, rows)
return Set(rows)
} else {
return try fetchSet(request.statement, adapter: request.adapter)
@@ -1809,7 +1809,7 @@ extension Row {
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
}
try request.supplementaryFetch?(db, [row], nil)
try request.supplementaryFetch?(db, [row])
return row
}
}
+5 -3
View File
@@ -39,6 +39,8 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
/// - ``Swift/Collection/joined(separator:)``
/// - ``Swift/Sequence/joined(separator:)``
public struct SQL {
/// `SQL.Element` is a component of an `SQL` literal.
///
@@ -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:
+8 -9
View File
@@ -42,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
@@ -91,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)
}
@@ -102,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
}()
@@ -119,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)
@@ -223,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)"
+4 -4
View File
@@ -57,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
+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 {
+1 -1
View File
@@ -1,6 +1,6 @@
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) {
@@ -75,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 -4
View File
@@ -1,8 +1,7 @@
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.
@@ -31,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.
@@ -115,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 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
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 -2
View File
@@ -1,7 +1,7 @@
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 {
@@ -35,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
}
}
@@ -44,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,6 +1,6 @@
// 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.
@@ -95,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.
@@ -134,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.
@@ -173,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.
@@ -212,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.
@@ -251,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.
@@ -294,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.
@@ -333,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.
@@ -372,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.
@@ -411,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.
@@ -450,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.
@@ -489,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.
@@ -529,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.
@@ -569,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.
+16 -41
View File
@@ -2,20 +2,11 @@ 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
@@ -29,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)
}
@@ -796,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.
@@ -805,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
@@ -1113,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,
@@ -1154,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!) }
@@ -1290,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,
@@ -1347,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!) }
@@ -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
+12 -21
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,18 +372,10 @@ 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``
+3 -5
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:
@@ -83,9 +83,7 @@ do {
- ``acceptsDoubleQuotedStringLiterals``
- ``busyMode``
- ``foreignKeysEnabled``
- ``journalMode``
- ``readonly``
- ``JournalModeConfiguration``
### Configuring GRDB Connections
@@ -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(_:_:)``
@@ -91,7 +91,8 @@ A `DatabaseQueue` 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.
- ``inDatabase(_:)``
- ``inTransaction(_:_:)``
@@ -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``
@@ -97,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
+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``
-151
View File
@@ -1,151 +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(_:)``
- ``Database/jsonGroupObject(key:value:)``
### 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/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
+4 -1
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()
}
+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``
-2
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.
-260
View File
@@ -1,260 +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
/// 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
/// 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.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// db.dumpTables(["player", "team"])
/// }
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - 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,
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpTables(tables, format: format, tableHeader: tableHeader, to: &dumpStream)
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// 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_").
///
/// - 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)
}
}
// 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 = .automatic,
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)
}
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
}
}
func _dumpContent(
format: some DumpFormat,
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 Database.isSQLiteInternalTable(name) || Database.isGRDBInternalTable(name) {
continue
}
stream.writeln(row[0])
}
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
!(Database.isSQLiteInternalTable($0) || Database.isGRDBInternalTable($0))
}
if tables.isEmpty { return }
stream.write("\n")
try _dumpTables(tables, format: format, tableHeader: .always, to: &stream)
}
}
/// Options for printing table names.
public enum DumpTableHeaderOptions {
/// Table names are only printed when several tables are printed.
case automatic
/// Table names are always printed.
case always
}
-125
View File
@@ -1,125 +0,0 @@
extension DatabaseReader {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
///
/// ```swift
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// 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
/// 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.
///
/// For example:
///
/// ```swift
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// dbQueue.dumpTables(["player", "team"])
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - 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,
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpTables(tables, format: format, tableHeader: tableHeader, to: stream)
}
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// 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_").
///
/// - 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)
}
}
}
-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...])
}
}
}
-153
View File
@@ -1,153 +0,0 @@
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 {
/// 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)
}
}
-204
View File
@@ -1,204 +0,0 @@
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 {
/// 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, watchOS 6.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)
}
}
-129
View File
@@ -1,129 +0,0 @@
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 {
/// 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)
}
}
-141
View File
@@ -1,141 +0,0 @@
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 {
/// 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)
}
}
-101
View File
@@ -1,101 +0,0 @@
/// 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 {
/// 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)
}
}
+3 -3
View File
@@ -143,9 +143,9 @@ public struct FTS5 {
private static func api_v2(
_ db: Database,
// swiftlint:disable:next line_length
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<CChar>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<CChar>?>?) -> CInt,
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
// swiftlint:disable:next line_length
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<CChar>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
-> UnsafePointer<fts5_api>
{
var statement: SQLiteStatement? = nil
@@ -157,7 +157,7 @@ public struct FTS5 {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: CChar.self, capacity: type.utf8CodeUnitCount) { typePointer in
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
+2 -2
View File
@@ -131,10 +131,10 @@ extension Database {
tokenizerPointer: OpaquePointer?,
context: UnsafeMutableRawPointer?,
flags: CInt,
pText: UnsafePointer<CChar>?,
pText: UnsafePointer<Int8>?,
nText: CInt,
// swiftlint:disable:next line_length
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<CChar>?, CInt, CInt, CInt) -> CInt)?)
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<Int8>?, CInt, CInt, CInt) -> CInt)?)
-> CInt
{
guard let tokenizerPointer else {
+7 -7
View File
@@ -7,7 +7,7 @@ import Foundation
public typealias FTS5TokenCallback = @convention(c) (
_ context: UnsafeMutableRawPointer?,
_ flags: CInt,
_ pToken: UnsafePointer<CChar>?,
_ pToken: UnsafePointer<Int8>?,
_ nToken: CInt,
_ iStart: CInt,
_ iEnd: CInt)
@@ -77,7 +77,7 @@ public protocol FTS5Tokenizer: AnyObject {
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<CChar>?,
pText: UnsafePointer<Int8>?,
nText: CInt,
tokenCallback: @escaping FTS5TokenCallback)
-> CInt
@@ -143,7 +143,7 @@ extension FTS5Tokenizer {
guard let addr = buffer.baseAddress else {
return []
}
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: CChar.self)
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nText = CInt(buffer.count)
var context = TokenizeContext()
@@ -206,8 +206,8 @@ extension Database {
} else {
func withArrayOfCStrings<Result>(
_ input: [String],
_ output: inout ContiguousArray<UnsafePointer<CChar>>,
_ accessor: (ContiguousArray<UnsafePointer<CChar>>) -> Result)
_ output: inout ContiguousArray<UnsafePointer<Int8>>,
_ accessor: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
-> Result
{
if output.count == input.count {
@@ -219,7 +219,7 @@ extension Database {
}
}
}
var cStrings = ContiguousArray<UnsafePointer<CChar>>()
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
cStrings.reserveCapacity(arguments.count)
code = withArrayOfCStrings(arguments, &cStrings) { (cStrings) in
cStrings.withUnsafeBufferPointer { azArg in
@@ -252,7 +252,7 @@ extension Database {
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<CChar>?,
pText: UnsafePointer<Int8>?,
nText: CInt,
tokenCallback: @escaping FTS5TokenCallback)
-> CInt
+2 -2
View File
@@ -87,7 +87,7 @@ extension FTS5WrapperTokenizer {
public func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<CChar>?,
pText: UnsafePointer<Int8>?,
nText: CInt,
tokenCallback: @escaping FTS5TokenCallback)
-> CInt
@@ -138,7 +138,7 @@ extension FTS5WrapperTokenizer {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr)
.assumingMemoryBound(to: CChar.self)
.assumingMemoryBound(to: Int8.self)
let nToken = CInt(buffer.count)
// Inject token bytes into SQLite
-91
View File
@@ -1,91 +0,0 @@
/// A JSON column in a database table.
///
/// ## Overview
///
/// `JSONColumn` has benefits over ``Column`` for database columns that
/// contain JSON strings.
///
/// It behaves like a regular `Column`, with all extra conveniences and
/// behaviors of ``SQLJSONExpressible``.
///
/// For example, the sample code below directly accesses the "countryCode"
/// key of the "address" JSON column:
///
/// ```swift
/// struct Player: Codable {
/// var id: Int64
/// var name: String
/// var address: Address
/// }
///
/// struct Address: Codable {
/// var street: String
/// var city: String
/// var countryCode: String
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn!
/// }
/// }
///
/// try dbQueue.write { db in
/// // In a real app, table creation should happen in a migration.
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// t.column("address", .jsonText).notNull()
/// }
///
/// // Fetch all country codes
/// // SELECT DISTINCT address ->> 'countryCode' FROM player
/// let countryCodes: [String] = try Player
/// .select(Player.Columns.address["countryCode"], as: String.self)
/// .distinct()
/// .fetchAll(db)
/// }
/// ```
///
/// > Tip: When you can not create a `JSONColumn`, you'll get the same
/// > convenient access to JSON subcomponents
/// > with ``SQLSpecificExpressible/asJSON``.
/// >
/// > For example, the above sample can be adapted as below:
/// >
/// > ```swift
/// > extension Player: FetchableRecord, PersistableRecord {
/// > // That's another valid way to define columns.
/// > // But we don't have any JSONColumn this time.
/// > enum Columns: String, ColumnExpression {
/// > case id, name, address
/// > }
/// > }
/// >
/// > try dbQueue.write { db in
/// > // Fetch all country codes
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
/// > let countryCodes: [String] = try Player
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
/// > .distinct()
/// > .fetchAll(db)
/// > }
/// > ```
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
public var name: String
/// Creates a `JSONColumn` given its name.
///
/// The name should be unqualified, such as `"score"`. Qualified name such
/// as `"player.score"` are unsupported.
public init(_ name: String) {
self.name = name
}
/// Creates a `JSONColumn` given a `CodingKey`.
public init(_ codingKey: some CodingKey) {
self.name = codingKey.stringValue
}
}
-440
View File
@@ -1,440 +0,0 @@
/// A type of SQL expression that is interpreted as a JSON value.
///
/// ## Overview
///
/// JSON values that conform to `SQLJSONExpressible` have two purposes:
///
/// - They provide Swift APIs for accessing their JSON subcomponents at
/// the SQL level.
///
/// - When used in a JSON-building function such as
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)``,
/// they are parsed and interpreted as JSON, not as plain strings.
///
/// To build a JSON value, create a ``JSONColumn``, or call the
/// ``SQLSpecificExpressible/asJSON`` property of any
/// other expression.
///
/// For example, here are some JSON values:
///
/// ```swift
/// // JSON columns:
/// JSONColumn("info")
/// Column("info").asJSON
///
/// // The JSON array [1, 2, 3]:
/// "[1, 2, 3]".databaseValue.asJSON
///
/// // A JSON value that will trigger a
/// // "malformed JSON" SQLite error when
/// // parsed by SQLite:
/// "{foo".databaseValue.asJSON
/// ```
///
/// The expressions below are not JSON values:
///
/// ```swift
/// // A plain column:
/// Column("info")
///
/// // Plain strings:
/// "[1, 2, 3]"
/// "{foo"
/// ```
///
/// ## Access JSON subcomponents
///
/// JSON values provide access to the [`->` and `->>` SQL operators](https://www.sqlite.org/json1.html)
/// and other SQLite JSON functions:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// ## Build JSON objects and arrays from JSON values
///
/// When used in a JSON-building function such as
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)-5iswr``,
/// JSON values are parsed and interpreted as JSON, not as plain strings.
///
/// In the example below, we can see how the `JSONColumn` is interpreted as
/// JSON, while the `Column` with the same name is interpreted as a
/// plain string:
///
/// ```swift
/// let elements: [any SQLExpressible] = [
/// JSONColumn("address"),
/// Column("address"),
/// ]
///
/// let array = Database.jsonArray(elements)
///
/// // SELECT JSON_ARRAY(JSON(address), address) FROM player
/// // → '[{"country":"FR"},"{\"country\":\"FR\"}"]'
/// // <--- object ---> <------ string ------>
/// let json = try Player
/// .select(array, as: String.self)
/// .fetchOne(db)
/// ```
///
/// ## Topics
///
/// ### Accessing JSON subcomponents
///
/// - ``subscript(_:)``
/// - ``jsonExtract(atPath:)``
/// - ``jsonExtract(atPaths:)``
/// - ``jsonRepresentation(atPath:)``
///
/// ### Supporting Types
///
/// - ``AnySQLJSONExpressible``
public protocol SQLJSONExpressible: SQLSpecificExpressible { }
extension ColumnExpression where Self: SQLJSONExpressible {
/// Returns an SQL column that is interpreted as a JSON value.
public var sqlExpression: SQLExpression {
.column(name).withPreferredJSONInterpretation(.jsonValue)
}
}
// This type only grants access to `SQLJSONExpressible` apis. The fact that
// it is a JSON value is embedded in its
// `sqlExpression.preferredJSONInterpretation`.
/// A type-erased ``SQLJSONExpressible``.
public struct AnySQLJSONExpressible: SQLJSONExpressible {
/// An SQL expression that is interpreted as a JSON value.
public let sqlExpression: SQLExpression
public init(_ base: some SQLJSONExpressible) {
self.init(sqlExpression: base.sqlExpression)
}
/// - Precondition: `sqlExpression` is a JSON value
init(sqlExpression: SQLExpression) {
assert(sqlExpression.preferredJSONInterpretation == .jsonValue)
self.sqlExpression = sqlExpression
}
}
extension SQLSpecificExpressible {
/// Returns an expression that is interpreted as a JSON value.
///
/// For example:
///
/// ```swift
/// let info = Column("info").asJSON
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// For more information, see ``SQLJSONExpressible``.
public var asJSON: AnySQLJSONExpressible {
AnySQLJSONExpressible(sqlExpression: sqlExpression.withPreferredJSONInterpretation(.jsonValue))
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public subscript(_ path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
Database.jsonExtract(self, atPath: path)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
Database.jsonExtract(self, atPaths: paths)
}
/// Returns a valid JSON string with the `->` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
}
}
#else
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
public subscript(_ path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
Database.jsonExtract(self, atPath: path)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
Database.jsonExtract(self, atPaths: paths)
}
/// Returns a valid JSON string with the `->` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
}
}
// TODO: Enable when those apis are ready.
// extension ColumnExpression where Self: SQLJSONExpressible {
// /// Updates a columns with the `JSON_PATCH` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_PATCH(address, '{"country": "FR"}')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonPatch(#"{"country": "FR"}"#)
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonPatch(
// with patch: some SQLExpressible)
// -> ColumnAssignment
// {
// .init(columnName: name, value: Database.jsonPatch(self, with: patch))
// }
//
// /// Updates a columns with the `JSON_REMOVE` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonRemove(atPath: "$.country")
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - Parameters:
// /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment {
// .init(columnName: name, value: Database.jsonRemove(self, atPath: path))
// }
//
// /// Updates a columns with the `JSON_REMOVE` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country', '$.city')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonRemove(atPatsh: ["$.country", "$.city"])
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - Parameters:
// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonRemove<C>(atPaths paths: C)
// -> ColumnAssignment
// where C: Collection, C.Element: SQLExpressible
// {
// .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths))
// }
//
// }
#endif
-796
View File
@@ -1,796 +0,0 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.json(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
public static func json(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON", [value.sqlExpression])
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element == any SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
/// Database.jsonArrayLength("[1,2,3,4]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
///
/// - Parameters:
/// - value: A JSON array.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonArrayLength(
_ value: some SQLExpressible,
atPath path: some SQLExpressible)
-> SQLExpression
{
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonInsert<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonReplace<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonSet<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
/// key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.jsonObject(["e": 5])),
/// ])
///
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.json(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
public static func jsonObject<C>(_ elements: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
public static func jsonPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression])
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_VALID` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_VALID('{"x":35') → 0
/// Database.jsonIsValid(#"{"x":35"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
/// The `JSON_QUOTE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_QUOTE('[1]') → '"[1]"'
/// Database.jsonQuote("[1]")
///
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
/// Database.jsonQuote(Database.json("[1]"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
}
}
#else
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.json(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func json(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON", [value.sqlExpression])
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element == any SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
/// Database.jsonArrayLength("[1,2,3,4]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
///
/// - Parameters:
/// - value: A JSON array.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArrayLength(
_ value: some SQLExpressible,
atPath path: some SQLExpressible)
-> SQLExpression
{
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonInsert<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonReplace<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonSet<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
/// key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.jsonObject(["e": 5])),
/// ])
///
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.json(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonObject<C>(_ elements: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression])
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_VALID` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_VALID('{"x":35') → 0
/// Database.jsonIsValid(#"{"x":35"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
/// Returns a valid JSON string with the `JSON_QUOTE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_QUOTE('[1]') → '"[1]"'
/// Database.jsonQuote("[1]")
///
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
/// Database.jsonQuote(Database.json("[1]"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
}
}
#endif
+4 -4
View File
@@ -269,8 +269,8 @@ public struct DatabaseMigrator {
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
let db = try dbResult.get()
if let lastMigration = _migrations.last {
try migrate(db, upTo: lastMigration.identifier)
if let lastMigration = self._migrations.last {
try self.migrate(db, upTo: lastMigration.identifier)
}
completion(.success(db))
} catch {
@@ -409,7 +409,7 @@ public struct DatabaseMigrator {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
let appliedIdentifiers = try appliedIdentifiers(db)
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
@@ -446,7 +446,7 @@ public struct DatabaseMigrator {
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
.appendingPathComponent(ProcessInfo().globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
@@ -222,12 +222,6 @@ extension Association {
relation = relation.unordered()
}
}
public func withStableOrder() -> Self {
withDestinationRelation { relation in
relation = relation.withStableOrder()
}
}
}
// TableRequest conformance
@@ -127,7 +127,7 @@ extension AssociationToMany {
/// }
/// ```
public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -174,7 +174,7 @@ extension AssociationToMany {
/// }
/// ```
public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -221,7 +221,7 @@ extension AssociationToMany {
/// }
/// ```
public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -271,7 +271,7 @@ extension AssociationToMany {
/// }
/// ```
public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
@@ -321,7 +321,7 @@ extension AssociationToMany {
/// }
/// ```
public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("TOTAL", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
// Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)`
@@ -28,23 +28,26 @@
/// }
/// 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 <https://sqlite.org/foreignkeys.html#fk_actions> for
/// more information.
/// 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 `author.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 <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
@@ -28,22 +28,26 @@
/// }
/// 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.
/// 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 <https://sqlite.org/foreignkeys.html#fk_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 `author.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 <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
@@ -29,9 +29,10 @@
/// }
/// 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)
/// }
@@ -39,17 +40,16 @@
///
/// 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
/// <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
/// 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 demographics.
/// 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 <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses a string primary for the country table. But generally
/// speaking, all primary keys are supported.
@@ -100,13 +100,8 @@ extension QueryInterfaceRequest: FetchRequest {
let associations = relation.prefetchedAssociations
if associations.isEmpty == false {
// Eager loading of prefetched associations
preparedRequest.supplementaryFetch = { [relation] db, rows, willExecuteSupplementaryRequest in
try prefetch(
db,
associations: associations,
from: relation,
into: rows,
willExecuteSupplementaryRequest: willExecuteSupplementaryRequest)
preparedRequest.supplementaryFetch = { [relation] db, rows in
try prefetch(db, associations: associations, from: relation, into: rows)
}
}
return preparedRequest
@@ -344,12 +339,6 @@ extension QueryInterfaceRequest: OrderedRequest {
$0.relation = $0.relation.unordered()
}
}
public func withStableOrder() -> QueryInterfaceRequest<RowDecoder> {
with {
$0.relation = $0.relation.withStableOrder()
}
}
}
extension QueryInterfaceRequest: AggregatingRequest {
@@ -1385,14 +1374,11 @@ extension ColumnExpression {
/// - parameter associations: Prefetched associations.
/// - parameter originRows: The rows that need to be extended with prefetched rows.
/// - parameter originQuery: The query that was used to fetch `originRows`.
/// - parameter willExecuteSupplementaryRequest: A closure executed before a
/// supplementary fetch is performed.
private func prefetch(
_ db: Database,
associations: [_SQLAssociation],
from originRelation: SQLRelation,
into originRows: [Row],
willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?) throws
into originRows: [Row]) throws
{
guard let firstOriginRow = originRows.first else {
// No rows -> no prefetch
@@ -1487,10 +1473,6 @@ private func prefetch(
annotatedWith: pivotColumns)
}
if let willExecuteSupplementaryRequest {
// Support for `Database.dumpRequest`
try willExecuteSupplementaryRequest(.init(prefetchRequest), association.keyPath)
}
let prefetchedRows = try prefetchRequest.fetchAll(db)
let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
let groupingIndexes = firstOriginRow.indexes(forColumns: leftColumns)
@@ -442,11 +442,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// make it impractical to define `filter(id:)`, `fetchOne(_:key:)`,
// `deleteAll(_:ids:)` etc.
if let recordType = RowDecoder.self as? any EncodableRecord.Type {
if Sequence.Element.self == Data.self || Sequence.Element.self == Optional<Data>.self {
let strategy = recordType.databaseDataEncodingStrategy
let keys = keys.compactMap { ($0 as! Data?).flatMap(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
} else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
let strategy = recordType.databaseDateEncodingStrategy
let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
@@ -905,7 +901,6 @@ extension AggregatingRequest {
/// - ``orderWhenConnected(_:)``
/// - ``reversed()``
/// - ``unordered()``
/// - ``withStableOrder()``
public protocol OrderedRequest {
/// Sorts the fetched rows according to the given SQL ordering terms.
///
@@ -966,14 +961,6 @@ public protocol OrderedRequest {
/// .unordered()
/// ```
func unordered() -> Self
/// Returns a request with a stable order.
///
/// The returned request lifts ordering ambiguities and always return
/// its results in the same order.
///
/// The purpose of this method is to make requests testable.
func withStableOrder() -> Self
}
extension OrderedRequest {
@@ -1387,7 +1374,6 @@ extension JoinableRequest where Self: SelectionRequest {
/// - ``TableRequest/orderByPrimaryKey()``
/// - ``OrderedRequest/reversed()``
/// - ``OrderedRequest/unordered()``
/// - ``OrderedRequest/withStableOrder()``
///
/// ### Associations
///
-17
View File
@@ -27,7 +27,6 @@ public protocol ColumnExpression: SQLSpecificExpressible {
}
extension ColumnExpression {
/// Returns an SQL column.
public var sqlExpression: SQLExpression {
.column(name)
}
@@ -66,27 +65,11 @@ extension ColumnExpression where Self == Column {
/// A column in a database table.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// var score: Int
/// }
///
/// let maximumScore = try dbQueue.read { db in
/// // SELECT MAX(score) FROM player
/// try Player
/// .select(max(Column("score")), as: Int.self)
/// .fetchOne(db)
/// }
/// ```
///
/// ## Topics
///
/// ### Standard Columns
///
/// - ``rowID-3bn70``
/// - ``rank``
///
/// ### Creating A Column
///
@@ -38,7 +38,7 @@ struct DatabasePromise<T> {
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
try transform(self.resolve(db))
}
}
}
+209 -439
View File
@@ -37,25 +37,6 @@
public struct SQLExpression {
private var impl: Impl
/// The preferred interpretation of the expression in JSON
/// building contexts (see `jsonBuilderExpression`).
///
/// ```swift
/// // Considering:
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → [[1,2,3]]
///
/// // Compare an expression with preferredJSONInterpretation = .unspecified:
/// // JSON_ARRAY("info")
/// Database.jsonArray([Column("info")])
///
/// // ...with an expression with preferredJSONInterpretation = .jsonValue:
/// // JSON_ARRAY(JSON("info"))
/// Database.jsonArray([Column("info").jsonValue])
/// Database.jsonArray([JSONColumn("info")])
/// ```
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
/// The private implementation of the public `SQLExpression`.
private enum Impl {
/// A column.
@@ -165,7 +146,7 @@ public struct SQLExpression {
///
/// <function>(<argument>, ...)
/// <function>(DISTINCT <argument>)
case function(String, flags: SQLFunctionFlags, arguments: [SQLExpression])
case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression])
/// An expression that checks for zero or positive values.
///
@@ -197,90 +178,6 @@ public struct SQLExpression {
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
case qualifiedExists(TableAlias, isNegated: Bool)
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Impl {
switch self {
case .databaseValue,
.qualifiedColumn,
.qualifiedFastPrimaryKey,
.qualifiedExists,
.subquery,
.exists:
return self
case let .column(name):
return .qualifiedColumn(name, alias)
case let .rowValue(expressions):
return .rowValue(expressions.map { $0.qualified(with: alias) })
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .between(
expression: expression,
lowerBound: lowerBound,
upperBound: upperBound,
isNegated: isNegated):
return .between(
expression: expression.qualified(with: alias),
lowerBound: lowerBound.qualified(with: alias),
upperBound: upperBound.qualified(with: alias),
isNegated: isNegated)
case let .binary(op, lhs, rhs):
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .escapableBinary(op, lhs, rhs, escape):
return .escapableBinary(
op,
lhs.qualified(with: alias),
rhs.qualified(with: alias),
escape: escape?.qualified(with: alias))
case let .associativeBinary(op, expressions):
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
case let .in(expression, collection, isNegated: isNegated):
return .in(
expression.qualified(with: alias),
collection.qualified(with: alias),
isNegated: isNegated
)
case let .unary(op, expression):
return .unary(op, expression.qualified(with: alias))
case let .compare(op, lhs, rhs):
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .tableMatch(a, expression):
return .tableMatch(a, expression.qualified(with: alias))
case let .not(expression):
return .not(expression.qualified(with: alias))
case let .collated(expression, collationName):
return .collated(expression.qualified(with: alias), collationName)
case .countAll:
return .countAll
case let .function(name, flags: flags, arguments: arguments):
return .function(
name,
flags: flags,
arguments: arguments.map { $0.qualified(with: alias) })
case let .isEmpty(expression, isNegated: isNegated):
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
case .fastPrimaryKey:
return .qualifiedFastPrimaryKey(alias)
}
}
}
/// `BooleanTest` supports truthiness tests.
@@ -299,7 +196,7 @@ public struct SQLExpression {
/// An associative binary SQL operator, such as `+`, `*`, `AND`, etc.
///
/// Use it with the `joined(operator:)` method. For example:
/// Use an associative operator with the `joined(operator:)` method:
///
/// ```swift
/// // SELECT score + bonus + 1000 FROM player
@@ -309,6 +206,27 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
///
/// ## Topics
///
/// ### Arithmetic Operators
///
/// - ``add``
/// - ``multiply``
///
/// ### Logical Operators
///
/// - ``and``
/// - ``or``
///
/// ### String Operators
///
/// - ``concat``
///
/// ### Bitwise Operators
///
/// - ``bitwiseAnd``
/// - ``bitwiseOr``
public struct AssociativeBinaryOperator: Hashable {
/// The SQL operator
let sql: String
@@ -340,7 +258,7 @@ public struct SQLExpression {
self.isBijective = bijective
}
/// The `+` binary SQL operator.
/// The arithmetic `+` binary SQL operator.
///
/// For example:
///
@@ -348,13 +266,19 @@ public struct SQLExpression {
/// // score + bonus
/// [Column("score"), Column("bonus")].joined(operator: .add)
/// ```
///
/// The neutral value of the `add` operator, used when joining an
/// empty sequence, is `0`.
///
/// The `add` operator performs a numeric addition. To concatenate
/// strings, use the ``concat`` operator instead.
public static let add = AssociativeBinaryOperator(
sql: "+",
neutralValue: 0.databaseValue,
strictlyAssociative: false,
bijective: false)
/// The `*` binary SQL operator.
/// The arithmetic `*` binary SQL operator.
///
/// For example:
///
@@ -362,13 +286,16 @@ public struct SQLExpression {
/// // score * factor
/// [Column("score"), Column("factor")].joined(operator: .multiply)
/// ```
///
/// The neutral value of the `multiply` operator, used when joining an
/// empty sequence, is `1`.
public static let multiply = AssociativeBinaryOperator(
sql: "*",
neutralValue: 1.databaseValue,
strictlyAssociative: false,
bijective: false)
/// The `AND` binary SQL operator.
/// The logical `AND` binary SQL operator.
///
/// For example:
///
@@ -376,13 +303,16 @@ public struct SQLExpression {
/// // isBlue AND isTall
/// [Column("isBlue"), Column("isTall")].joined(operator: .and)
/// ```
///
/// The neutral value of the `and` operator, used when joining an
/// empty sequence, is `true`.
public static let and = AssociativeBinaryOperator(
sql: "AND",
neutralValue: true.databaseValue,
strictlyAssociative: true,
bijective: false)
/// The `OR` binary SQL operator.
/// The logical `OR` binary SQL operator.
///
/// For example:
///
@@ -390,6 +320,9 @@ public struct SQLExpression {
/// // isBlue OR isTall
/// [Column("isBlue"), Column("isTall")].joined(operator: .or)
/// ```
///
/// The neutral value of the `or` operator, used when joining an
/// empty sequence, is `false`.
public static let or = AssociativeBinaryOperator(
sql: "OR",
neutralValue: false.databaseValue,
@@ -404,13 +337,16 @@ public struct SQLExpression {
/// // firstName || ' ' || lastName
/// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat)
/// ```
///
/// The neutral value of the `concat` operator, used when joining an
/// empty sequence, is the empty string.
public static let concat = AssociativeBinaryOperator(
sql: "||",
neutralValue: "".databaseValue,
strictlyAssociative: true,
bijective: true)
/// The `&` bitwise AND SQL operator.
/// The bitwise `&` SQL operator.
///
/// For example:
///
@@ -418,13 +354,17 @@ public struct SQLExpression {
/// // mask & 2
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseAnd)
/// ```
///
/// The neutral value of the `bitwiseAnd` operator, used when
/// joining an empty sequence, is `-1` (the signed 64-bit integer
/// with all bits set).
public static let bitwiseAnd = AssociativeBinaryOperator(
sql: "&",
neutralValue: (-1).databaseValue,
strictlyAssociative: true,
bijective: false)
/// The `|` bitwise OR SQL operator.
/// The bitwise `|` SQL operator.
///
/// For example:
///
@@ -432,6 +372,9 @@ public struct SQLExpression {
/// // mask | 2
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseOr)
/// ```
///
/// The neutral value of the `bitwiseOr` operator, used when
/// joining an empty sequence, is `0`.
public static let bitwiseOr = AssociativeBinaryOperator(
sql: "|",
neutralValue: 0.databaseValue,
@@ -447,22 +390,11 @@ public struct SQLExpression {
/// The SQL operator
let sql: String
/// A boolean value indicating if the operator is known to return a
/// JSON value.
/// Creates a binary operator
///
/// A false value does not provide any information.
let isJSONValue: Bool
/// Creates a binary operator.
///
/// For example:
///
/// ```
/// BinaryOperator("-")
/// ```
init(_ sql: String, isJSONValue: Bool = false) {
/// BinaryOperator("-")
init(_ sql: String) {
self.sql = sql
self.isJSONValue = isJSONValue
}
/// The `<` binary operator
@@ -491,22 +423,6 @@ public struct SQLExpression {
/// The `>>` bitwise right shift operator
static let rightShift = BinaryOperator(">>")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `->` SQL operator
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
/// The `->>` SQL operator
static let jsonExtractSQL = BinaryOperator("->>")
#else
/// The `->` SQL operator
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
/// The `->>` SQL operator
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
static let jsonExtractSQL = BinaryOperator("->>")
#endif
}
/// `EscapableBinaryOperator` is an SQLite binary operator that accepts an
@@ -574,36 +490,6 @@ public struct SQLExpression {
/// The `~` unary operator
static let bitwiseNot = UnaryOperator("~")
}
/// Describes the interpretation of an expression in a JSON
/// building context.
enum JSONInterpretation {
/// JSON interpretation is deferred to SQLite:
///
/// ```swift
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
/// Database.jsonArray(["[1, 2, 3]"])
///
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
/// Database.jsonArray([Database.json("[1, 2, 3]")])
///
/// // JSON_ARRAY("info")
/// Database.jsonArray([Column("info")])
/// ```
case deferredToSQLite
/// Expression is interpreted as a JSON value:
///
/// ```swift
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
/// Database.jsonArray(["[1, 2, 3]"].jsonValue)
///
/// // JSON_ARRAY(JSON("info"))
/// Database.jsonArray([Column("info").jsonValue])
/// Database.jsonArray([JSONColumn("info")])
/// ```
case jsonValue
}
}
// MARK: - Creating Expressions
@@ -923,31 +809,41 @@ extension SQLExpression {
///
/// COUNT(<expression>)
static func count(_ expression: SQLExpression) -> Self {
function("COUNT", [expression])
aggregate("COUNT", [expression])
}
/// The `COUNT(DISTINCT)` function.
///
/// COUNT(DISTINCT <expression>)
static func countDistinct(_ expression: SQLExpression) -> Self {
function("COUNT", [expression], flags: .init(isAggregate: true, isDistinct: true))
distinctAggregate("COUNT", expression)
}
/// A function call.
///
/// <function>(<argument>, ...)
///
/// - warning: for aggregate functions, call one of:
/// - `SQLExpression.aggregate(_:_:)`,
/// - `SQLExpression.distinctAggregate(_:_:)`,
/// - `SQLExpression.countDistinct(_:)`
/// - `SQLExpression.countAll`.
static func function(_ name: String, _ arguments: [SQLExpression]) -> Self {
.init(impl: .function(
name,
flags: .defaultFlags(for: name, argumentCount: arguments.count),
arguments: arguments))
self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments))
}
/// A function call with explicit flags.
/// An aggregate function call.
///
/// <function>(<argument>, ...)
static func function(_ name: String, _ arguments: [SQLExpression], flags: SQLFunctionFlags) -> Self {
.init(impl: .function(name, flags: flags, arguments: arguments))
/// <aggregate>(<argument>, ...)
static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self {
self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments))
}
/// A distinct aggregate function call.
///
/// <aggregate>(DISTINCT <argument>)
static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self {
self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument]))
}
/// An expression that checks for zero or positive values.
@@ -993,27 +889,12 @@ extension SQLExpression {
}
}
// MARK: - Deriving Expressions
extension SQLExpression {
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Self {
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
}
func withPreferredJSONInterpretation(_ interpretation: JSONInterpretation) -> Self {
.init(impl: impl, preferredJSONInterpretation: interpretation)
}
}
// MARK: - Expressions Information
extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
func quotedSQL(_ db: Database) throws -> String {
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
return try sql(context)
}
@@ -1071,7 +952,7 @@ extension SQLExpression {
case let .collated(expression, _):
return try expression.column(db, for: alias, acceptsBijection: acceptsBijection)
case let .function(name, flags: flags, arguments: arguments) where !flags.isAggregate:
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
guard acceptsBijection else {
return nil
}
@@ -1266,11 +1147,11 @@ extension SQLExpression {
case .countAll:
return "COUNT(*)"
case let .function(name, flags: flags, arguments: arguments):
assert(!flags.isDistinct || flags.isAggregate, "distinct requires aggregate")
assert(!flags.isDistinct || arguments.count == 1, "distinct requires a single argument")
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
assert(!distinct || aggregate, "distinct requires aggregate")
assert(!distinct || arguments.count == 1, "distinct requires a single argument")
return try name
+ (flags.isDistinct ? "(DISTINCT " : "(")
+ (distinct ? "(DISTINCT " : "(")
+ arguments.map { try $0.sql(context) }.joined(separator: ", ")
+ ")"
@@ -1681,6 +1562,17 @@ extension SQLExpression {
}
}
private static let knownPureFunctions = [
"ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL",
"IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD",
"LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM",
"NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND",
"RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID",
"SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM",
"TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB",
]
/// Returns true if the expression has a unique value when SQLite runs
/// a request.
///
@@ -1721,8 +1613,13 @@ extension SQLExpression {
let .collated(expression, _):
return expression.isConstantInRequest
case let .function(_, flags: flags, arguments: arguments)
where flags.isPure && !flags.isAggregate:
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
let name = name.uppercased()
guard ((name == "MAX" || name == "MIN") && arguments.count > 1)
|| Self.knownPureFunctions.contains(name)
else {
return false // Don't know - assume not constant
}
return arguments.allSatisfy(\.isConstantInRequest)
@@ -1731,6 +1628,84 @@ extension SQLExpression {
}
}
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> SQLExpression {
switch impl {
case .databaseValue,
.qualifiedColumn,
.qualifiedFastPrimaryKey,
.qualifiedExists,
.subquery,
.exists:
return self
case let .column(name):
return .qualifiedColumn(name, alias)
case let .rowValue(expressions):
assert(!expressions.isEmpty)
return .rowValue(expressions.map { $0.qualified(with: alias) })!
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
return .between(
expression: expression.qualified(with: alias),
lowerBound: lowerBound.qualified(with: alias),
upperBound: upperBound.qualified(with: alias),
isNegated: isNegated)
case let .binary(op, lhs, rhs):
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .escapableBinary(op, lhs, rhs, escape):
return .escapableBinary(
op,
lhs.qualified(with: alias),
rhs.qualified(with: alias),
escape: escape?.qualified(with: alias))
case let .associativeBinary(op, expressions):
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
case let .in(expression, collection, isNegated: isNegated):
return .in(
expression.qualified(with: alias),
collection.qualified(with: alias),
isNegated: isNegated
)
case let .unary(op, expression):
return .unary(op, expression.qualified(with: alias))
case let .compare(op, lhs, rhs):
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .tableMatch(a, expression):
return .tableMatch(a, expression.qualified(with: alias))
case let .not(expression):
return .not(expression.qualified(with: alias))
case let .collated(expression, collationName):
return .collated(expression.qualified(with: alias), collationName)
case .countAll:
return .countAll
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct,
arguments: arguments.map { $0.qualified(with: alias) }))
case let .isEmpty(expression, isNegated: isNegated):
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
case .fastPrimaryKey:
return .qualifiedFastPrimaryKey(alias)
}
}
/// Returns true if the expression is an aggregate.
///
/// When in doubt, returns false.
@@ -1780,10 +1755,8 @@ extension SQLExpression {
return false
case .countAll:
return true
case let .function(_, flags: flags, arguments: _) where flags.isAggregate:
case .countAll,
.function(_, aggregate: true, distinct: _, arguments: _):
return true
default:
@@ -1792,223 +1765,17 @@ extension SQLExpression {
}
}
// MARK: - Function Flags
/// Information about a function
struct SQLFunctionFlags {
/// A boolean value indicating if a function is known to be pure.
///
/// A false value does not provide any information.
var isPure = false
/// A boolean value indicating if a function is known to be
/// an aggregate.
///
/// A false value does not provide any information.
var isAggregate = false
/// A boolean value indicating if the function should have `DISTINCT`
/// in its SQL generation (as in `COUNT(DISTINCT ...)`).
var isDistinct = false
/// A boolean value indicating if a function is known to return a
/// JSON value.
///
/// A false value does not provide any information.
var isJSONValue = false
}
extension SQLFunctionFlags {
// TODO: add missing pure functions:
// https://www.sqlite.org/lang_aggfunc.html
// https://www.sqlite.org/lang_datefunc.html
// https://www.sqlite.org/lang_mathfunc.html
private static let knownPureFunctions: Set<String> = [
"ABS",
"CHAR",
"COALESCE",
"GLOB",
"HEX",
"IFNULL",
"IIF",
"INSTR",
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"LENGTH",
"LIKE",
"LIKELIHOOD",
"LIKELY",
"LOAD_EXTENSION",
"LOWER",
"LTRIM",
"NULLIF",
"PRINTF",
"QUOTE",
"REPLACE",
"ROUND",
"RTRIM",
"SOUNDEX",
"SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED",
"SQLITE_SOURCE_ID",
"SQLITE_VERSION",
"SUBSTR",
"TRIM",
"TYPEOF",
"UNICODE",
"UNLIKELY",
"UPPER",
"ZEROBLOB",
]
private static let knownAggregateFunctions: Set<String> = [
"AVG",
"COUNT",
"GROUP_CONCAT",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"MAX", // when single argument
"MIN", // when single argument
"SUM",
"TOTAL",
]
private static let knownFunctionsReturningJSONValue: Set<String> = [
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
]
/// Infers flags from the function name and number of arguments.
static func defaultFlags(for functionName: String, argumentCount: Int) -> Self {
var flags = SQLFunctionFlags()
let name = functionName.uppercased()
flags.isPure = Self.knownPureFunctions.contains(name)
if (name == "MAX" || name == "MIN") && argumentCount > 1 {
flags.isPure = true
} else {
flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased())
}
if name == "JSON_EXTRACT" && argumentCount > 2 {
flags.isJSONValue = true
} else {
flags.isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
}
return flags
}
}
// MARK: - JSON
extension SQLExpression {
/// A boolean value indicating if the expression is known to be a
/// JSON value.
///
/// A false value does not provide any information.
///
/// For examples:
///
/// ```swift
/// // isJSONValue is true:
/// //
/// // NULL
/// // JSON('[1, 2, 3]')
/// // info -> 'address'
/// DatabaseValue.null
/// Database.json("[1, 2, 3]")
/// JSONColumn("info").jsonRepresentation(forKey: "address")
///
/// // isJSONValue is false
/// //
/// // '[1, 2, 3]'
/// // info
/// // info ->> 'address'
/// [1, 2, 3].databaseValue
/// JSONColumn("info")
/// JSONColumn("info")["address"]
/// ```
var isJSONValue: Bool {
switch impl {
case .databaseValue(.null):
return true
case let .binary(op, _, _):
return op.isJSONValue
case let .collated(expression, _):
return expression.isJSONValue
case let .function(_, flags: flags, arguments: _):
return flags.isJSONValue
default:
return false
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
case .deferredToSQLite:
return self
case .jsonValue:
if isJSONValue {
return self
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
}
#else
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
case .deferredToSQLite:
return self
case .jsonValue:
if isJSONValue {
return self
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
}
#endif
}
// MARK: - SQLExpressible
/// A type that can be used as an SQL expression.
///
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
///
/// ## Topics
///
/// ### Supporting Type
///
/// - ``SQLExpression``
public protocol SQLExpressible {
/// Returns an SQL expression.
var sqlExpression: SQLExpression { get }
@@ -2033,6 +1800,11 @@ extension SQLExpressible where Self == Column {
///
/// ## Topics
///
/// ### Column Expressions
///
/// - ``Column``
/// - ``ColumnExpression``
///
/// ### Applying a Collation
///
/// - ``collating(_:)-2mr78``
@@ -2040,8 +1812,6 @@ extension SQLExpressible where Self == Column {
///
/// ### SQL Functions & Operators
///
/// See also JSON functions in <doc:JSON>.
///
/// - ``abs(_:)-5l6xp``
/// - ``average(_:)``
/// - ``capitalized``
@@ -2062,9 +1832,19 @@ extension SQLExpressible where Self == Column {
/// - ``uppercased``
/// - ``SQLDateModifier``
///
/// ### Interpreting an expression as JSON
/// ### Create SQL Expressions from Sequences
///
/// - ``asJSON``
/// - ``Swift/Sequence/contains(_:)-9i0ld``
/// - ``Swift/Sequence/contains(_:)-o8ic``
/// - ``Swift/Sequence/joined(operator:)-33dy5``
/// - ``Swift/Sequence/joined(operator:)-4k88t``
///
/// ### Create SQL Expressions from Ranges
///
/// - ``Swift/ClosedRange/contains(_:)-64zwp``
/// - ``Swift/ClosedRange/contains(_:)-19a6d``
/// - ``Swift/Range/contains(_:)-11nr0``
/// - ``Swift/Range/contains(_:)-3v32b``
///
/// ### Creating Ordering Terms
///
@@ -2133,13 +1913,8 @@ extension Sequence where Element: SQLSpecificExpressible {
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
/// value of the operator. It is:
///
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
/// value of the operator. See
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
.associativeBinary(`operator`, map(\.sqlExpression))
}
@@ -2151,7 +1926,7 @@ extension Sequence where Element == any SQLSpecificExpressible {
///
/// For example:
///
/// ```
/// ```swift
/// // SELECT * FROM player
/// // WHERE (registered
/// // AND (score >= 1000)
@@ -2164,13 +1939,8 @@ extension Sequence where Element == any SQLSpecificExpressible {
/// ```
///
/// When the sequence is empty, `joined(operator:)` returns the neutral
/// value of the operator. It is:
///
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
/// value of the operator. See
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
.associativeBinary(`operator`, map(\.sqlExpression))
}
+5 -5
View File
@@ -19,7 +19,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// average(Column("length"))
/// ```
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("AVG", [value.sqlExpression])
.aggregate("AVG", [value.sqlExpression])
}
/// The `COUNT` SQL function.
@@ -81,7 +81,7 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// max(Column("score"))
/// ```
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("MAX", [value.sqlExpression])
.aggregate("MAX", [value.sqlExpression])
}
/// The `MIN` SQL function.
@@ -93,7 +93,7 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// min(Column("score"))
/// ```
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("MIN", [value.sqlExpression])
.aggregate("MIN", [value.sqlExpression])
}
/// The `SUM` SQL function.
@@ -109,7 +109,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("SUM", [value.sqlExpression])
.aggregate("SUM", [value.sqlExpression])
}
/// The `TOTAL` SQL function.
@@ -125,7 +125,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("TOTAL", [value.sqlExpression])
.aggregate("TOTAL", [value.sqlExpression])
}
// MARK: - String functions
-15
View File
@@ -282,21 +282,6 @@ extension SQLRelation: Refinable {
}
}
func withStableOrder() -> Self {
with {
// Order by primary key. Don't order by rowid because those are
// not stable: rowids can change after a vacuum.
$0.ordering = $0.ordering.appending(Ordering(orderings: { db in
try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
}))
$0.children = children.mapValues { child in
child.with {
$0.relation = $0.relation.withStableOrder()
}
}
}
}
// Remove ordering iff relation has no LIMIT clause
func unorderedUnlessLimited() -> Self {
if limit != nil {
@@ -1,145 +0,0 @@
enum SQLColumnGenerator {
case columnDefinition(ColumnDefinition)
case columnLiteral(SQL)
/// - parameter tableName: The name of the table that contains
/// the column.
/// - parameter primaryKeyColumns: A closure that returns the
/// primary key columns in the table that contains the column. If
/// the result is nil, the primary key is the hidden rowID.
func sql(
_ db: Database,
tableName: String,
primaryKeyColumns: () throws -> [SQLColumnDescriptor]?)
throws -> String
{
switch self {
case let .columnDefinition(column):
return try columnSQL(
db, column: column,
tableName: tableName,
primaryKeyColumns: primaryKeyColumns)
case let .columnLiteral(sqlLiteral):
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sqlLiteral.sql(context)
}
}
private func columnSQL(
_ db: Database,
column: ColumnDefinition,
tableName: String,
primaryKeyColumns: () throws -> [SQLColumnDescriptor]?)
throws -> String
{
var chunks: [String] = []
chunks.append(column.name.quotedDatabaseIdentifier)
if let type = column.type {
chunks.append(type.rawValue)
}
if let (conflictResolution, autoincrement) = column.primaryKey {
chunks.append("PRIMARY KEY")
if let conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
if autoincrement {
chunks.append("AUTOINCREMENT")
}
}
switch column.notNullConflictResolution {
case .none:
break
case .abort:
chunks.append("NOT NULL")
case let conflictResolution?:
chunks.append("NOT NULL ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
switch column.indexing {
case .none:
break
case .unique(let conflictResolution):
switch conflictResolution {
case .abort:
chunks.append("UNIQUE")
default:
chunks.append("UNIQUE ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
case .index:
break
}
for checkConstraint in column.checkConstraints {
try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))")
}
if let defaultExpression = column.defaultExpression {
try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))")
}
if let collationName = column.collationName {
chunks.append("COLLATE")
chunks.append(collationName)
}
for constraint in column.foreignKeyConstraints {
chunks.append("REFERENCES")
if let column = constraint.destinationColumn {
// explicit referenced column names
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)\
(\(column.quotedDatabaseIdentifier))
""")
} else {
// implicit reference to primary key
let pkColumns: [String]
if constraint.destinationTable.lowercased() == tableName.lowercased() {
// autoreference
let primaryKeyColumns = try primaryKeyColumns() ?? [.rowID]
pkColumns = primaryKeyColumns.map(\.name)
} else {
pkColumns = try db.primaryKey(constraint.destinationTable).columns
}
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)\
(\(pkColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))
""")
}
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if constraint.isDeferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
}
if let constraint = column.generatedColumnConstraint {
try chunks.append("GENERATED ALWAYS AS (\(constraint.expression.quotedSQL(db)))")
let qualificationLiteral: String
switch constraint.qualification {
case .stored:
qualificationLiteral = "STORED"
case .virtual:
qualificationLiteral = "VIRTUAL"
}
chunks.append(qualificationLiteral)
}
return chunks.joined(separator: " ")
}
}
@@ -172,21 +172,15 @@ class StatementArgumentsSink {
private(set) var arguments: StatementArguments
private let rawSQL: Bool
/// A sink which turns all argument values into SQL literals.
///
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
/// `WHERE name = 'O''Brien'` SQL.
static let literalValues = StatementArgumentsSink(rawSQL: true)
/// A sink which does not accept any arguments.
static let forRawSQL = StatementArgumentsSink(rawSQL: true)
private init(rawSQL: Bool) {
self.arguments = []
self.rawSQL = rawSQL
}
/// A sink which turns all argument values into `?` SQL parameters.
///
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
/// `WHERE name = ?` SQL.
/// A sink which accepts arguments
convenience init() {
self.init(rawSQL: false)
}
@@ -431,15 +425,6 @@ public class TableAlias {
expression.sqlExpression.qualified(with: self)
}
public subscript(_ expression: some SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm)
-> AnySQLJSONExpressible
{
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
}
/// Returns an SQL ordering term that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
@@ -1,42 +0,0 @@
struct SQLIndexGenerator {
let name: String
let table: String
let expressions: [SQLExpression]
let options: IndexOptions
let condition: SQLExpression?
func sql(_ db: Database) throws -> String {
var sql: SQL = "CREATE"
if options.contains(.unique) {
sql += " UNIQUE"
}
sql += " INDEX"
if options.contains(.ifNotExists) {
sql += " IF NOT EXISTS"
}
sql += " \(identifier: name) ON \(identifier: table)("
sql += expressions.map { SQL($0) }.joined(separator: ", ")
sql += ")"
if let condition {
sql += " WHERE \(condition)"
}
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sql.sql(context)
}
}
extension SQLIndexGenerator {
init(index: IndexDefinition) {
name = index.name
table = index.table
expressions = index.expressions
options = index.options
condition = index.condition
}
}
@@ -566,8 +566,8 @@ private struct SQLQualifiedRelation {
/// The full selection, including selection of joined relations
var selectionPromise: DatabasePromise<[SQLSelection]> {
DatabasePromise { db in
let selection = try sourceSelectionPromise.resolve(db)
return try joins.values.reduce(into: selection) { selection, join in
let selection = try self.sourceSelectionPromise.resolve(db)
return try self.joins.values.reduce(into: selection) { selection, join in
let joinedSelection = try join.relation.selectionPromise.resolve(db)
selection.append(contentsOf: joinedSelection)
}
@@ -1,84 +0,0 @@
struct SQLTableAlterationGenerator {
private enum TableAlterationKind {
case addColumn(SQLColumnGenerator)
case addIndex(SQLIndexGenerator)
case renameColumn(old: String, new: String)
case dropColumn(String)
}
private var name: String
private var alterations: [TableAlterationKind] = []
func sql(_ db: Database) throws -> String {
var statements: [String] = []
for alteration in alterations {
switch alteration {
case let .addColumn(column):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ADD COLUMN")
let sql = try column.sql(db, tableName: name, primaryKeyColumns: {
try db.primaryKey(name).columnInfos.map { columnInfos in
columnInfos.map { SQLColumnDescriptor($0) }
}
})
chunks.append(sql)
let statement = chunks.joined(separator: " ")
statements.append(statement)
case let .addIndex(index):
try statements.append(index.sql(db))
case let .renameColumn(oldName, newName):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("RENAME COLUMN")
chunks.append(oldName.quotedDatabaseIdentifier)
chunks.append("TO")
chunks.append(newName.quotedDatabaseIdentifier)
let statement = chunks.joined(separator: " ")
statements.append(statement)
case let .dropColumn(column):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("DROP COLUMN")
chunks.append(column.quotedDatabaseIdentifier)
let statement = chunks.joined(separator: " ")
statements.append(statement)
}
}
return statements.joined(separator: "; ")
}
}
extension SQLTableAlterationGenerator {
init(_ tableAlteration: TableAlteration) {
self.name = tableAlteration.name
self.alterations = []
for alteration in tableAlteration.alterations {
switch alteration {
case let .add(column):
alterations.append(.addColumn(.columnDefinition(column)))
if let indexDefinition = column.indexDefinition(in: name) {
alterations.append(.addIndex(SQLIndexGenerator(index: indexDefinition)))
}
case let .addColumnLiteral(sql):
alterations.append(.addColumn(.columnLiteral(sql)))
case let .rename(old: oldName, new: newName):
alterations.append(.renameColumn(old: oldName, new: newName))
case let .drop(column):
alterations.append(.dropColumn(column))
}
}
}
}
@@ -1,476 +0,0 @@
struct SQLTableGenerator {
var name: String
var options: TableOptions
var columnGenerators: [SQLColumnGenerator]
/// Used for auto-referencing foreign keys: we need to know the columns
/// of the primary key before they exist in the database schema, hence
/// the name of "forward" primary key columns.
///
/// If nil, the primary key is the hidden rowID.
var forwardPrimaryKeyColumns: [SQLColumnDescriptor]?
var primaryKeyConstraint: KeyConstraint?
var uniqueKeyConstraints: [KeyConstraint]
var foreignKeyConstraints: [SQLForeignKeyConstraint]
var checkConstraints: [SQLExpression]
var literalConstraints: [SQL]
var indexGenerators: [SQLIndexGenerator]
struct KeyConstraint {
var columns: [String]
var conflictResolution: Database.ConflictResolution?
}
func sql(_ db: Database) throws -> String {
var statements: [String] = []
do {
var chunks: [String] = []
chunks.append("CREATE")
if options.contains(.temporary) {
chunks.append("TEMPORARY")
}
chunks.append("TABLE")
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
do {
var items: [String] = []
try items.append(contentsOf: columnGenerators.map {
try $0.sql(db, tableName: name, primaryKeyColumns: { forwardPrimaryKeyColumns })
})
if let constraint = primaryKeyConstraint {
var chunks: [String] = []
chunks.append("PRIMARY KEY")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
if let conflictResolution = constraint.conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for constraint in uniqueKeyConstraints {
var chunks: [String] = []
chunks.append("UNIQUE")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
if let conflictResolution = constraint.conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for constraint in foreignKeyConstraints {
var chunks: [String] = []
chunks.append("FOREIGN KEY")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
chunks.append("REFERENCES")
if let destinationColumns = constraint.destinationColumns {
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(destinationColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
} else if constraint.destinationTable.lowercased() == name.lowercased() {
// autoreference
let forwardPrimaryKeyColumns = forwardPrimaryKeyColumns ?? [.rowID]
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(forwardPrimaryKeyColumns.map(\.name.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
} else {
let primaryKey = try db.primaryKey(constraint.destinationTable)
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(primaryKey.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
}
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if constraint.isDeferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
items.append(chunks.joined(separator: " "))
}
for checkExpression in checkConstraints {
var chunks: [String] = []
try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))")
items.append(chunks.joined(separator: " "))
}
for literal in literalConstraints {
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
try items.append(literal.sql(context))
}
chunks.append("(\(items.joined(separator: ", ")))")
}
var tableOptions: [String] = []
#if GRDBCUSTOMSQLITE || GRDBCIPHER
if options.contains(.strict) {
tableOptions.append("STRICT")
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
if options.contains(.strict) {
tableOptions.append("STRICT")
}
}
#endif
if options.contains(.withoutRowID) {
tableOptions.append("WITHOUT ROWID")
}
if !tableOptions.isEmpty {
chunks.append(tableOptions.joined(separator: ", "))
}
statements.append(chunks.joined(separator: " "))
}
let indexStatements = try indexGenerators.map { try $0.sql(db) }
statements.append(contentsOf: indexStatements)
return statements.joined(separator: "; ")
}
private struct ForeignKeyGenerator {
var columnNames: [String]
var columnGenerators: [SQLColumnGenerator]
var foreignKeyConstraint: SQLForeignKeyConstraint?
var indexGenerator: SQLIndexGenerator?
}
}
extension SQLTableGenerator {
init(_ db: Database, table: TableDefinition) throws {
var indexOptions: IndexOptions = []
if table.options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) }
func makeKeyConstraint(
_ db: Database,
constraint: TableDefinition.KeyConstraint,
forwardPrimaryKey: SQLPrimaryKeyDescriptor)
throws -> SQLTableGenerator.KeyConstraint
{
try SQLTableGenerator.KeyConstraint(
columns: constraint.components.flatMap { component -> [String] in
switch component {
case let .columnName(columnName):
return [columnName]
case let .columnDefinition(column):
return [column.name]
case let .foreignKeyDefinition(foreignKey):
return try Self.makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: table.name,
forwardPrimaryKey: forwardPrimaryKey,
indexOptions: indexOptions).columnNames
}
},
conflictResolution: constraint.conflictResolution)
}
var forwardPrimaryKeyColumns: [SQLColumnDescriptor]?
if let primaryKeyConstraint = table.primaryKeyConstraint {
forwardPrimaryKeyColumns = try Self.forwardPrimaryKeyColumns(
db, primaryKeyConstraint: primaryKeyConstraint,
originTable: table.name)
} else {
for component in table.columnComponents {
if case let .columnDefinition(column) = component, column.primaryKey != nil {
forwardPrimaryKeyColumns = [SQLColumnDescriptor(column)]
break
}
}
}
let forwardPrimaryKey = SQLPrimaryKeyDescriptor(
tableName: table.name,
primaryKeyColumns: forwardPrimaryKeyColumns)
var columnGenerators: [SQLColumnGenerator] = []
var foreignKeyConstraints: [SQLForeignKeyConstraint] = []
var indexGenerators: [SQLIndexGenerator] = []
for component in table.columnComponents {
switch component {
case let .columnDefinition(column):
columnGenerators.append(.columnDefinition(column))
case let .columnLiteral(sql):
columnGenerators.append(.columnLiteral(sql))
case let .foreignKeyDefinition(foreignKey):
let fkGenerator = try Self.makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: table.name,
forwardPrimaryKey: forwardPrimaryKey,
indexOptions: indexOptions)
columnGenerators.append(contentsOf: fkGenerator.columnGenerators)
if let indexGenerator = fkGenerator.indexGenerator {
indexGenerators.append(indexGenerator)
}
if let foreignKeyConstraint = fkGenerator.foreignKeyConstraint {
foreignKeyConstraints.append(foreignKeyConstraint)
}
case let .foreignKeyConstraint(constraint):
foreignKeyConstraints.append(constraint)
}
}
for columnGenerator in columnGenerators {
if case let .columnDefinition(column) = columnGenerator,
let index = column.indexDefinition(in: table.name, options: indexOptions)
{
indexGenerators.append(SQLIndexGenerator(index: index))
}
}
try self.init(
name: table.name,
options: table.options,
columnGenerators: columnGenerators,
forwardPrimaryKeyColumns: forwardPrimaryKeyColumns,
primaryKeyConstraint: table.primaryKeyConstraint.map {
try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey)
},
uniqueKeyConstraints: table.uniqueKeyConstraints.map {
try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey)
},
foreignKeyConstraints: foreignKeyConstraints,
checkConstraints: table.checkConstraints,
literalConstraints: table.literalConstraints,
indexGenerators: indexGenerators)
}
private static func forwardPrimaryKeyColumns(
_ db: Database,
primaryKeyConstraint: TableDefinition.KeyConstraint,
originTable: String)
throws -> [SQLColumnDescriptor]?
{
var forwardPrimaryKeyColumns: [SQLColumnDescriptor] = []
for component in primaryKeyConstraint.components {
switch component {
case let .columnDefinition(column):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column))
case let .foreignKeyDefinition(foreignKey):
let fkGenerator = try makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: originTable,
forwardPrimaryKey: nil, // not known yet, since we're building it
indexOptions: [])
for columnGenerator in fkGenerator.columnGenerators {
switch columnGenerator {
case let .columnDefinition(column):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column))
case .columnLiteral:
// Unknown column name
return nil
}
}
case let .columnName(name):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(name: name, type: nil))
}
}
return forwardPrimaryKeyColumns
}
private static func makeForeignKeyGenerator(
_ db: Database,
foreignKey: ForeignKeyDefinition,
originTable: String,
forwardPrimaryKey: SQLPrimaryKeyDescriptor?,
indexOptions: IndexOptions)
throws -> ForeignKeyGenerator
{
let destinationPrimaryKey: SQLPrimaryKeyDescriptor
if let table = foreignKey.table {
if let forwardPrimaryKey,
originTable.lowercased() == table.lowercased()
{
// autoreference
destinationPrimaryKey = forwardPrimaryKey
} else {
destinationPrimaryKey = try foreignKey.primaryKey(db)
}
} else {
if let forwardPrimaryKey,
originTable.singularized.lowercased() == foreignKey.name.singularized.lowercased()
{
// autoreference
destinationPrimaryKey = forwardPrimaryKey
} else {
destinationPrimaryKey = try foreignKey.primaryKey(db)
}
}
guard let primaryKeyColumns = destinationPrimaryKey.primaryKeyColumns else {
// Destination table has an hidden rowID primary key
let columnName = foreignKey.name + "Id"
let column = ColumnDefinition(name: columnName, type: .integer).references(
destinationPrimaryKey.tableName,
onDelete: foreignKey.deleteAction,
onUpdate: foreignKey.updateAction,
deferred: foreignKey.isDeferred)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
switch foreignKey.indexing {
case nil:
break
case .index:
column.indexed()
case .unique:
column.unique()
}
return ForeignKeyGenerator(
columnNames: [columnName],
columnGenerators: [SQLColumnGenerator.columnDefinition(column)],
foreignKeyConstraint: nil,
indexGenerator: nil)
}
assert(!primaryKeyColumns.isEmpty)
let columnNames = primaryKeyColumns.map {
foreignKey.name + $0.name.uppercasingFirstCharacter
}
if primaryKeyColumns.count == 1 {
// Destination table has a single column primary key
let pkColumn = primaryKeyColumns[0]
let columnName = columnNames[0]
let column = ColumnDefinition(name: columnName, type: pkColumn.type).references(
destinationPrimaryKey.tableName,
column: pkColumn.name,
onDelete: foreignKey.deleteAction,
onUpdate: foreignKey.updateAction,
deferred: foreignKey.isDeferred)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
switch foreignKey.indexing {
case nil:
break
case .index:
column.indexed()
case .unique:
column.unique()
}
return ForeignKeyGenerator(
columnNames: [columnName],
columnGenerators: [SQLColumnGenerator.columnDefinition(column)],
foreignKeyConstraint: nil,
indexGenerator: nil)
} else {
// Destination table has a composite primary key
let columnGenerators = zip(primaryKeyColumns, columnNames).map { pkColumn, columnName in
let column = ColumnDefinition(name: columnName, type: pkColumn.type)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
return SQLColumnGenerator.columnDefinition(column)
}
let foreignKeyConstraint = SQLForeignKeyConstraint(
columns: columnNames,
destinationTable: destinationPrimaryKey.tableName,
destinationColumns: nil,
deleteAction: foreignKey.deleteAction,
updateAction: foreignKey.updateAction,
isDeferred: foreignKey.isDeferred)
let indexGenerator: SQLIndexGenerator?
switch foreignKey.indexing {
case nil:
indexGenerator = nil
case .index:
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
expressions: columnNames.map { .column($0) },
options: indexOptions,
condition: nil)
case .unique:
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
expressions: columnNames.map { .column($0) },
options: indexOptions.union([.unique]),
condition: nil)
}
return ForeignKeyGenerator(
columnNames: columnNames,
columnGenerators: columnGenerators,
foreignKeyConstraint: foreignKeyConstraint,
indexGenerator: indexGenerator)
}
}
}
struct SQLColumnDescriptor {
static let rowID = SQLColumnDescriptor(name: Column.rowID.name, type: .integer)
var name: String
var type: Database.ColumnType?
}
extension SQLColumnDescriptor {
init(_ column: ColumnInfo) {
self.init(
name: column.name,
type: column.columnType)
}
init(_ column: ColumnDefinition) {
self.init(name: column.name, type: column.type)
}
}
struct SQLForeignKeyConstraint {
var columns: [String]
var destinationTable: String
var destinationColumns: [String]?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var isDeferred: Bool
}
struct SQLPrimaryKeyDescriptor {
/// The name of the forward-declared table
var tableName: String
/// If nil, the primary key is the hidden rowID.
var primaryKeyColumns: [SQLColumnDescriptor]?
}
extension SQLPrimaryKeyDescriptor {
static func find(_ db: Database, table: String) throws -> Self {
let columnInfos = try db.primaryKey(table).columnInfos
return SQLPrimaryKeyDescriptor(
tableName: table,
primaryKeyColumns: columnInfos.map { columnInfos in
columnInfos.map { SQLColumnDescriptor($0) }
})
}
}
@@ -38,15 +38,6 @@ extension SQLInterpolation {
appendInterpolation(type(of: record))
}
/// Appends a quoted identifier.
///
/// // INSERT INTO "group" ...
/// let tableName = "group"
/// let request: SQLRequest<Player> = "INSERT INTO \(identifier: tableName) ..."
public mutating func appendInterpolation(identifier: String) {
appendLiteral(identifier.quotedDatabaseIdentifier)
}
/// Appends the table name of the record.
///
/// // INSERT INTO player ...
@@ -1,567 +0,0 @@
/// Describes a database column.
///
/// You get instances of `ColumnDefinition` when you create or alter a database
/// tables. For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.column("name", .text) // ColumnDefinition
/// }
///
/// try db.alter(table: "player") { t in
/// t.add(column: "score", .integer) // ColumnDefinition
/// }
/// ```
///
/// See ``TableDefinition/column(_:_:)`` and ``TableAlteration/add(column:_:)``.
///
/// Related SQLite documentation:
///
/// - <https://www.sqlite.org/lang_createtable.html>
/// - <https://www.sqlite.org/lang_altertable.html>
///
/// ## Topics
///
/// ### Foreign Keys
///
/// - ``references(_:column:onDelete:onUpdate:deferred:)``
///
/// ### Indexes
///
/// - ``indexed()``
/// - ``unique(onConflict:)``
///
/// ### Default value
///
/// - ``defaults(to:)``
/// - ``defaults(sql:)``
///
/// ### Collations
///
/// - ``collate(_:)-4dljx``
/// - ``collate(_:)-9ywza``
///
/// ### Generated Columns
///
/// - ``generatedAs(_:_:)``
/// - ``generatedAs(sql:_:)``
/// - ``GeneratedColumnQualification``
///
/// ### Other Constraints
///
/// - ``check(_:)``
/// - ``check(sql:)``
/// - ``notNull(onConflict:)``
///
/// ### Sunsetted Methods
///
/// Those are legacy interfaces that are preserved for backwards compatibility.
/// Their use is not recommended.
///
/// - ``primaryKey(onConflict:autoincrement:)``
public final class ColumnDefinition {
enum Indexing {
case index
case unique(Database.ConflictResolution)
}
struct ForeignKeyConstraint {
var destinationTable: String
var destinationColumn: String?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var isDeferred: Bool
}
/// The kind of a generated column.
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
public enum GeneratedColumnQualification {
/// A `VIRTUAL` generated column.
case virtual
/// A `STORED` generated column.
case stored
}
struct GeneratedColumnConstraint {
var expression: SQLExpression
var qualification: GeneratedColumnQualification
}
let name: String
let type: Database.ColumnType?
var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
var indexing: Indexing?
var notNullConflictResolution: Database.ConflictResolution?
var checkConstraints: [SQLExpression] = []
var foreignKeyConstraints: [ForeignKeyConstraint] = []
var defaultExpression: SQLExpression?
var collationName: String?
var generatedColumnConstraint: GeneratedColumnConstraint?
init(name: String, type: Database.ColumnType?) {
self.name = name
self.type = type
}
/// Adds a primary key constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id TEXT NOT NULL PRIMARY KEY
/// // )
/// try db.create(table: "player") { t in
/// t.primaryKey("id", .text)
/// }
/// ```
///
/// - important: Make sure you add a not null constraint on your primary key
/// column, as in the above example, or SQLite will allow null values.
/// See <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
/// for more information.
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``TableDefinition/primaryKey(_:_:onConflict:)``
/// instead.
///
/// - parameters:
/// - conflictResolution: An optional ``Database/ConflictResolution``.
/// - autoincrement: If true, the primary key is autoincremented.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func primaryKey(
onConflict conflictResolution: Database.ConflictResolution? = nil,
autoincrement: Bool = false)
-> Self
{
primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement)
return self
}
/// Adds a not null constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT NOT NULL
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).notNull()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#notnullconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
notNullConflictResolution = conflictResolution ?? .abort
return self
}
/// Adds a unique constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT UNIQUE
/// // )
/// try db.create(table: "player") { t in
/// t.column("email", .text).unique()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#uniqueconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
indexing = .unique(conflictResolution ?? .abort)
return self
}
/// Adds an index.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(email TEXT);
/// // CREATE INDEX player_on_email ON player(email);
/// try db.create(table: "player") { t in
/// t.column("email", .text).indexed()
/// }
/// ```
///
/// The name of the created index is `<table>_on_<column>`, where `table`
/// and `column` are the names of the table and the column. See the
/// example above.
///
/// See also ``unique(onConflict:)``.
///
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func indexed() -> Self {
if case .none = indexing {
self.indexing = .index
}
return self
}
/// Adds a check constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT CHECK (LENGTH(name) > 0)
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).check { length($0) > 0 }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter condition: A closure whose argument is a ``Column`` that
/// represents the defined column, and returns the expression to check.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func check(_ condition: (Column) -> any SQLExpressible) -> Self {
checkConstraints.append(condition(Column(name)).sqlExpression)
return self
}
/// Adds a check constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT CHECK (LENGTH(name) > 0)
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter sql: An SQL snippet.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func check(sql: String) -> Self {
checkConstraints.append(SQL(sql: sql).sqlExpression)
return self
}
/// Defines the default value.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT DEFAULT 'Anonymous'
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).defaults(to: "Anonymous")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#dfltval>
///
/// - parameter value: A ``DatabaseValueConvertible`` value.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func defaults(to value: some DatabaseValueConvertible) -> Self {
defaultExpression = value.sqlExpression
return self
}
/// Defines the default value.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP
/// // )
/// try db.create(table: "player") { t in
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#dfltval>
///
/// - parameter sql: An SQL snippet.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func defaults(sql: String) -> Self {
defaultExpression = SQL(sql: sql).sqlExpression
return self
}
/// Defines the default collation.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT COLLATE NOCASE
/// // )
/// try db.create(table: "player") { t in
/// t.column("email", .text).collate(.nocase)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collation>
///
/// - parameter collation: A ``Database/CollationName``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: Database.CollationName) -> Self {
collationName = collation.rawValue
return self
}
/// Defines the default collation.
///
/// For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collation>
///
/// - parameter collation: A ``DatabaseCollation``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: DatabaseCollation) -> Self {
collationName = collation.name
return self
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - sql: An SQL expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func generatedAs(
sql: String,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
let expression = SQL(sql: sql).sqlExpression
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression,
qualification: qualification)
return self
}
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - expression: The generated expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func generatedAs(
_ expression: some SQLExpressible,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression.sqlExpression,
qualification: qualification)
return self
}
#else
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - sql: An SQL expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
sql: String,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
let expression = SQL(sql: sql).sqlExpression
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression,
qualification: qualification)
return self
}
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - expression: The generated expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
_ expression: some SQLExpressible,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression.sqlExpression,
qualification: qualification)
return self
}
#endif
/// Adds a foreign key constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE book(
/// // authorId INTEGER REFERENCES author(id) ON DELETE CASCADE
/// // )
/// try db.create(table: "book") { t in
/// t.column("authorId", .integer).references("author", onDelete: .cascade)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
///
/// - parameters:
/// - table: The referenced table.
/// - column: The referenced column in the referenced table. If not
/// specified, the column of the primary key of the referenced table
/// is used.
/// - deleteAction: Optional action when the referenced row is deleted.
/// - updateAction: Optional action when the referenced row is updated.
/// - isDeferred: A boolean value indicating whether the foreign key
/// constraint is deferred.
/// See <https://www.sqlite.org/foreignkeys.html#fk_deferred>.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func references(
_ table: String,
column: String? = nil,
onDelete deleteAction: Database.ForeignKeyAction? = nil,
onUpdate updateAction: Database.ForeignKeyAction? = nil,
deferred isDeferred: Bool = false) -> Self
{
foreignKeyConstraints.append(ForeignKeyConstraint(
destinationTable: table,
destinationColumn: column,
deleteAction: deleteAction,
updateAction: updateAction,
isDeferred: isDeferred))
return self
}
func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? {
switch indexing {
case .none: return nil
case .unique: return nil
case .index:
return IndexDefinition(
name: "\(table)_on_\(name)",
table: table,
expressions: [.column(name)],
options: options,
condition: nil)
}
}
}
@@ -1,694 +0,0 @@
extension Database {
// MARK: - Database Schema
/// Creates a database table.
///
/// For example:
///
/// ```swift
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
/// ```
///
/// Related SQLite documentation:
/// - <https://www.sqlite.org/lang_createtable.html>
/// - <https://www.sqlite.org/withoutrowid.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(table:options:body:)`` instead.
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
withoutRowID: Bool = false,
body: (TableDefinition) throws -> Void)
throws
{
var options: TableOptions = []
if temporary { options.insert(.temporary) }
if ifNotExists { options.insert(.ifNotExists) }
if withoutRowID { options.insert(.withoutRowID) }
try create(table: name, options: options, body: body)
}
/// Creates a database table.
///
/// ### Reference documentation
///
/// SQLite has many reference documents about table creation. They are a
/// great learning material:
///
/// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html)
/// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html)
/// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)
/// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html)
/// - [Rowid Tables](https://www.sqlite.org/rowidtable.html)
/// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html)
/// - [STRICT Tables](https://www.sqlite.org/stricttables.html)
///
/// ### Usage
///
/// ```swift
/// // CREATE TABLE place (
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // title TEXT,
/// // isFavorite BOOLEAN NOT NULL DEFAULT 0,
/// // latitude DOUBLE NOT NULL,
/// // longitude DOUBLE NOT NULL
/// // )
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("isFavorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
/// ```
///
/// ### Configure table creation
///
/// Use the `options` parameter to configure table creation
/// (see ``TableOptions``):
///
/// ```swift
/// // CREATE TABLE player ( ... )
/// try db.create(table: "player") { t in ... }
///
/// // CREATE TEMPORARY TABLE player IF NOT EXISTS (
/// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
/// ```
///
/// ### Add columns
///
/// Add columns with their name and eventual type (`text`, `integer`,
/// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`
/// and `any`) - see ``Database/ColumnType``:
///
/// ```swift
/// // CREATE TABLE example (
/// // a,
/// // name TEXT,
/// // creationDate DATETIME,
/// try db.create(table: "example") { t in
/// t.column("a")
/// t.column("name", .text)
/// t.column("creationDate", .datetime)
/// ```
///
/// The `column()` method returns a ``ColumnDefinition`` that you can
/// further configure:
///
/// ### Not null constraints, default values
///
/// ```swift
/// // email TEXT NOT NULL,
/// t.column("email", .text).notNull()
///
/// // name TEXT DEFAULT 'O''Reilly',
/// t.column("name", .text).defaults(to: "O'Reilly")
///
/// // flag BOOLEAN NOT NULL DEFAULT 0,
/// t.column("flag", .boolean).notNull().defaults(to: false)
///
/// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP,
/// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP")
/// ```
///
/// ### Primary, unique, and foreign keys
///
/// Use an individual column as **primary**, **unique**, or **foreign key**.
/// When defining a foreign key, the referenced column is the primary key of
/// the referenced table (unless you specify otherwise):
///
/// ```swift
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// t.autoIncrementedPrimaryKey("id")
///
/// // uuid TEXT NOT NULL PRIMARY KEY,
/// t.primaryKey("uuid", .text)
///
/// // email TEXT UNIQUE,
/// t.column("email", .text)
/// .unique()
///
/// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
/// t.column("countryCode", .text)
/// .references("country", onDelete: .cascade)
/// ```
///
/// Primary, unique and foreign keys can also be added on several columns:
///
/// ```swift
/// // a INTEGER NOT NULL,
/// // b TEXT NOT NULL,
/// // PRIMARY KEY (a, b)
/// t.primaryKey {
/// t.column("a", .integer)
/// t.column("b", .text)
/// }
///
/// // a INTEGER NOT NULL,
/// // b TEXT NOT NULL,
/// // PRIMARY KEY (a, b)
/// t.column("a", .integer).notNull()
/// t.column("b", .text).notNull()
/// t.primaryKey(["a", "b"])
///
/// // a INTEGER,
/// // b TEXT,
/// // UNIQUE (a, b) ON CONFLICT REPLACE
/// t.column("a", .integer)
/// t.column("b", .text)
/// t.uniqueKey(["a", "b"], onConflict: .replace)
///
/// // a INTEGER,
/// // b TEXT,
/// // FOREIGN KEY (a, b) REFERENCES parents(c, d)
/// t.column("a", .integer)
/// t.column("b", .text)
/// t.foreignKey(["a", "b"], references: "parents")
/// ```
///
/// > Tip: when you need an integer primary key that automatically generates
/// unique values, it is recommended that you use the
/// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method:
/// >
/// > ```swift
/// > try db.create(table: "example") { t in
/// > t.autoIncrementedPrimaryKey("id")
/// > ...
/// > }
/// > ```
/// >
/// > The reason for this recommendation is that auto-incremented primary
/// > keys forbid the reuse of ids. This prevents your app or
/// > <doc:DatabaseObservation> to think that a row was updated, when it was
/// > actually deleted and replaced. Depending on your application needs,
/// > this may be acceptable. But usually it is not.
///
/// ### Indexed columns
///
/// ```swift
/// t.column("score", .integer).indexed()
/// ```
///
/// For extra index options, see ``create(indexOn:columns:options:condition:)``.
///
/// ### Generated columns
///
/// See [Generated columns](https://sqlite.org/gencol.html) for
/// more information:
///
/// ```swift
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// ```
///
/// ### Integrity checks
///
/// SQLite will only let conforming rows in:
///
/// ```swift
/// // name TEXT CHECK (LENGTH(name) > 0)
/// t.column("name", .text).check { length($0) > 0 }
///
/// // score INTEGER CHECK (score > 0)
/// t.column("score", .integer).check(sql: "score > 0")
///
/// // CHECK (a + b < 10),
/// t.check(Column("a") + Column("b") < 10)
///
/// // CHECK (a + b < 10)
/// t.check(sql: "a + b < 10")
/// ```
///
/// ### Raw SQL columns and constraints
///
/// Columns and constraints can be defined with raw sql:
///
/// ```swift
/// t.column(sql: "name TEXT")
/// t.constraint(sql: "CHECK (a + b < 10)")
/// ```
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let defaultName = "O'Reilly"
/// t.column(literal: "name TEXT DEFAULT \(defaultName)")
///
/// let forbiddenName = "admin"
/// t.constraint(literal: "CHECK (name <> \(forbiddenName))")
/// ```
///
/// - parameters:
/// - name: The table name.
/// - options: Table creation options.
/// - body: A closure that defines table columns and constraints.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
table name: String,
options: TableOptions = [],
body: (TableDefinition) throws -> Void)
throws
{
let table = TableDefinition(
name: name,
options: options)
try body(table)
let generator = try SQLTableGenerator(self, table: table)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Renames a database table.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func rename(table name: String, to newName: String) throws {
try execute(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)")
}
/// Modifies a database table.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.add(column: "url", .text)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameters:
/// - name: The table name.
/// - body: A closure that defines table alterations.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func alter(table name: String, body: (TableAlteration) -> Void) throws {
let alteration = TableAlteration(name: name)
body(alteration)
let generator = SQLTableAlterationGenerator(alteration)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Deletes a database table.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_droptable.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(table name: String) throws {
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
/// Creates a database view.
///
/// You can create a view with an ``SQLRequest``:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(view: "hero", as: SQLRequest(literal: """
/// SELECT * FROM player WHERE isHero == 1
/// """)
/// ```
///
/// You can also create a view with a ``QueryInterfaceRequest``:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(
/// view: "hero",
/// as: Player.filter(Column("isHero") == true))
/// ```
///
/// When creating views in <doc:Migrations>, it is not recommended to
/// use record types defined in the application. Instead of the `Player`
/// record type, prefer `Table("player")`:
///
/// ```swift
/// // RECOMMENDED IN MIGRATIONS
/// try db.create(
/// view: "hero",
/// as: Table("player").filter(Column("isHero") == true))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createview.html>
///
/// - parameters:
/// - view: The view name.
/// - options: View creation options.
/// - columns: The columns of the view. If nil, the columns are the
/// columns of the request.
/// - request: The request that feeds the view.
public func create(
view name: String,
options: ViewOptions = [],
columns: [String]? = nil,
as request: SQLSubqueryable)
throws {
var literal: SQL = "CREATE "
if options.contains(.temporary) {
literal += "TEMPORARY "
}
literal += "VIEW "
if options.contains(.ifNotExists) {
literal += "IF NOT EXISTS "
}
literal += "\(identifier: name) "
if let columns {
literal += "("
literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ")
literal += ") "
}
literal += "AS \(request)"
// CREATE VIEW does not support arguments, so make sure we use
// literal values.
let context = SQLGenerationContext(self, argumentsSink: .literalValues)
let sql = try literal.sql(context)
try execute(sql: sql)
}
/// Creates a database view.
///
/// For example:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(view: "hero", asLiteral: """
/// SELECT * FROM player WHERE isHero == 1
/// """)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createview.html>
///
/// - parameters:
/// - view: The view name.
/// - options: View creation options.
/// - columns: The columns of the view. If nil, the columns are the
/// columns of the request.
/// - sqlLiteral: An `SQL` literal.
public func create(
view name: String,
options: ViewOptions = [],
columns: [String]? = nil,
asLiteral sqlLiteral: SQL)
throws {
try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral))
}
/// Deletes a database view.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropview.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(view name: String) throws {
try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)")
}
/// Creates an index on the specified table and columns.
///
/// For example:
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
/// ```
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use
/// ``create(index:on:expressions:options:condition:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(indexOn:columns:options:condition:)`` instead.
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If true, no error is thrown if index already exists.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false,
condition: (any SQLExpressible)? = nil)
throws
{
var options: IndexOptions = []
if ifNotExists { options.insert(.ifNotExists) }
if unique { options.insert(.unique) }
try create(index: name, on: table, columns: columns, options: options, condition: condition)
}
/// Creates an index on the specified table and columns.
///
/// For example:
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique)
/// ```
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use a raw SQL
/// query:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
index name: String,
on table: String,
columns: [String],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
let index = IndexDefinition(
name: name,
table: table,
expressions: columns.map { .column($0) },
options: options,
condition: condition?.sqlExpression)
let generator = SQLIndexGenerator(index: index)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Creates an index on the specified table and expressions.
///
/// This method can generally create indexes on expressions (see
/// <https://www.sqlite.org/expridx.html>):
///
/// ```swift
/// // CREATE INDEX txy ON t(x+y)
/// try db.create(
/// index: "txy",
/// on: "t",
/// expressions: [Column("x") + Column("y")])
/// ```
///
/// In particular, you can specify the collation on indexed
/// columns (see <https://www.sqlite.org/lang_createindex.html#collations>):
///
/// ```swift
/// // CREATE INDEX index_player_name ON player(name COLLATE NOCASE)
/// try db.create(
/// index: "index_player_name",
/// on: "player",
/// expressions: [Column("name").collating(.nocase)])
/// ```
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - expressions: The indexed expressions.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
index name: String,
on table: String,
expressions: [any SQLExpressible],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
let index = IndexDefinition(
name: name,
table: table,
expressions: expressions.map { $0.sqlExpression },
options: options,
condition: condition?.sqlExpression)
let generator = SQLIndexGenerator(index: index)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Creates an index with a default name on the specified table and columns.
///
/// The created index is named after the table and the column name(s):
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"], options: .unique)
/// ```
///
/// In order to specify the index name, use
/// ``create(index:on:columns:options:condition:)`` instead.
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use
/// ``create(index:on:expressions:options:condition:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
indexOn table: String,
columns: [String],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
try create(
index: Database.defaultIndexName(on: table, columns: columns),
on: table,
columns: columns,
options: options,
condition: condition)
}
/// Deletes a database index.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropindex.html>
///
/// - parameter name: The index name.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(index name: String) throws {
try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)")
}
/// Deletes the database index on the specified table and columns
/// if exactly one such index exists.
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(indexOn table: String, columns: [String]) throws {
let lowercasedColumns = columns.map { $0.lowercased() }
let indexes = try indexes(on: table).filter { index in
index.columns.map({ $0.lowercased() }) == lowercasedColumns
}
if let index = indexes.first, indexes.count == 1 {
try drop(index: index.name)
}
}
/// Deletes and recreates from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_reindex.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func reindex(collation: Database.CollationName) throws {
try execute(sql: "REINDEX \(collation.rawValue)")
}
/// Deletes and recreates from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_reindex.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func reindex(collation: DatabaseCollation) throws {
try reindex(collation: Database.CollationName(rawValue: collation.name))
}
}
/// View creation options
public struct ViewOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the view if it does not already exist.
public static let ifNotExists = ViewOptions(rawValue: 1 << 0)
/// Creates a temporary view.
public static let temporary = ViewOptions(rawValue: 1 << 1)
}
@@ -1,106 +0,0 @@
/// Describes an association in the database schema.
///
/// You get instances of `ForeignKeyDefinition` when you create a database
/// tables. For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.belongsTo("team") // ForeignKeyDefinition
/// }
/// ```
///
/// See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)``.
public final class ForeignKeyDefinition {
enum Indexing {
case index
case unique
}
var name: String
var table: String?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var indexing: Indexing?
var isDeferred: Bool
var notNullConflictResolution: Database.ConflictResolution?
init(
name: String,
table: String?,
deleteAction: Database.ForeignKeyAction?,
updateAction: Database.ForeignKeyAction?,
isIndexed: Bool,
isDeferred: Bool)
{
self.name = name
self.table = table
self.deleteAction = deleteAction
self.updateAction = updateAction
self.indexing = isIndexed ? .index : nil
self.isDeferred = isDeferred
}
/// Adds a not null constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // teamId INTEGER NOT NULL REFERENCES team(id)
/// // )
/// try db.create(table: "player") { t in
/// t.belongsTo("team").notNull()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#notnullconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the definition of
/// the association.
@discardableResult
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
notNullConflictResolution = conflictResolution ?? .abort
return self
}
/// Adds a unique constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // teamId INTEGER UNIQUE REFERENCES team(id)
/// // )
/// try db.create(table: "player") { t in
/// t.belongsTo("team").unique()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#uniqueconst>
///
/// - returns: `self` so that you can further refine the definition of
/// the association.
@discardableResult
public func unique() -> Self {
indexing = .unique
return self
}
func primaryKey(_ db: Database) throws -> SQLPrimaryKeyDescriptor {
if let table {
return try SQLPrimaryKeyDescriptor.find(db, table: table)
}
if try db.tableExists(name) {
return try SQLPrimaryKeyDescriptor.find(db, table: name)
}
let pluralizedName = name.pluralized
if try db.tableExists(pluralizedName) {
return try SQLPrimaryKeyDescriptor.find(db, table: pluralizedName)
}
throw DatabaseError.noSuchTable(name)
}
}
@@ -1,26 +0,0 @@
struct IndexDefinition {
let name: String
let table: String
let expressions: [SQLExpression]
let options: IndexOptions
let condition: SQLExpression?
}
/// Index creation options
public struct IndexOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the index if it does not already exist.
public static let ifNotExists = IndexOptions(rawValue: 1 << 0)
/// Creates a unique index.
public static let unique = IndexOptions(rawValue: 1 << 1)
}
extension Database {
static func defaultIndexName(on table: String, columns: [String]) -> String {
"index_\(table)_on_\(columns.joined(separator: "_"))"
}
}
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more