Compare commits

..
Author SHA1 Message Date
Gwendal Roué 9318693fe4 Attached Cache 2023-03-20 13:19:18 +01:00
288 changed files with 4462 additions and 20930 deletions

No files matched your search

+22 -58
View File
@@ -13,7 +13,6 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
pull_request:
paths:
- 'GRDB/**'
@@ -21,7 +20,6 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
concurrency:
group: ${{ github.ref_name }}
@@ -40,34 +38,18 @@ 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
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-13
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-13
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.1.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
destination: "platform=macOS"
@@ -77,7 +59,7 @@ jobs:
destination: "OS=16.0,name=iPhone 14"
name: "iOS"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -90,20 +72,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-13
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-13
runsOn: macOS-12
name: "Xcode 14.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -116,14 +92,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
name: "Xcode 14.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -136,14 +109,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
name: "Xcode 14.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -156,14 +126,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
name: "Xcode 14.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -176,14 +143,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
name: "Xcode 14.1"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_universal_xcframework
run: make test_archive_GRDBOSX_xcframework
+1 -191
View File
@@ -7,22 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.25.x` Releases - [6.25.0](#6250)
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
- `6.22.x` Releases - [6.22.0](#6220)
- `6.21.x` Releases - [6.21.0](#6210)
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
- `6.19.x` Releases - [6.19.0](#6190)
- `6.18.x` Releases - [6.18.0](#6180)
- `6.17.x` Releases - [6.17.0](#6170)
- `6.16.x` Releases - [6.16.0](#6160)
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
- `6.14.x` Releases - [6.14.0](#6140)
- `6.13.x` Releases - [6.13.0](#6130)
- `6.12.x` Releases - [6.12.0](#6120)
- `6.11.x` Releases - [6.11.0](#6110)
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
- `6.10.x` Releases - [6.10.0](#6100)
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
- `6.8.x` Releases - [6.8.0](#680)
- `6.7.x` Releases - [6.7.0](#670)
@@ -123,181 +108,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## Next Release
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
## 6.25.0
Released February 25, 2024
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
## 6.24.2
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
Released January 6, 2024
- **New**: [#1477](https://github.com/groue/GRDB.swift/pull/1477): Remove shadow tables from database dump
## 6.24.0
Released January 6, 2024
- **New**: [#1466](https://github.com/groue/GRDB.swift/pull/1466) by [@barnettben](https://github.com/barnettben): Add schema name option to database introspection methods
## 6.23.0
Released December 1, 2023
- **New**: [#1462](https://github.com/groue/GRDB.swift/pull/1462) Temporary read-only access
## 6.22.0
Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
Released October 29, 2023
- **New**: [#1448](https://github.com/groue/GRDB.swift/pull/1448) by [@groue](https://github.com/groue): Add support for stable ordering and dump of views
- **New**: [#1449](https://github.com/groue/GRDB.swift/pull/1449) by [@groue](https://github.com/groue): Backport temporary copies from GRDBSnapshotTesting
## 6.20.2
Released October 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.1...v6.20.2)
- **Fixed**: [#1442](https://github.com/groue/GRDB.swift/pull/1442) by [@groue](https://github.com/groue): Extend the macOS availability of JSON functions
## 6.20.1
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.0...v6.20.1)
- **Fixed**: Removed a debug print
## 6.20.0
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.19.0...v6.20.0)
- **New**: [#1439](https://github.com/groue/GRDB.swift/pull/1439) by [@groue](https://github.com/groue): Dump requests
- **New**: `QueryInterfaceRequest.withStableOrder()` returns a request with well-defined order, suitable for tests.
## 6.19.0
Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
- **New**: Expose the database path from `DatabaseReader`.
## 6.17.0
Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode
## 6.16.0
Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0)
- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views
- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes
- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
## 6.15.1
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
- **Fixed**: Fixed Xcode 15 warnings
- **Fixed**: [#1391](https://github.com/groue/GRDB.swift/pull/1391) Fix upsert in FTS5-synchronized tables
## 6.15.0
Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.14.0...v6.15.0)
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
## 6.14.0
Released May 25, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)
- **New**: [#1376](https://github.com/groue/GRDB.swift/pull/1376) Bitwise operations
- **New**: [#1379](https://github.com/groue/GRDB.swift/pull/1379) Create indexes with a default name
## 6.13.0
Released May 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.12.0...v6.13.0)
- **New**: [#1373](https://github.com/groue/GRDB.swift/pull/1373) Deprecate string literal arguments for `TableDefinition.check()`
## 6.12.0
Released April 29, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.11.0...v6.12.0)
- **Fixed**: [#1364](https://github.com/groue/GRDB.swift/pull/1364) Fix a regression introduced with version 6.10.0, where starting multiple observations while performing writes could create a deadlock.
- **New**: `FetchableRecordDecoder` is an object that decodes `Decodable` fetchable records from database rows. You may want to use this decoder when you want to use the `Decodable` initializer from `init(row: Row)`.
## 6.11.0
Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
## 6.10.2
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
Released April 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
## 6.10.0
Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
+2 -2
View File
@@ -61,7 +61,7 @@ How you can Contribute
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
- No Swiftlint warning after a build.
@@ -69,7 +69,7 @@ How you can Contribute
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
+23 -27
View File
@@ -429,13 +429,15 @@ The matching [migration] would look like:
migrator.registerMigration("Employees") { db in
try db.create(table: "employee") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
t.column("managerId", .integer)
.indexed()
.references("employee", onDelete: .restrict)
t.column("name", .text)
}
}
```
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
```swift
struct EmployeeInfo: FetchableRecord, Decodable {
@@ -534,16 +536,20 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", onDelete: .cascade) // (2)
t.column("authorId", .integer) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
2. The `book.authorId` column is used to link a book to the author it belongs to.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -589,16 +595,20 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", onDelete: .cascade) // (2)
t.column("authorId", .integer) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
2. The `book.authorId` column is used to link a book to the author it belongs to.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -644,9 +654,10 @@ migrator.registerMigration("Countries") { db in
}
try db.create(table: "demographics") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("country", onDelete: .cascade) // (2)
t.column("countryCode", .text) // (2)
.notNull() // (3)
.unique() // (4)
.references("country", onDelete: .cascade) // (5)
t.column("population", .integer)
t.column("density", .double)
}
@@ -654,9 +665,10 @@ migrator.registerMigration("Countries") { db in
```
1. The `country` table has a primary key.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -708,22 +720,6 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/AmbiguousForeignKeys.svg)
```swift
// The migration that has created the above schema
migrator.registerMigration("Library") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", inTable: "person")
t.belongsTo("translator", inTable: "person")
t.column("title", .text)
}
}
```
When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person".
Your help is needed. You have to instruct GRDB which foreign key to use:
@@ -2004,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco
- [Decoding a Joined Request with a Decodable Record]
- [Decoding a Joined Request with FetchableRecord]
- [Debugging Request Decoding]
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
## The Structure of a Joined Request
@@ -2864,7 +2860,7 @@ extension DerivableRequest<Book> {
}
```
See [Recommended Practices for Designing Record Types] for more information.
See [Good Practices for Designing Record Types] for more information.
## Known Issues
@@ -3003,7 +2999,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[Record class]: ../README.md#record-class
[EncodableRecord]: ../README.md#persistablerecord-protocol
+1 -3
View File
@@ -362,9 +362,7 @@ And we can fetch the data that feeds our application screen:
```swift
let chatInfos: [ChatInfos] = try dbQueue.read { db in
try request.fetchAll(db)
}
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
+1 -1
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
@@ -61,13 +61,6 @@
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,29 +1,12 @@
import Foundation
import GRDB
import os.log
/// A database of players.
/// AppDatabase lets the application access the database.
///
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -36,67 +19,18 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -118,7 +52,6 @@ extension AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -194,8 +127,8 @@ extension AppDatabase {
}
}
}
private static let uiTestPlayers = [
static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -204,7 +137,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,31 +7,26 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Pick a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: directoryURL)
try? fileManager.removeItem(at: folderURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -64,7 +59,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try! DatabaseQueue()
return try! AppDatabase(dbQueue)
}
@@ -69,7 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() async throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = try await dbQueue.write { db in
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() async throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
let playerIds: [Int64] = try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() async throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -127,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -61,13 +61,6 @@
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,29 +1,13 @@
import Combine
import Foundation
import GRDB
import os.log
/// A database of players.
/// AppDatabase lets the application access the database.
///
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -36,67 +20,18 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -118,7 +53,6 @@ extension AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -194,8 +128,8 @@ extension AppDatabase {
}
}
}
private static let uiTestPlayers = [
static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -204,7 +138,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,31 +7,26 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Pick a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: directoryURL)
try? fileManager.removeItem(at: folderURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -64,7 +59,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try! DatabaseQueue()
return try! AppDatabase(dbQueue)
}
@@ -69,7 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS2</string>
<string>com.github.groue.GRDBDemoiOS</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -640,7 +640,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -660,7 +660,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -677,7 +677,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -694,7 +694,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -832,7 +832,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -849,7 +849,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
@@ -61,13 +61,6 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,28 +1,11 @@
import GRDB
import os.log
/// `AppDatabase` lets the application access the database.
/// AppDatabase lets the application access the database.
///
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
final class AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -35,67 +18,18 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -117,7 +51,6 @@ extension AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
@@ -7,24 +7,19 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Create a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -68,7 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let dbQueue = try DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
+1 -1
View File
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
**Files of interest:**
+1 -3
View File
@@ -397,9 +397,7 @@ let publisher = observation
// NEW: GRDB 5
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read { db in
try query.build(db)
}
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
@@ -1,4 +1,836 @@
Good Practices for Designing Record Types
=========================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
This guide aims at helping you leverage the best of GRDB [records] and [associations].
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Singleton Records]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
This is why we recommend defining a **robust database schema** even before playing with record types.
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("country", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
try migrator.migrate(dbQueue)
```
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
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] for more information.
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
>
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
>
> ```swift
> migrator.registerMigration("createLibrary") { db in
> // RECOMMENDED
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> ...
> }
>
> // NOT RECOMMENDED
> try db.create(table: Author.databaseTableName) { t in
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
> ...
> }
> }
> ```
>
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
>
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Persistable Record Types are Responsible for Their Tables
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var country: String?
}
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
}
```
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
>
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
>
> ```swift
> try dbQueue.write { db in
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
> try author.insert(db)
> print(author.id!) // Guaranteed non-nil id
> }
> ```
>
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
>
> ```swift
> let authorID: Int64 = ...
> let author: Author? = try dbQueue.read { db in
> try Author.fetchOne(db, id: authorID)
> }
> ```
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
## Singleton Records
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done!
## Define Record Requests
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
```swift
// For a codable record
extension Author {
// Define database columns from CodingKeys
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let country = Column(CodingKeys.country)
}
}
```
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
```swift
// For a non-codable record
extension Author {
// Define database columns as an enum
enum Columns: String, ColumnExpression {
case id, name, country
}
}
```
Those columns let you define requests:
```swift
try dbQueue.read { db in
// Order authors by name, in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// French authors
let frenchAuthors: [Author] = try Author.all()
.filter(Author.Columns.country == "France")
.fetchAll(db)
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
```
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
```swift
try dbQueue.read { db in
let sortedAuthors: [Author] = try Author.all()
.orderByName()
.fetchAll(db)
let frenchAuthors: [Author] = try Author.all()
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
```swift
// Book requests
extension DerivableRequest<Book> {
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
func filter(authorCountry: String) -> Self {
// Books do not have any country column. But their author has one.
// A book is from a country if it can be joined to an author from this country:
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
```swift
// Author requests
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// IDs of French authors
let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db)
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
```swift
extension Author {
static let books = hasMany(Book.self)
}
extension Book {
static let author = belongsTo(Author.self)
}
```
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
```swift
// Fetch all authors and their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
let request = Author.annotated(with: Author.books.count)
return try AuthorInfo.fetchAll(db, request)
}
// Fetch all Colombian books and their authors:
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
let request = Book.including(required: Book.author.filter(country: "Colombia"))
return try Authorship.fetchAll(db, request)
}
```
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
>
> That is because other ORMs perform lazy loading:
>
> ```ruby
> # Ruby's Active Record
> author = Author.find(123) # fetch author
> book_count = author.books.count # lazily counts books on demand
> ```
>
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
>
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = try dbQueue.read { db in
try Author.all().orderByName().fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
let request = Author
.filter(id: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
```
3. Prepare the application screen that displays a book information:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(id: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
```
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
A last extension on your record types will further help navigation from records to associated ones:
```swift
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
request(for: Author.books)
}
}
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
request(for: Book.author)
}
}
```
Those properties provide an alternative way to feed our application:
1. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(
author: author,
books: books)
}
```
2. Prepare the application screen that displays a book information:
```swift
struct BookInfo {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
```
## How to Design Database Managers
Many developers want to hide GRDB database queues and pools inside "database managers":
```swift
// LibraryManager grants access to the library database.
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
```
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
Design your database managers with the [GRDB concurrency rules] in mind.
Practically, let's start with a naive example, and gradually improve it:
```swift
// A naive manager that we will improve
class NaiveLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func books(writtenBy author: Author) -> [Book] {
do {
return try dbQueue.read { db in
try author.books.fetchAll(db)
}
} catch {
return []
}
}
}
```
**This manager can be improved in two ways.**
- [Embrace Errors]
- [Thread-Safety is also an Application Concern]
### Embrace Errors
Have database managers throw database errors instead of catching them.
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
Exposing errors will help you building your application:
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
- You will be able to opt in for advanced OS features like [data protection].
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
```swift
// An improved manager that does not hide errors
class ImprovedLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) throws -> Author? {
try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
}
func book(id: Int64) throws -> Book? {
try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
}
func books(writtenBy author: Author) throws -> [Book] {
try dbQueue.read { db in
try author.books.fetchAll(db)
}
}
}
```
### Thread-Safety is also an Application Concern
Now, let's make our database manager **thread-safe**.
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
For example, in the screen that displays an author and her books, we would write:
```swift
let authorId = 123
if let author = libraryManager.author(id: authorId) {
let books = libraryManager.books(writtenBy: author)
// Use author and books
}
```
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
This gives a much safer manager:
```swift
// A manager that actually manages
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
// Feeds the list of authors
extension LibraryManager {
struct AuthorListItem: Decodable, FetchableRecord {
let author: Author
let bookCount: Int
}
func authorList() throws -> [AuthorListItem] {
try dbQueue.read { db in
let request = Author
.annotated(with: Author.books.count)
.orderByName()
return try AuthorListItem.fetchAll(db, request)
}
}
}
// Feeds a book screen
extension LibraryManager {
struct BookInfo {
var book: Book
var author: Author
}
func bookInfo(bookId: Int64) throws -> BookInfo? {
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
}
}
// Feeds an author screen
extension LibraryManager {
struct AuthorInfo {
var author: Author
var books: [Book]
}
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
}
}
```
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
>
> ```ruby
> # Ruby's Active Record
> book = Book.find(123) # fetch book
> author = book.author # fetch author
> # use book and author
> ```
>
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
>
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
>
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
>
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
[records]: ../README.md#records
[associations]: AssociationsBasics.md
[FMDB]: https://github.com/ccgus/fmdb
[Core Data]: https://developer.apple.com/documentation/coredata
[Realm]: https://realm.io
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Singleton Records]: #singleton-records
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
[query interface]: ../README.md#the-query-interface
[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[data protection]: ../README.md#data-protection
[Embrace Errors]: #embrace-errors
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
@@ -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
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
### FetchRequest
+2 -1
View File
@@ -6,7 +6,7 @@ Release Process
To release a new GRDB version:
- Tests
- `make distclean test`
- `make test`
- Build and run GRDBDemoiOS in Release configuration on a device
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
@@ -21,6 +21,7 @@ To release a new GRDB version:
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master & development branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- Update https://github.com/groue/WWDCCompanion
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
+5 -7
View File
@@ -112,15 +112,13 @@ let components: [SQL] = [
let query = components.joined(separator: " ")
```
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
Extract the plain SQL string from a literal:
```swift
try dbQueue.read { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try query.build(db)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
}
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
+2 -2
View File
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
### Allow database records to cross threads
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
### Never pay for using raw SQL
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.25.0'
s.version = '6.10.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+16 -166
View File
@@ -13,10 +13,6 @@
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
@@ -58,9 +54,6 @@
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
@@ -75,12 +68,9 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; };
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */; };
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
@@ -103,7 +93,6 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
@@ -125,7 +114,6 @@
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
@@ -157,7 +145,6 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
@@ -206,24 +193,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 */; };
@@ -397,18 +374,11 @@
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
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 */; };
@@ -438,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>"; };
@@ -482,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>"; };
@@ -492,13 +455,10 @@
5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = "<group>"; };
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
@@ -532,7 +492,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>"; };
@@ -554,7 +513,7 @@
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>"; };
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; 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>"; };
@@ -653,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>"; };
@@ -829,6 +778,7 @@
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
@@ -836,14 +786,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>"; };
@@ -853,7 +795,6 @@
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
@@ -882,25 +823,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 = (
@@ -980,7 +902,6 @@
isa = PBXGroup;
children = (
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -1008,14 +929,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 */,
@@ -1091,7 +1010,6 @@
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
@@ -1131,10 +1049,8 @@
5687359E1CEDE16C009B9116 /* Betty.jpeg */,
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */,
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */,
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */,
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */,
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */,
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */,
);
name = DatabaseQueue;
@@ -1143,7 +1059,6 @@
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
isa = PBXGroup;
children = (
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */,
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
@@ -1200,6 +1115,13 @@
path = GRDBCombineTests;
sourceTree = "<group>";
};
564390D42414FC2C00BA61E6 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
5653EABF20944B1300F46237 /* Association */ = {
isa = PBXGroup;
children = (
@@ -1257,11 +1179,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 */,
);
@@ -1271,12 +1188,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>";
@@ -1342,7 +1255,6 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1350,38 +1262,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 = (
@@ -1566,6 +1446,7 @@
56A238701B9C75030082EB20 /* Configuration.swift */,
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
56A238711B9C75030082EB20 /* Database.swift */,
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
@@ -1710,6 +1591,8 @@
DC37742D19C8CC90004FCF85 /* GRDB */,
DC10500F19C904DD00D8CA30 /* Tests */,
DC3773F419C8CBB3004FCF85 /* Products */,
564390D42414FC2C00BA61E6 /* Frameworks */,
5643676D272EDF2400C718C7 /* Scripts */,
);
indentWidth = 4;
sourceTree = "<group>";
@@ -1739,11 +1622,8 @@
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEB52AC862EC00CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
56300B6D1C53F592005A543B /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1866,7 +1746,6 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */,
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */,
56D496C21D81374C008276D7 /* Betty.jpeg in Resources */,
);
@@ -1876,7 +1755,6 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1929,7 +1807,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 */,
@@ -1941,7 +1818,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 */,
@@ -1956,7 +1832,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 */,
@@ -2016,7 +1891,6 @@
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */,
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
@@ -2035,7 +1909,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 */,
@@ -2046,7 +1919,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 */,
@@ -2063,7 +1935,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 */,
@@ -2091,7 +1962,6 @@
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */,
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
@@ -2102,7 +1972,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 */,
@@ -2157,8 +2026,8 @@
buildActionMask = 2147483647;
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56F0383B28C21814000DEBFB /* Database+Cache.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 */,
@@ -2192,7 +2061,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 */,
@@ -2207,13 +2075,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 */,
@@ -2227,8 +2093,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 */,
@@ -2236,7 +2100,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 */,
@@ -2245,12 +2108,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 */,
@@ -2264,11 +2125,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 */,
@@ -2276,10 +2134,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 */,
@@ -2296,14 +2152,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 */,
@@ -2316,9 +2168,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;
+1 -41
View File
@@ -182,7 +182,7 @@ public struct Configuration {
/// var config = Configuration()
/// config.transactionClock = .custom { db in /* return some Date */ }
/// ```
public var transactionClock: any TransactionClock = .default
public var transactionClock: TransactionClock = .default
// MARK: - Managing SQLite Connections
@@ -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: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
/// ``wal`` case).
case `default`
/// The journal mode is set to WAL (plus extra configurations that
/// make life easier with WAL databases).
case wal
}
/// Defines how the journal mode is configured when the database
/// connection is opened.
///
/// This configuration is ignored when ``readonly`` is true.
///
/// The default value has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool`` configure
/// the database for the WAL mode.
///
/// Applications that need to open a WAL database with a
/// ``DatabaseQueue`` should set the `journalMode` to `wal`:
///
/// ```swift
/// // Open a WAL database with DatabaseQueue
/// var config = Configuration()
/// config.journalMode = .wal
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public var journalMode = JournalModeConfiguration.default
// MARK: - Concurrency
/// Defines the how `SQLITE_BUSY` errors are handled.
-40
View File
@@ -733,11 +733,6 @@ public final class AnyCursor<Element>: Cursor {
}
}
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
// sendable than non-sendable cursors (such as `DatabaseCursor`).
@available(*, unavailable)
extension AnyCursor: Sendable { }
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
/// cursor before possibly returning the first available element.
public final class DropFirstCursor<Base: Cursor> {
@@ -752,11 +747,6 @@ public final class DropFirstCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropFirstCursor: Sendable { }
extension DropFirstCursor: Cursor {
public func next() throws -> Base.Element? {
while dropped < limit {
@@ -783,11 +773,6 @@ public final class DropWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropWhileCursor: Sendable { }
extension DropWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if predicateHasFailed {
@@ -833,11 +818,6 @@ public final class EnumeratedCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension EnumeratedCursor: Sendable { }
extension EnumeratedCursor: Cursor {
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
@@ -895,11 +875,6 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FlattenCursor: Sendable { }
extension FlattenCursor: Cursor {
public func next() throws -> Base.Element.Element? {
while true {
@@ -926,11 +901,6 @@ public final class MapCursor<Base: Cursor, Element> {
}
}
// Explicit non-conformance to Sendable: There is no known reason for making
// it thread-safe (`transform` a Sendable closure).
@available(*, unavailable)
extension MapCursor: Sendable { }
extension MapCursor: Cursor {
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
@@ -957,11 +927,6 @@ public final class PrefixCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixCursor: Sendable { }
extension PrefixCursor: Cursor {
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
@@ -989,11 +954,6 @@ public final class PrefixWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixWhileCursor: Sendable { }
extension PrefixWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
+74
View File
@@ -0,0 +1,74 @@
extension Database {
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
return try throwingFirstError {
attachedCache = AttachedCache(
schema: .attached("cache"),
statementCache: StatementCache(database: self))
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
return try execute()
} finally: {
attachedCache = nil
try self.execute(sql: "DETACH DATABASE cache")
}
}
}
extension Statement {
/// Returns a statement ready for iterating the results of this statement
/// with a DatabaseCursor.
///
/// The result is not the same statement as the receiver if we cache the
/// statement's results.
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
// Should we cache statement results and return a new statement on the cached values?
guard
// Don't cache until we were instructed to.
let attachedCache = database.attachedCache,
// Only cache read-only statements.
isReadonly,
// Only cache statements that access user tables.
databaseRegion
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
.isEmpty == false,
// Only cache statements that can build a name for the cache table.
let cacheTableName,
// Only cache statements for which we can guarantee rowid ordering
// without ambiguity.
case let statementColumns = columnNames.map({ $0.lowercased() }),
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
else {
// Don't cache: return self.
// Reset before cursor iteration: the statement may be reused.
try prepareExecution(withArguments: arguments)
return self
}
// Cache the results if not done yet
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
try database.execute(sql: """
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
""", arguments: arguments ?? self.arguments)
// Return a statement on the cached values, preserving the order of the
// original rows.
//
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
//
// > Tables created using CREATE TABLE AS are initially populated with
// > the rows of data returned by the SELECT statement. Rows are
// > assigned contiguously ascending rowid values, starting with 1, in
// > the order that they are returned by the SELECT statement.
let statement = try attachedCache.statementCache.statement("""
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
""")
// Reset before cursor iteration: the statement may be reused.
try statement.reset()
return statement
}
}
+76 -263
View File
@@ -58,12 +58,8 @@ extension Database {
}
}
/// The name of the master sqlite table, without the schema name.
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main, .attached: return "sqlite_master"
case .temp: return "sqlite_temp_master"
}
func table(_ name: String) -> TableIdentifier {
TableIdentifier(schemaID: self, name: name)
}
}
@@ -154,19 +150,6 @@ extension Database {
return schemaIdentifiers
}
/// The `SchemaIdentifier` named `schemaName` if it exists.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if no such schema exists.
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
let allIdentifiers = try schemaIdentifiers()
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return result
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns information about a table or a view
func table(_ tableName: String) throws -> TableInfo? {
@@ -223,24 +206,15 @@ extension Database {
return tableInfo
}
/// Returns whether a table exists
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .table, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
/// Returns whether a table exists, in the main or temp schema, or in an
/// attached database.
public func tableExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .table, name: name, in: $0)
}
}
private func tableExists(_ table: TableIdentifier) throws -> Bool {
func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
}
@@ -268,57 +242,20 @@ extension Database {
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .view, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
public func viewExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .view, name: name, in: $0)
}
}
/// Returns whether a trigger exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .trigger, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
public func triggerExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .trigger, name: name, in: $0)
}
}
/// Checks if an entity exists in a given schema
///
/// This is checking for the existence of the entity specified by
/// `type` and `name`. It is assumed that the existence of a schema
/// named `schemaName` is already known and will throw an error if it
/// cannot be found.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return try exists(type: type, name: name, in: schemaID)
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
// SQLite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
@@ -331,17 +268,10 @@ extension Database {
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table exists in
/// the main or temp schema, or in an attached database.
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -428,13 +358,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)
@@ -500,18 +430,10 @@ extension Database {
/// the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func indexes(on tableName: String) throws -> [IndexInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -600,18 +522,10 @@ extension Database {
/// Returns the foreign keys defined on table named `tableName`.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -692,27 +606,10 @@ extension Database {
/// Returns a cursor over foreign key violations in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeyViolations(
in tableName: String,
in schemaName: String? = nil)
throws -> RecordCursor<ForeignKeyViolation>
{
if let schemaName {
let schemaID = try schemaIdentifier(named: schemaName)
if try exists(type: .table, name: tableName, in: schemaID) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
for schemaIdentifier in try schemaIdentifiers() {
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
@@ -741,21 +638,14 @@ extension Database {
/// Throws an error if there exists a foreign key violation in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// On the first foreign key violation found in the table, this method
/// throws a ``DatabaseError`` with extended code
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
///
/// If you are looking for the list of foreign key violations, prefer
/// ``foreignKeyViolations(in:in:)`` instead.
///
/// - throws: A ``DatabaseError`` as described above; when a
/// specified schema does not exist; if no such table or view with this
/// name exists in the main or temp schema or in an attached database.
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
/// ``foreignKeyViolations(in:)`` instead.
public func checkForeignKeys(in tableName: String) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
}
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
@@ -772,17 +662,9 @@ extension Database {
/// attached database.
func canonicalTableName(_ tableName: String) throws -> String? {
for schemaIdentifier in try schemaIdentifiers() {
// Regular tables
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
return result
}
// Master table (sqlite_master, sqlite_temp_master)
// swiftlint:disable:next inclusive_language
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
if tableName.lowercased() == masterTableName.lowercased() {
return masterTableName
}
}
return nil
}
@@ -795,44 +677,16 @@ extension Database {
schemaCache[schemaID].schemaInfo = schemaInfo
return schemaInfo
}
/// Attempts to perform a table introspection function on a given
/// table and schema
///
/// - parameter tableName: The name of the table to examine
/// - parameter schemaName: The name of the schema to check
/// - parameter introspector: An introspection function taking a
/// `TableIdentifier` as the only parameter
private func introspect<T>(
tableNamed tableName: String,
inSchemaNamed schemaName: String,
using introspector: (TableIdentifier) throws -> T?
) throws -> T {
let schemaIdentifier = try schemaIdentifier(named: schemaName)
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
}
extension Database {
/// Returns the columns in a table or a view.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
}
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table or view with this name exists in the main or temp schema, or
/// in an attached database.
public func columns(in tableName: String) throws -> [ColumnInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -990,14 +844,14 @@ extension Database {
/// Information about a column of a database table.
///
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord, Sendable {
public struct ColumnInfo: FetchableRecord {
let cid: Int
let hidden: Int?
@@ -1008,22 +862,8 @@ public struct ColumnInfo: FetchableRecord, Sendable {
///
/// The casing of this string depends on the SQLite version: make sure you
/// process this string in a case-insensitive way.
///
/// The type is the empty string when the column has no declared type.
public let type: String
/// The column data type (nil when the column has no declared type).
///
/// The casing of the raw value depends on the SQLite version: make sure
/// you process the result in a case-insensitive way.
var columnType: Database.ColumnType? {
if type.isEmpty {
return nil
} else {
return Database.ColumnType(rawValue: type)
}
}
/// A boolean value indicating if the column is constrained to be not null.
public let isNotNull: Bool
@@ -1076,16 +916,16 @@ public struct ColumnInfo: FetchableRecord, Sendable {
/// Information about an index.
///
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo: Sendable{
public struct IndexInfo {
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public var rawValue: String
public init(rawValue: String) {
@@ -1119,7 +959,7 @@ public struct IndexInfo: Sendable{
///
/// You get instances of `ForeignKeyViolation` from the `Database` methods
/// ``Database/foreignKeyViolations()`` and
/// ``Database/foreignKeyViolations(in:in:)`` methods.
/// ``Database/foreignKeyViolations(in:)`` methods.
///
/// For example:
///
@@ -1158,7 +998,7 @@ public struct IndexInfo: Sendable{
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation: Sendable {
public struct ForeignKeyViolation {
/// The name of the table that contains the foreign key.
public var originTable: String
@@ -1173,7 +1013,7 @@ public struct ForeignKeyViolation: Sendable {
/// The id of the foreign key constraint that failed.
///
/// This id matches the ``ForeignKeyInfo/id`` property in
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:in:)``.
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
public var foreignKeyId: Int
/// A precise description of the foreign key violation.
@@ -1263,7 +1103,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// Information about a primary key.
///
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
/// `Database` method.
///
/// When the table's primary key is the rowid:
@@ -1307,29 +1147,29 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo: Sendable {
public struct PrimaryKeyInfo {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
/// Associated string is the column name.
case rowID(ColumnInfo)
case rowID(String)
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
case regular(columns: [String], tableHasRowID: Bool)
}
private let impl: Impl
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(columnInfo))
static func rowID(_ column: String) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(column))
}
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columnInfos.isEmpty)
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
@@ -1339,34 +1179,21 @@ public struct PrimaryKeyInfo: Sendable {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case let .rowID(columnInfo):
return [columnInfo.name]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos.map(\.name)
case let .rowID(column):
return [column]
case let .regular(columns: columns, tableHasRowID: _):
return columns
}
}
/// The columns in the primary key. Nil if the primary key is the
/// hidden rowID. Never empty otherwise.
var columnInfos: [ColumnInfo]? {
switch impl {
case .hiddenRowID:
return nil
case let .rowID(columnInfo):
return [columnInfo]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos
}
}
/// When not nil, the name of the column that contains the
/// `INTEGER PRIMARY KEY`.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
return nil
case .rowID(let columnInfo):
return columnInfo.name
case .rowID(let column):
return column
case .regular:
return nil
}
@@ -1393,7 +1220,7 @@ public struct PrimaryKeyInfo: Sendable {
return true
case .rowID:
return true
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
case let .regular(columns: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
@@ -1429,11 +1256,11 @@ public struct PrimaryKeyInfo: Sendable {
/// Information about a foreign key.
///
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
/// `Database` method.
///
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
public struct ForeignKeyInfo: Sendable {
public struct ForeignKeyInfo {
/// The first column in the output of the `foreign_key_list` pragma.
public var id: Int
@@ -1490,39 +1317,22 @@ struct TableInfo: FetchableRecord {
}
}
/// A value in the `type` column of `sqlite_master`.
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
var rawValue: String
static let index = SchemaObjectType(rawValue: "index")
static let table = SchemaObjectType(rawValue: "table")
static let trigger = SchemaObjectType(rawValue: "trigger")
static let view = SchemaObjectType(rawValue: "view")
}
/// A row in `sqlite_master`.
struct SchemaObject: Hashable, FetchableRecord {
var type: SchemaObjectType
var name: String
var tbl_name: String?
var sql: String?
init(row: Row) throws {
// "rootpage" column is not always there: avoid using numerical indexes
type = row["type"]
name = row["name"]
tbl_name = row["tbl_name"]
sql = row["sql"]
}
enum SchemaObjectType: String {
case index
case table
case trigger
case view
}
/// All objects in a database schema (tables, views, indexes, triggers).
struct SchemaInfo: Equatable {
let objects: Set<SchemaObject>
private var objects: Set<SchemaObject>
/// Returns whether there exists a object of given type with this name
/// (case-insensitive).
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
let name = name.lowercased()
let type = type.rawValue
return objects.contains {
$0.type == type && $0.name.lowercased() == name
}
@@ -1535,12 +1345,15 @@ struct SchemaInfo: Equatable {
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
return objects
.first { $0.type == type && $0.name.lowercased() == name }?
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
.name
}
func filter(_ isIncluded: (SchemaObject) -> Bool) -> Self {
SchemaInfo(objects: objects.filter(isIncluded))
private struct SchemaObject: Codable, Hashable, FetchableRecord {
var type: String
var name: String
var tbl_name: String?
var sql: String?
}
}
+1 -6
View File
@@ -361,11 +361,6 @@ public class SQLStatementCursor {
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension SQLStatementCursor: Sendable { }
extension SQLStatementCursor: Cursor {
public func next() throws -> Statement? {
guard offset < cString.count - 1 /* trailing \0 */ else {
@@ -378,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,
+100 -195
View File
@@ -60,28 +60,16 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``inSavepoint(_:)``
/// - ``inTransaction(_:_:)``
/// - ``isInsideTransaction``
/// - ``readOnly(_:)``
/// - ``rollback()``
/// - ``transactionDate``
/// - ``TransactionCompletion``
/// - ``TransactionKind``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Database Observation
///
/// - ``add(transactionObserver:extent:)``
/// - ``remove(transactionObserver:)``
/// - ``afterNextTransaction(onCommit:onRollback:)``
/// - ``notifyChanges(in:)``
/// - ``registerAccess(to:)``
///
/// ### Collations
@@ -106,7 +94,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
/// - ``backup(to:pagesPerStep:progress:)``
/// - ``checkpoint(_:on:)``
/// - ``clearSchemaCache()``
@@ -344,6 +331,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
class AttachedCache {
var schema: SchemaIdentifier
var statementCache: StatementCache
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
self.schema = schema
self.statementCache = statementCache
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The attached database that caches the results of requests.
var attachedCache: AttachedCache?
// MARK: - Private properties
/// Support for ``Configuration/busyMode``.
@@ -433,41 +434,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)
@@ -774,38 +740,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Executes read-only database operations, and returns their result
/// after they have finished executing.
///
/// Attempts to write throw a ``DatabaseError`` with
/// resultCode `SQLITE_READONLY`.
///
/// For example:
///
/// ```swift
/// try dbQueue.write do { db in
/// // Write OK
/// try Player(...).insert(db)
///
/// try db.readOnly {
/// // Read OK
/// let players = try Player.fetchAll(db)
///
/// // Throws SQLITE_READONLY
/// try Player(...).insert(db)
/// }
/// }
/// ```
///
/// This method is reentrant.
///
/// - parameter value: A closure that reads from the database.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `value`.
public func readOnly<T>(_ value: () throws -> T) throws -> T {
/// Grants read-only access in the wrapped closure.
func readOnly<T>(_ block: () throws -> T) throws -> T {
try beginReadOnly()
return try throwingFirstError(
execute: value,
execute: block,
finally: endReadOnly)
}
@@ -850,65 +789,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Notifies that some changes were performed in the provided
/// database region.
///
/// This method makes it possible to notify undetected changes, such as
/// changes performed by another process, changes performed by
/// direct calls to SQLite C functions, or changes to the
/// database schema.
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// for a detailed list of undetected database modifications.
///
/// It triggers active transaction observers (``TransactionObserver``).
/// In particular, ``ValueObservation`` that observe the input `region`
/// will fetch and notify a fresh value.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // Notify observers that some changes were performed in the database
/// try db.notifyChanges(in: .fullDatabase)
///
/// // Notify observers that some changes were performed in the player table
/// try db.notifyChanges(in: Player.all())
///
/// // Equivalent alternative
/// try db.notifyChanges(in: Table("player"))
/// }
/// ```
///
/// This method has no effect when called from a read-only
/// database access.
///
/// > Caveat: Individual rowids in the input region are ignored.
/// > Notifying a change to a specific rowid is the same as notifying a
/// > change in the whole table:
/// >
/// > ```swift
/// > try dbQueue.write { db in
/// > // Equivalent
/// > try db.notifyChanges(in: Player.all())
/// > try db.notifyChanges(in: Player.filter(id: 1))
/// > }
/// > ```
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
// Don't do anything when read-only, because read-only transactions
// are not notified. We don't want to notify transactions observers
// of changes, and have them wait for a commit notification that
// will never come.
if !isReadOnly, let observationBroker {
let eventKinds = try region
.databaseRegion(self)
// Use canonical table names for case insensitivity of the input.
.canonicalTables(self)
.impactfulEventKinds(self)
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
}
}
/// Extends the `region` argument with the database region selected by all
/// statements executed by the closure, and all regions explicitly tracked
/// with the ``registerAccess(to:)`` method.
@@ -993,16 +873,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
@@ -1010,7 +905,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 }
@@ -1018,22 +913,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
@@ -1254,7 +1153,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// For example:
///
/// ```swift
/// try dbQueue.writeWithoutTransaction do { db in
/// try dbQueue.writeWithoutTransaction do {
/// try db.inTransaction {
/// try db.execute(sql: "INSERT ...")
/// return .commit
@@ -1730,11 +1629,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
@@ -1860,7 +1754,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt, Sendable {
public enum CheckpointMode: CInt {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1879,7 +1773,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable, Sendable {
public struct CollationName: RawRepresentable, Hashable {
public let rawValue: String
/// Creates a collation name.
@@ -1916,11 +1810,10 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable, Sendable {
public struct ColumnType: RawRepresentable, Hashable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// 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
@@ -1929,14 +1822,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")
@@ -1968,7 +1853,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String, Sendable {
public enum ConflictResolution: String {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -1988,7 +1873,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String, Sendable {
public enum ForeignKeyAction: String {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -2011,7 +1896,7 @@ extension Database {
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet, Sendable {
public struct TracingOptions: OptionSet {
/// The raw trace event code.
public let rawValue: CInt
@@ -2025,11 +1910,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.
@@ -2040,11 +1927,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:
@@ -2052,11 +1945,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
}
}
}
@@ -2072,18 +1975,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
}
}
}
}
@@ -2144,7 +2059,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion: Sendable {
public enum TransactionCompletion {
case commit
case rollback
}
@@ -2152,7 +2067,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String, Sendable {
public enum TransactionKind: String {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
@@ -2185,13 +2100,3 @@ extension Database {
}
}
}
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent: Sendable { }
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent.Statement: Sendable { }
+1 -1
View File
@@ -1,7 +1,7 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress: Sendable {
public struct DatabaseBackupProgress {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
+2 -6
View File
@@ -396,10 +396,6 @@ public struct DatabaseError: Error {
static func noSuchTable(_ tableName: String) -> Self {
DatabaseError(message: "no such table: \(tableName)")
}
static func noSuchSchema(_ schemaName: String) -> Self {
DatabaseError(message: "no such schema: \(schemaName)")
}
}
extension DatabaseError {
@@ -553,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)"
@@ -581,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)"
+8 -19
View File
@@ -30,9 +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)) }
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
/// Creates an SQL function.
///
@@ -76,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]!)
@@ -140,11 +140,10 @@ 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() }
}
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
/// Returns an SQL expression that applies the function.
///
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
@@ -172,23 +171,13 @@ public final class DatabaseFunction: Hashable {
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
switch kind {
case .function:
return .simpleFunction(
name,
arguments.map(\.sqlExpression),
isPure: isPure,
isJSONValue: false)
case .aggregate:
return .aggregateFunction(
name,
arguments.map(\.sqlExpression),
isDistinct: false,
ordering: nil,
filter: nil,
isJSONValue: false)
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
}
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: Database) {
+48 -29
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,31 @@ 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")
if !FileManager.default.fileExists(atPath: path + "-wal") {
// Create the -wal file if it does not exist yet. This
// avoids an SQLITE_CANTOPEN (14) error whenever a user
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
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 +113,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 +161,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 +337,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
@@ -879,11 +900,9 @@ extension DatabasePool {
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if this method is called from a write transaction, or if the
/// wal file is missing or truncated (size zero).
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or
/// if this method is called from a database access where a write
/// transaction is open.
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
try unsafeReentrantRead { db in
try DatabaseSnapshotPool(db)
+41 -148
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
@@ -235,22 +225,21 @@ extension DatabaseQueue: DatabaseReader {
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
try? db.commit()
try? db.endReadOnly()
}
do {
// Enter read-only mode before starting a transaction, so that the
// transaction commit does not trigger database observation.
// See <https://github.com/groue/GRDB.swift/pull/1213>.
try db.beginReadOnly()
// The transaction guarantees snapshot isolation against eventual
// external connection.
try db.beginTransaction(.deferred)
value(.success(db))
try db.beginReadOnly()
} catch {
value(.failure(error))
return
}
value(.success(db))
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
}
}
@@ -284,23 +273,20 @@ extension DatabaseQueue: DatabaseReader {
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore error because we can not notify it.
try? db.commit()
try? db.endReadOnly()
}
do {
// Enter read-only mode before starting a transaction, so that the
// transaction commit does not trigger database observation.
// See <https://github.com/groue/GRDB.swift/pull/1213>.
try db.beginReadOnly()
try db.beginTransaction(.deferred)
value(.success(db))
try db.beginReadOnly()
} catch {
value(.failure(error))
return
}
value(.success(db))
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
}
}
@@ -429,96 +415,3 @@ extension DatabaseQueue: DatabaseWriter {
writer.async(updates)
}
}
// MARK: - Temp Copy
extension DatabaseQueue {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The database memory is released when the returned connection
/// is deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.inMemoryCopy(fromPath: path)
/// ```
public static func inMemoryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. And SQLITE_OPEN_READONLY has no effect on in-memory
// databases anyway.
//
// So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
/// Returns a connection to a private, temporary, on-disk copy of the
/// database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The on-disk copy will be automatically deleted from disk as soon as
/// the returned connection is closed or deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.temporaryCopy(fromPath: path)
/// ```
public static func temporaryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
// <https://www.sqlite.org/c3ref/open.html>
// > If the filename is an empty string, then a private, temporary
// > on-disk database will be created. This private database will be
// > automatically deleted as soon as the database connection
// > is closed.
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(path: "", configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
}
-21
View File
@@ -17,7 +17,6 @@ import Dispatch
/// ### Database Information
///
/// - ``configuration``
/// - ``path``
///
/// ### Reading from the Database
///
@@ -33,16 +32,6 @@ import Dispatch
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Other Database Operations
///
/// - ``backup(to:pagesPerStep:progress:)``
@@ -57,12 +46,6 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// The database configuration.
var configuration: Configuration { get }
/// The path to the database file.
///
/// In-memory databases also have a path:
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
var path: String { get }
/// Closes the database connection.
///
/// - note: You do not have to call this method, and you should not call
@@ -661,10 +644,6 @@ extension AnyDatabaseReader: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+15 -48
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion: Sendable {
public struct DatabaseRegion {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
@@ -168,17 +168,22 @@ public struct DatabaseRegion: Sendable {
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
//
// We also remove GRDB internal tables (cache tables).
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods. (TODO: is this comment still accurate?
// Isn't it about providing TransactionObserver.observes() with
// real tables names, instead?)
try ignoringInternalSQLiteTables().canonicalTables(db)
// `isModified` methods.
let notInternalTables = filteringTables {
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
}
return try notInternalTables.canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
/// Canonical names help the `isModified` methods.
///
/// This method removes views.
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
/// This method removes views (assuming no table exists with the same name
/// as a view).
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
@@ -190,11 +195,11 @@ public struct DatabaseRegion: Sendable {
return region
}
/// Returns a region which doesn't contain any SQLite internal table.
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
/// Returns a region which only contains the filtered tables
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter {
!Database.isSQLiteInternalTable($0.key.rawValue)
predicate($0.key.rawValue)
}
return DatabaseRegion(tableRegions: filteredRegions)
}
@@ -233,44 +238,6 @@ extension DatabaseRegion {
}
return tableRegion.contains(rowID: event.rowID)
}
/// Returns an array of all event kinds that can impact this region.
///
/// - precondition: the region is canonical.
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
if let tableRegions {
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
let tableName = table.rawValue // canonical table name
let columnNames: Set<String>
if let columns = tableRegion.columns {
columnNames = Set(columns.map(\.rawValue))
} else {
columnNames = try Set(db.columns(in: tableName).map(\.name))
}
return [
DatabaseEventKind.delete(tableName: tableName),
DatabaseEventKind.insert(tableName: tableName),
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
]
}
} else {
// full database
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
let columnNames = try Set(db.columns(in: table.name).map(\.name))
return [
DatabaseEventKind.delete(tableName: table.name),
DatabaseEventKind.insert(tableName: table.name),
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
]
}
}
}
}
}
extension DatabaseRegion: Equatable {
@@ -161,11 +161,6 @@ private class DatabaseRegionObserver: TransactionObserver {
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange() {
isChanged = true
stopObservingDatabaseChangesUntilNextTransaction()
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
isChanged = true
+2 -6
View File
@@ -59,14 +59,10 @@ import Dispatch
/// let snapshot2 = try dbPool.makeSnapshot()
///
/// // Guaranteed to be zero
/// let count1 = try snapshot1.read { db in
/// try Player.fetchCount(db)
/// }
/// let count1 = try snapshot1.read(Player.fetchCount)
///
/// // Could be anything
/// let count2 = try snapshot2.read { db in
/// try Player.fetchCount(db)
/// }
/// let count2 = try snapshot2.read(Player.fetchCount)
/// ```
///
/// `DatabaseSnapshot` inherits its database access methods from the
+10 -10
View File
@@ -104,16 +104,16 @@ public final class DatabaseSnapshotPool {
///
/// // Later... Maybe some players have been created.
/// // The snapshot is guaranteed to see an empty table of players, though:
/// let count = try snapshot.read { db in
/// try Player.fetchCount(db)
/// }
/// let count = try snapshot.read(Player.fetchCount)
/// assert(count == 0)
/// ```
///
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if this method is called from a write transaction, or if the
/// wal file is missing or truncated (size zero).
/// If any of the following statements are false when the snapshot is
/// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown:
///
/// - The database connection must be in the
/// [WAL mode](https://www.sqlite.org/wal.html).
/// - There must not be a write transaction open.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
@@ -175,9 +175,9 @@ public final class DatabaseSnapshotPool {
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
/// ```
///
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
/// or if the wal file is missing or truncated (size zero).
/// If the database at `path` is not in the
/// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code
/// `SQLITE_ERROR` is thrown.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
+20 -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
@@ -343,6 +342,25 @@ extension DatabaseValue: CustomStringConvertible {
}
}
extension DatabaseValue {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
switch storage {
case .null:
return "NULL"
case let .string(string):
return String(reflecting: string)
case let .double(double):
return double.description
case let .int64(int64):
return int64.description
case let .blob(data):
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
}
}
}
/// Compares DatabaseValue like SQLite.
///
/// See RxGRDB for tests.
+1 -57
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
@@ -196,6 +147,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
private let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -203,9 +155,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
@@ -222,11 +171,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension DatabaseValueCursor: Sendable { }
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
+11 -40
View File
@@ -289,13 +289,14 @@ public protocol DatabaseWriter: DatabaseReader {
/// ```
///
/// - note: Usage of this method is discouraged, because waiting on the
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// returned ``DatabaseFuture`` blocks a thread. You may prefer the
/// asynchronous version of this method: ``spawnConcurrentRead(_:)``.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
/// Schedules read-only database operations for execution, and
/// returns immediately.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
@@ -310,7 +311,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// by the database writer.
///
/// In the example below, the number of players is fetched concurrently with
/// the player insertion. Yet it is guaranteed to return zero:
/// the player insertion. Yet the future is guaranteed to return zero:
///
/// ```swift
/// try writer.writeWithoutTransaction { db in
@@ -333,10 +334,6 @@ public protocol DatabaseWriter: DatabaseReader {
/// }
/// ```
///
/// - important: The database operations are executed immediately,
/// or asynchronously, depending on the actual class
/// of `DatabaseWriter`.
///
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
@@ -445,21 +442,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,25 +458,14 @@ 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) }
}
// MARK: - Erasing the content of the database
/// Erase the database: delete all content, drop all tables, etc.
/// Erases the content of the database.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func erase() throws {
try barrierWriteWithoutTransaction { try $0.erase() }
@@ -709,7 +684,7 @@ extension DatabaseWriter {
}
}
/// Erase the database: delete all content, drop all tables, etc.
/// Erases the content of the database.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
@@ -986,10 +961,6 @@ extension AnyDatabaseWriter: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+8 -32
View File
@@ -58,6 +58,10 @@
/// - ``makePreparedRequest(_:forSingleResult:)``
/// - ``PreparedRequest``
///
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
///
/// ### Adapting the Fetched Rows
///
/// - ``adapted(_:)``
@@ -107,28 +111,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 +119,13 @@ public struct PreparedRequest {
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
init(
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
{
self.statement = statement
self.adapter = adapter
@@ -152,11 +133,6 @@ public struct PreparedRequest {
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
// MARK: - AdaptedFetchRequest
@@ -241,8 +217,8 @@ public struct AnyFetchRequest<RowDecoder> {
///
/// // AnyFetchRequest<Row>
/// let rowRequest = playerRequest.asRequest(of: Row.self)
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
AnyFetchRequest<T>(request: request)
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
AnyFetchRequest<RowDecoder>(request: request)
}
}
+5 -18
View File
@@ -245,12 +245,6 @@ public final class Row {
}
}
// Explicit non-conformance to Sendable: a row contains transient
// information. TODO GRDB7: split non sendable statement rows from sendable
// copied rows.
@available(*, unavailable)
extension Row: Sendable { }
extension Row {
// MARK: - Columns
@@ -1366,11 +1360,9 @@ public final class RowCursor: DatabaseCursor {
@usableFromInline let _row: Row // Reused for performance
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
@@ -1383,11 +1375,6 @@ public final class RowCursor: DatabaseCursor {
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension RowCursor: Sendable { }
extension Row {
// MARK: - Fetching From Prepared Statement
@@ -1750,7 +1737,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
}
@@ -1783,7 +1770,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)
@@ -1820,7 +1807,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
}
}
@@ -2070,7 +2057,7 @@ typealias RowIndex = Row.Index
extension Row {
/// An index to a (column, value) pair in a ``Row``.
public struct Index: Sendable {
public struct Index {
let index: Int
init(_ index: Int) { self.index = index }
}
+5 -5
View File
@@ -378,7 +378,7 @@ extension RowAdapter {
///
/// This limit adapter may turn out useful in some narrow use cases. You'll
/// be happy to find it when you need it.
public struct EmptyRowAdapter: RowAdapter, Sendable {
public struct EmptyRowAdapter: RowAdapter {
/// Creates an `EmptyRowAdapter`.
public init() { }
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter, Sendable {
///
/// Note that columns that are not present in the dictionary are not present
/// in the resulting adapted row.
public struct ColumnMapping: RowAdapter, Sendable {
public struct ColumnMapping: RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter, Sendable {
/// // [c:2, d: 3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
/// ```
public struct SuffixRowAdapter: RowAdapter, Sendable {
public struct SuffixRowAdapter: RowAdapter {
/// The suffix index
let index: Int
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter, Sendable {
/// // [b:1 c:2]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
/// ```
public struct RangeRowAdapter: RowAdapter, Sendable {
public struct RangeRowAdapter: RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -572,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: any RowAdapter]) {
public init(_ scopes: [String: RowAdapter]) {
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
}
+43 -19
View File
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -42,15 +43,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,18 +91,35 @@ 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)
}
/// A string that represented the statement in a lossless and
/// unambiguous way.
lazy var losslessDescription: String = {
"\(sql); -- \(arguments.losslessDescription)"
}()
/// A table name for caching the results of this statement
lazy var cacheTableName: String? = {
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
let losslessDescription = losslessDescription.data(using: .utf8)
else {
return nil
}
let digest = Insecure.SHA1.hash(data: losslessDescription)
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
}()
@usableFromInline
unowned let database: Database
/// 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 +136,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 +240,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)"
@@ -623,11 +640,6 @@ public final class Statement {
}
}
// Explicit non-conformance to Sendable: statements must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension Statement: Sendable { }
extension Statement: CustomStringConvertible {
public var description: String {
SchedulingWatchdog.allows(database) ? sql : "Statement"
@@ -785,10 +797,7 @@ final class StatementCursor: DatabaseCursor {
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
self._statement = statement
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
_statement = try statement.databaseCursorStatement(with: arguments)
}
deinit {
@@ -1036,7 +1045,7 @@ public struct StatementArguments: Hashable {
/// The result is nil unless all array elements conform to the
/// ``DatabaseValueConvertible`` protocol.
public init?(_ array: [Any]) {
var values = [(any DatabaseValueConvertible)?]()
var values = [DatabaseValueConvertible?]()
for value in array {
guard let dbValue = DatabaseValue(value: value) else {
return nil
@@ -1395,4 +1404,19 @@ extension StatementArguments: CustomStringConvertible {
}
}
extension StatementArguments {
/// A string that represented the value in a lossless and
/// unambiguous way.
var losslessDescription: String {
var chunks: [String] = []
for value in values {
chunks.append(value.losslessDescription)
}
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
chunks.append("\(key): \(value.losslessDescription)")
}
return chunks.joined(separator: ",")
}
}
extension StatementArguments: Sendable { }
+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
+2 -9
View File
@@ -89,7 +89,7 @@ public protocol StatementColumnConvertible {
///
/// Do not check for `NULL` in your implementation of this method. Null
/// database values are handled
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
///
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
@@ -214,6 +214,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@usableFromInline let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
let statement = try statement.databaseCursorStatement(with: arguments)
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
@@ -221,9 +222,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
@@ -241,11 +239,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension FastDatabaseValueCursor: Sendable { }
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
@@ -1,10 +1,10 @@
import Foundation
/// A database value that holds date components.
public struct DatabaseDateComponents: Sendable {
public struct DatabaseDateComponents {
/// The SQLite formats for date components.
public enum Format: String, Sendable {
public enum Format: String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -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)
}
@@ -4,7 +4,6 @@ import Foundation
@usableFromInline
struct SQLiteDateParser {
// swiftlint:disable:next unneeded_synthesized_initializer
@usableFromInline
init() { }
@@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? any DatabaseValueConvertible.Type {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
// String, for example.
@@ -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
}
}
+31 -112
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)
}
@@ -135,7 +117,7 @@ extension Database {
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent: Sendable {
public enum TransactionObservationExtent {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
@@ -282,20 +264,6 @@ class DatabaseObservationBroker {
}
}
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
// Support for stopObservingDatabaseChangesUntilNextTransaction()
SchedulingWatchdog.current!.databaseObservationBroker = self
defer {
SchedulingWatchdog.current!.databaseObservationBroker = nil
}
for observation in transactionObservations where observation.isEnabled {
if eventKinds.contains(where: { observation.observes(eventsOfKind: $0) }) {
observation.databaseDidChange()
}
}
}
// MARK: - Statement execution
/// Returns true if there exists some transaction observer interested in
@@ -486,7 +454,7 @@ class DatabaseObservationBroker {
if savepointStack.isEmpty {
// Notify now
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
statementObservation.transactionObservation.databaseWillChange(with: event)
}
} else {
@@ -511,7 +479,7 @@ class DatabaseObservationBroker {
if savepointStack.isEmpty {
// Notify now
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
statementObservation.transactionObservation.databaseDidChange(with: event)
}
} else {
@@ -580,11 +548,6 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
//
// 2023-11-26: I'm glad we did, because that's how we support calls
// to `Database.notifyChanges(in:)` from an empty transaction, as a
// way to tell transaction observers about changes performed by some
// external connection.
do {
try databaseWillCommit()
@@ -676,7 +639,7 @@ class DatabaseObservationBroker {
for (event, statementObservations) in eventsBuffer {
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
event.send(to: statementObservation.transactionObservation)
}
}
@@ -801,16 +764,6 @@ public protocol TransactionObserver: AnyObject {
/// from being applied on the observed tables.
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// Called when the database was modified in some unspecified way.
///
/// This method allows a transaction observer to handle changes that are
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// and ``Database/notifyChanges(in:)`` for more information.
///
/// The exact nature of changes is unknown, but they comply to the
/// ``observes(eventsOfKind:)`` test.
func databaseDidChange()
/// Called when the database is changed by an insert, update, or
/// delete event.
///
@@ -825,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.
@@ -834,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
@@ -886,15 +837,11 @@ extension TransactionObserver {
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// The default implementation does nothing.
public func databaseDidChange() { }
/// Prevents the observer from receiving further change notifications
/// until the next transaction.
/// Prevents the observer from receiving further change notifications until
/// the next transaction.
///
/// After this method has been called, the ``databaseDidChange(with:)``
/// and ``databaseDidChange()-7olv7`` methods won't be called until the
/// next transaction.
/// method won't be called until the next transaction.
///
/// For example:
///
@@ -907,13 +854,6 @@ extension TransactionObserver {
/// return eventKind.tableName == "player"
/// }
///
/// func databaseDidChange() {
/// playerTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playerTableWasModified = true
///
@@ -924,12 +864,12 @@ extension TransactionObserver {
/// ```
///
/// - precondition: This method must be called from
/// ``databaseDidChange(with:)`` or ``databaseDidChange()-7olv7``.
/// ``databaseDidChange(with:)``.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("""
stopObservingDatabaseChangesUntilNextTransaction must be called \
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
from the databaseDidChange method
""")
}
broker.disableUntilNextTransaction(transactionObserver: self)
@@ -982,11 +922,6 @@ final class TransactionObservation {
}
#endif
func databaseDidChange() {
guard isEnabled else { return }
observer?.databaseDidChange()
}
func databaseDidChange(with event: DatabaseEvent) {
guard isEnabled else { return }
observer?.databaseDidChange(with: event)
@@ -1034,18 +969,12 @@ final class TransactionObservation {
struct StatementObservation {
var transactionObservation: TransactionObservation
/// A predicate that filters database events that should be notified.
///
/// Call this predicate as a method:
///
/// ```
/// if observation.tracksEvent(event) { ... }
/// ```
var tracksEvent: DatabaseEventPredicate
/// Filters database events that should be notified.
var predicate: DatabaseEventPredicate
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
self.transactionObservation = transactionObservation
self.tracksEvent = predicate
self.predicate = predicate
}
}
@@ -1056,7 +985,7 @@ struct StatementObservation {
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
/// ``TransactionObserver`` protocol for more information.
@frozen
public enum DatabaseEventKind: Sendable {
public enum DatabaseEventKind {
/// The insertion of a row in a database table.
case insert(tableName: String)
@@ -1109,7 +1038,7 @@ protocol DatabaseEventProtocol {
/// ``TransactionObserver`` protocol for more information.
public struct DatabaseEvent {
/// An event kind.
public enum Kind: CInt, Sendable {
public enum Kind: CInt {
/// An insertion event
case insert = 18 // SQLITE_INSERT
@@ -1158,12 +1087,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,
@@ -1173,11 +1097,6 @@ public struct DatabaseEvent {
}
}
// Explicit non-conformance to Sendable: this type can't be made Sendable
// until GRDB7 where we can distinguish between a transient event and its copy.
@available(*, unavailable)
extension DatabaseEvent: Sendable { }
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
@@ -1204,8 +1123,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!) }
@@ -1340,8 +1259,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,
@@ -1397,8 +1316,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!) }
@@ -1528,7 +1447,7 @@ enum DatabaseEventPredicate {
/// statement authorizer.
case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind])
func callAsFunction(_ event: some DatabaseEventProtocol) -> Bool {
func evaluate(_ event: some DatabaseEventProtocol) -> Bool {
switch self {
case .all:
return true
+20 -33
View File
@@ -1,5 +1,3 @@
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
///
@@ -21,9 +19,14 @@
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
final class WALSnapshot: Sendable {
// Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support.
// Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support.
// This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))
// swiftlint:disable:next line_length
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
static let available = true
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
@@ -32,30 +35,11 @@ final class WALSnapshot: @unchecked Sendable {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
// >
// > 1. The database handle must not be in autocommit mode.
// > 2. Schema S of database connection D must be a WAL
// > mode database.
// > 3. There must not be a write transaction open on schema S
// > of database connection D.
// > 4. One or more transactions must have been written to the
// > current wal file since it was created on disk (by any
// > connection). This means that a snapshot cannot be taken
// > on a wal mode database with no wal file immediately
// > after it is first opened. At least one transaction must
// > be written to it first.
// Test condition 1:
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
throw DatabaseError(resultCode: code, message: """
Can't create snapshot because database is in autocommit mode.
""")
}
// Test condition 2:
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
journalMode != "wal"
{
@@ -63,14 +47,7 @@ final class WALSnapshot: @unchecked Sendable {
Can't create snapshot because database is not in WAL mode.
""")
}
// Condition 3 can't happen because GRDB only calls this
// initializer from read transactions.
//
// Hence it is condition 4 that is false:
throw DatabaseError(resultCode: code, message: """
Can't create snapshot from a missing or empty wal file.
""")
throw DatabaseError(resultCode: code)
}
guard let sqliteSnapshot else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
@@ -90,5 +67,15 @@ final class WALSnapshot: @unchecked Sendable {
func compare(_ other: WALSnapshot) -> CInt {
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
}
}
#else
static let available = false
init(_ db: Database) throws {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available")
}
func compare(_ other: WALSnapshot) -> CInt {
preconditionFailure("snapshots are not available")
}
#endif
}
+1 -3
View File
@@ -46,9 +46,7 @@ class WALSnapshotTransaction {
// Open a long-lived transaction, and enter snapshot isolation
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
return try WALSnapshot(db)
}
self.reader = reader
+7 -7
View File
@@ -14,7 +14,7 @@ The other chapters cover, with more details, the fundamentals of SQLite concurre
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
#### Rule 1: Connect to any database file only once
### Rule 1: Connect to any database file only once
Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
@@ -27,7 +27,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
- You will not be able to use the <doc:DatabaseObservation> features.
- You will see SQLite errors ([`SQLITE_BUSY`]).
#### Rule 2: Mind your transactions
### Rule 2: Mind your transactions
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
@@ -150,31 +150,31 @@ This prevents the database operations from various concurrent accesses from bein
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
#### Serialized Writes
### Serialized Writes
**All writes performed by one ``DatabaseQueue`` or ``DatabasePool`` instance are serialized.**
This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
#### Write Transactions
### Write Transactions
**All writes are wrapped in a transaction.**
Concurrent reads can not see partial database updates (even reads performed by other processes).
#### Isolated Reads
### Isolated Reads
**All reads are wrapped in a transaction.**
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
#### Forbidden Writes
### Forbidden Writes
**Inside a read access, all attempts to write raise an error.**
This enforces the immutability of the database during a read.
#### Non-Reentrancy
### Non-Reentrancy
**Database accesses methods are not reentrant.**
@@ -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
+27 -36
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,16 +241,16 @@ 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
try db.create(
indexOn: "player",
columns: ["teamId", "position"],
index: "playerTeamPosition",
on: "player", columns: ["teamId", "position"],
options: .unique)
```
@@ -267,7 +268,10 @@ try db.create(
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> try db.create(
> index: "teamName",
> on: "team", columns: ["name"],
> options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
@@ -306,7 +310,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 +322,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
@@ -363,7 +365,6 @@ extension Team: TableRecord {
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
@@ -373,35 +374,25 @@ extension Team: TableRecord {
- ``TableOptions``
- ``VirtualTableModule``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Querying the Database Schema
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/columns(in:)``
- ``Database/foreignKeys(on:)``
- ``Database/indexes(on:)``
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:in:)``
- ``Database/primaryKey(_:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
- ``Database/tableExists(_:)``
- ``Database/triggerExists(_:)``
- ``Database/viewExists(_:)``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -410,9 +401,9 @@ extension Team: TableRecord {
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/checkForeignKeys(in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``Database/foreignKeyViolations(in:)``
- ``ForeignKeyViolation``
### Sunsetted Methods
+7 -12
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:
@@ -152,14 +150,11 @@ If several processes want to write in the database, configure the database pool
```swift
var configuration = Configuration()
configuration.defaultTransactionKind = .immediate
configuration.busyMode = .timeout(/* a TimeInterval */)
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing.
With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
```swift
do {
@@ -231,7 +226,9 @@ In applications that use the background modes supported by iOS, post `resumeNoti
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter]. You can trigger those notifications automatically with ``DatabaseRegionObservation``:
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
```swift
// Notify all changes made to the database
@@ -247,8 +244,6 @@ let observer = try observation.start(in: dbPool) { db in
}
```
The processes that observe the database can catch those notifications, and deal with the notified changes. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> for some related techniques.
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[WAL mode]: https://www.sqlite.org/wal.html
+47
View File
@@ -0,0 +1,47 @@
# ``GRDB``
A toolkit for SQLite databases, with a focus on application development
## Overview
Use GRDB to save your application’s permanent data into SQLite databases.
The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool.
It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases.
It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
## Topics
### Fundamentals
- <doc:DatabaseConnections>
- <doc:SQLSupport>
- <doc:Concurrency>
- <doc:Transactions>
### Migrations and The Database Schema
- <doc:DatabaseSchema>
- <doc:Migrations>
- <doc:SingleRowTables>
### Records and the Query Interface
- <doc:QueryInterface>
- <doc:RecordTimestamps>
### Responding to Database Changes
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
### Combine Publishers
- ``DatabasePublishers``
@@ -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(_:_:)``
@@ -88,12 +88,11 @@ A `DatabaseQueue` needs your application to follow rules in order to deliver its
- ``init(named:configuration:)``
- ``init(path:configuration:)``
- ``inMemoryCopy(fromPath:configuration:)``
- ``temporaryCopy(fromPath:configuration:)``
### Accessing the Database
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
access methods.
- ``inDatabase(_:)``
- ``inTransaction(_:_:)``
@@ -6,7 +6,11 @@
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
The only changes that are not notified are:
- Changes performed by external database connections.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
@@ -74,30 +78,6 @@ let observation = DatabaseRegionObservation(
tracking: .fullDatabase)
```
## Dealing with Undetected Changes
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify such undetected changes, applications can take explicit action: call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
## Topics
### Creating DatabaseRegionObservation
@@ -74,14 +74,7 @@ extension Color: DatabaseValueConvertible { }
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
```swift
protocol DatabaseValueConvertible {
static func databaseJSONDecoder() -> JSONDecoder
static func databaseJSONEncoder() -> JSONEncoder
}
```
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
### Adding support for the Tagged library
@@ -151,11 +144,6 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``databaseValue-1ob9k``
### Configuring the JSON format for the standard Decodable protocol
- ``databaseJSONDecoder()-7zou9``
- ``databaseJSONEncoder()-37sff``
### Fetching Values from Raw SQL
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
@@ -25,7 +25,13 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
The only changes and transactions that are not notified are:
- Read-only transactions.
- Changes and transactions performed by external database connections.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
@@ -91,7 +97,7 @@ do {
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
## Filtering Database Events
@@ -183,7 +189,7 @@ class PlayerObserver: TransactionObserver {
}
```
## Support for SQLite Pre-Update Hooks
### Support for SQLite Pre-Update Hooks
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
@@ -229,41 +235,6 @@ This extra API can be activated in two ways:
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
## Dealing with Undetected Changes
The changes and transactions that are not automatically notified to transaction observers are:
- Read-only transactions.
- Changes and transactions performed by external database connections.
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
To notify undetected changes to transaction observers, perform an explicit call to the ``Database/notifyChanges(in:)`` `Database` method. The ``databaseDidChange()-7olv7`` callback will be called accordingly. For example:
```swift
try dbQueue.write { db in
// Notify observers that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observers that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
To notify a change in the database schema, notify a change to the `sqlite_master` table:
```swift
try dbQueue.write { db in
// Notify all observers of the sqlite_master table
try db.notifyChanges(in: Table("sqlite_master"))
}
```
## Topics
### Filtering Database Changes
@@ -273,7 +244,6 @@ try dbQueue.write { db in
### Handling Database Changes
- ``databaseDidChange()-7olv7``
- ``databaseDidChange(with:)``
- ``stopObservingDatabaseChangesUntilNextTransaction()``
- ``DatabaseEvent``
@@ -6,7 +6,11 @@
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
The only changes that are not notified are:
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
## ValueObservation Usage
@@ -155,7 +159,7 @@ let cancellable = try sharedObservation
While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control.
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:_:fetch:)`` to do just that:
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:fetch:)`` to do just that:
```swift
let observation = ValueObservation.tracking(
@@ -168,31 +172,7 @@ let observation = ValueObservation.tracking(
)
```
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
## Dealing with Undetected Changes
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
This ``tracking(region:fetch:)`` method lets you entirely separate the **observed region** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
## ValueObservation Performance
@@ -239,16 +219,13 @@ When needed, you can help GRDB optimize observations and reduce database content
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
## Topics
### Creating a ValueObservation
- ``tracking(_:)``
- ``trackingConstantRegion(_:)``
- ``tracking(region:_:fetch:)``
- ``tracking(region:fetch:)``
- ``tracking(regions:fetch:)``
### Creating a Shared Observation
-103
View File
@@ -1,103 +0,0 @@
# ``GRDB``
A toolkit for SQLite databases, with a focus on application development
##
![GRDB Logo](GRDBLogo.png)
## Overview
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
- **SQL Generation**
Enhance your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
- **Database Observation**
Get notifications when database values are modified.
- **Robust Concurrency**
Multi-threaded applications can efficiently use their databases, including WAL databases that support concurrent reads and writes.
- **Migrations**
Evolve the schema of your database as you ship new versions of your application.
- **Leverage your SQLite skills**
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Come with your SQL and SQLite skills, or learn new ones as you go!
## Usage
Start using the database in four steps:
```swift
import GRDB
// 1. Open a database connection
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// 2. Define the database schema
try dbQueue.write { db in
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
}
// 3. Define a record type
struct Player: Codable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var score: Int
}
// 4. Write and read in the database
try dbQueue.write { db in
try Player(id: "1", name: "Arthur", score: 100).insert(db)
try Player(id: "2", name: "Barbara", score: 1000).insert(db)
}
let players: [Player] = try dbQueue.read { db in
try Player.fetchAll(db)
}
```
## 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
### Fundamentals
- <doc:DatabaseConnections>
- <doc:SQLSupport>
- <doc:Concurrency>
- <doc:Transactions>
### Migrations and The Database Schema
- <doc:DatabaseSchema>
- <doc:Migrations>
### Records and the Query Interface
- <doc:QueryInterface>
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Application Tools
- <doc:DatabaseObservation>
- <doc:FullTextSearch>
- <doc:JSON>
- ``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(_:filter:)``
- ``Database/jsonGroupObject(key:value:filter:)``
### Modify JSON values at the SQL level
- ``Database/jsonInsert(_:_:)``
- ``Database/jsonPatch(_:with:)``
- ``Database/jsonReplace(_:_:)``
- ``Database/jsonRemove(_:atPath:)``
- ``Database/jsonRemove(_:atPaths:)``
- ``Database/jsonSet(_:_:)``
### Validate JSON values at the SQL level
- ``Database/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
+5 -2
View File
@@ -26,7 +26,10 @@ migrator.registerMigration("Create authors") { db in
migrator.registerMigration("Add books and author.birthYear") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author").notNull()
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.column("title", .text).notNull()
}
@@ -233,7 +236,7 @@ To prevent a migration from committing foreign key violations on disk, you can:
}
```
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
```swift
// SQLite error 19: FOREIGN KEY constraint violation - from book(authorId) to author(id),
+4 -12
View File
@@ -17,22 +17,16 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
- ``PersistableRecord``
- ``TableRecord``
### Expressions
### Associations
- ``Column``
- ``JSONColumn``
- ``SQLExpression``
- ``Association``
### Requests
### Query Interface Requests
- ``CommonTableExpression``
- ``QueryInterfaceRequest``
- ``Table``
### Associations
- ``Association``
### Errors
- ``RecordError``
@@ -40,11 +34,9 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
### Supporting Types
- ``ColumnExpression``
- ``DerivableRequest``
- ``SQLExpressible``
- ``SQLJSONExpressible``
- ``SQLSpecificExpressible``
- ``SQLSubqueryable``
- ``SQLOrderingTerm``
- ``SQLSelectable``
- ``SQLSubqueryable``
@@ -1,596 +0,0 @@
# Recommended Practices for Designing Record Types
Leverage the best of record types and associations.
## Overview
GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Core Data], so you may face questions when designing the model layer of your application.
This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors.
## Trust SQLite More Than Yourself
Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed.
This is why it is recommended to define a **robust database schema** even before playing with record types.
This is important because SQLite is very robust, whereas we developers write bugs. The more responsibility we give to SQLite, the less code we have to write, and the fewer defects we will ship on our users' devices, affecting their precious data.
For example, if we were to define <doc:Migrations> that configure a database made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("countryCode", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.belongsTo("author", onDelete: .cascade) // (6)
.notNull() // (7)
}
}
try migrator.migrate(dbQueue)
```
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
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.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
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.
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
>
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users data, as long as enough energy is put in the proper definition of the database schema.
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
## Record Types
### Persistable Record Types are Responsible for Their Tables
**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.
```swift
struct Author: Codable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
}
```
**We add database powers to our types with record protocols.**
The `author` and `book` tables have an auto-incremented id. We want inserted records to learn about their id after a successful insertion. That's why we have them conform to the ``MutablePersistableRecord`` protocol, and implement ``MutablePersistableRecord/didInsert(_:)-109jm``. Other kinds of record types would just use ``PersistableRecord``, and ignore `didInsert`.
On the reading side, we use ``FetchableRecord``, the protocol that can decode database rows.
This gives:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`:
```swift
try dbQueue.write { db in
// Insert and set author's id
var author = Author(name: "Herman Melville", countryCode: "US")
try author.insert(db)
// Insert and set book's id
var book = Book(authorId: author.id!, title: "Moby-Dick")
try book.insert(db)
}
let books = try dbQueue.read { db in
try Book.fetchAll(db)
}
```
> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare:
>
> ```swift
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> t.column("name", .text).notNull() // Can't be NULL
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
> }
> ```
>
> There are exceptions to this rule.
>
> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
>
> Another exception to this rule is described in <doc:RecordTimestamps>, where the creation date of a record is never NULL in the database, but optional in the Swift type.
> Tip: When the database table has a single-column primary key, have the record type adopt the standard [`Identifiable`] protocol. This allows GRDB to define extra methods based on record ids:
>
> ```swift
> let authorID: Int64 = 42
> let author: Author = 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
In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
But it happens that raw database column names, or raw column types, are not a very good fit for the application.
When this happens, it's time to **distinguish the Swift and database representations**. Record types are the dedicated place where raw database values can be transformed into Swift types that are well-suited for the rest of the application.
Let's look at three examples.
#### First Example: Enums
Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database:
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We prefer an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case essay, novel, poetry, theater
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
Thanks to its enum property, the `Book` record prevents invalid book kinds from being stored into the database.
In order to use `Book.Kind` in database requests for books (see <doc:RecordRecommendedPractices#Record-Requests> below), we add the ``DatabaseValueConvertible`` conformance to `Book.Kind`:
```swift
extension Book.Kind: DatabaseValueConvertible { }
// Fetch all novels
let novels = try dbQueue.read { db in
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
}
```
#### Second Example: GPS Coordinates
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
try db.create(table: "place") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("latitude", .double).notNull()
t.column("longitude", .double).notNull()
}
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique.
#### Third Example: Money Amounts
Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency).
SQLite only supports two kinds of numbers: integers and doubles, so we'll store amounts as integers. $12.00 will be represented by 1200, a quantity of cents. This allows SQLite to compute exact sums of price, for example.
On the other side, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit.
That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column:
```swift
try db.create(table: "product") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("priceCents", .integer).notNull()
}
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get {
Decimal(priceCents) / 100
}
set {
priceCents = Self.cents(for: newValue)
}
}
private static func cents(for value: Decimal) -> Int {
Int(Double(truncating: NSDecimalNumber(decimal: value * 100)))
}
}
```
## Record Requests
Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records.
### Columns
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
```swift
// HOW TO define columns for a Codable record
extension Author {
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let countryCode = Column(CodingKeys.countryCode)
}
}
```
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
```swift
// HOW TO define columns for a non-Codable record
extension Author {
enum Columns: String, ColumnExpression {
case id, name, countryCode
}
}
```
From those columns it is possible to define requests of type ``QueryInterfaceRequest``:
```swift
try dbQueue.read { db in
// Fetch all authors, ordered by name,
// in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// Count French authors
let frenchAuthorCount: Int = try Author.all()
.filter(Author.Columns.countryCode == "FR")
.fetchCount(db)
}
```
### Turn Commonly-Used Requests into Methods
An application can define reusable request methods that extend the built-in GRDB apis. Those methods avoid code repetition, ease refactoring, and foster testability.
Define those methods in extensions of the ``DerivableRequest`` protocol, as below:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(countryCode: String) -> Self {
filter(Author.Columns.countryCode == countryCode)
}
}
// Book requests
extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
func orderByTitle() -> Self {
let title = Book.Columns.title
return order(title.collating(.localizedCaseInsensitiveCompare))
}
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
}
```
Those methods define a fluent and legible api that encapsulates intimate database details:
```swift
try dbQueue.read { db in
let sortedSpanishAuthors: [Author] = try Author.all()
.filter(countryCode: "ES")
.orderByName()
.fetchAll(db)
let novelCount: Int = try Book.all()
.filter(kind: .novel)
.fetchCount(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below:
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.fetchSet(db)
```
## Associations
[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
```swift
extension Book {
static let author = belongsTo(Author.self)
}
extension Author {
static let books = hasMany(Book.self)
}
```
With associations, you can fetch a book's author, or an author's books:
```swift
// Fetch all novels from an author
try dbQueue.read { db in
let author: Author = ...
let novels: [Book] = try author.request(for: Author.books)
.filter(kind: .novel)
.orderByTitle()
.fetchAll(db)
}
```
Associations also make it possible to define more convenience request methods:
```swift
extension DerivableRequest<Book> {
/// Filters books from a country
func filter(authorCountryCode countryCode: String) -> Self {
// Books do not have any country column. But their author has one!
// Return books that can be joined to an author from this country:
joining(required: Book.author.filter(countryCode: countryCode))
}
}
// Fetch all Italian novels
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountryCode: "IT")
.fetchAll(db)
}
```
With associations, you can also process graphs of authors and books, as described in the next section.
### How to Model Graphs of Objects
Since the beginning of this article, the `Book` and `Author` are independent structs that don't know each other. The only "meeting point" is the `Book.authorId` property.
Record types don't know each other on purpose: one does not need to know the author of a book when it's time to update the title of a book, for example.
When an application wants to process authors and books together, it defines dedicated types that model the desired view on the graph of related objects. For example:
```swift
// Fetch all authors along with their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
try Author
.annotated(with: Author.books.count)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
}
```
```swift
// Fetch the literary careers of German authors, sorted by name
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let careers: [LiteraryCareer] = try dbQueue.read { db in
try Author
.filter(countryCode: "DE")
.orderByName()
.including(all: Author.books)
.asRequest(of: LiteraryCareer.self)
.fetchAll(db)
}
```
```swift
// Fetch all Colombian books and their authors
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
try Book.all()
.including(required: Book.author.filter(countryCode: "CO"))
.asRequest(of: Authorship.self)
.fetchAll(db)
// Equivalent alternative
try Book.all()
.filter(authorCountryCode: "CO")
.including(required: Book.author)
.asRequest(of: Authorship.self)
.fetchAll(db)
}
```
In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
For more information about associations, see the [Associations] guide.
### Lazy and Eager Loading: Comparison with Other Database Libraries
The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types.
For example, [Core Data] and Ruby's [Active Record] use **lazy loading**. This means that relationships are lazily fetched on demand:
```ruby
# Lazy loading with Active Record
author = Author.first # Fetch first author
puts author.name
author.books.each do |book| # Lazily fetch books on demand
puts book.title
end
```
**GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the <doc:Concurrency> guide for more information.
Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested:
```swift
// Eager loading with Fluent
let query = Author.query(on: db)
.with(\.$books) // <- Explicit request for books
.first()
// Fetch first author and its books in one stroke
if let author = query.get() {
print(author.name)
for book in author.books { print(book.title) }
}
```
One must take care of fetching relationships, though, or Fluent raises a fatal error:
```swift
// Oops, the books relation is not explicitly requested
let query = Author.query(on: db).first()
if let author = query.get() {
// fatal error: Children relation not eager loaded.
for book in author.books { print(book.title) }
}
```
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides runtime safety:
```swift
// Eager loading with GRDB
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let request = Author.all()
.including(all: Author.books) // <- Explicit request for books
.asRequest(of: LiteraryCareer.self)
// Fetch first author and its books in one stroke
if let career = try request.fetchOne(db) {
print(career.author.name)
for book in career.books { print(book.title) }
}
```
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[`Codable`]: https://developer.apple.com/documentation/swift/Codable
[Core Data]: https://developer.apple.com/documentation/coredata
[`Decimal`]: https://developer.apple.com/documentation/foundation/decimal
[`Decodable`]: https://developer.apple.com/documentation/swift/Decodable
[Django]: https://docs.djangoproject.com/en/4.2/topics/db/
[Fluent]: https://docs.vapor.codes/fluent/overview/
[`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable
[isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[Associations]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md
+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?
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

-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.
-357
View File
@@ -1,357 +0,0 @@
import Foundation
// MARK: - Dump
extension Database {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
/// }
/// ```
///
/// - Parameters:
/// - sql: The executed SQL.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSQL(
_ sql: SQL,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSQL(sql, format: format, to: &dumpStream)
}
/// Prints the results of a request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpRequest(Player.orderByPrimaryKey())
/// }
/// ```
///
/// - Parameters:
/// - request : The executed request.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpRequest(request, format: format, to: &dumpStream)
}
/// Prints the contents of the provided tables and views.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// try db.dumpTables(["player", "team"])
/// }
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - stableOrder: A boolean value that controls the ordering of
/// rows fetched from views. If false (the default), rows are
/// printed in the order specified by the view (which may be
/// undefined). It true, outputted rows are always printed in the
/// same stable order. The purpose of this stable order is to make
/// the output suitable for testing.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpTables(
_ tables: [String],
format: some DumpFormat = .debug(),
tableHeader: DumpTableHeaderOptions = .automatic,
stableOrder: Bool = false,
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: &dumpStream)
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpContent()
/// }
/// ```
///
/// This prints the database schema as well as the content of all
/// tables. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
///
/// player
/// 1,'Arthur',500
/// 2,'Barbara',1000
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpContent(
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpContent(format: format, to: &dumpStream)
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpSchema()
/// }
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSchema(to: &dumpStream)
}
}
// MARK: -
extension Database {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
while let statement = try statements.next() {
var stepFormat = format
let cursor = try statement.makeCursor()
while try cursor.next() != nil {
try stepFormat.writeRow(self, statement: statement, to: &stream)
}
stepFormat.finalize(self, statement: statement, to: &stream)
}
}
func _dumpSQL(
_ sql: SQL,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpStatements(allStatements(literal: sql), format: format, to: &stream)
}
func _dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
let preparedRequest = try request.makePreparedRequest(self, forSingleResult: false)
try _dumpStatements(AnyCursor([preparedRequest.statement]), format: format, to: &stream)
if let supplementaryFetch = preparedRequest.supplementaryFetch {
let rows = try Row.fetchAll(self, request)
try withoutActuallyEscaping(
{ request, keyPath in
stream.write("\n")
stream.writeln(keyPath.joined(separator: "."))
try self._dumpRequest(request, format: format, to: &stream)
},
do: { willExecuteSupplementaryRequest in
try supplementaryFetch(self, rows, willExecuteSupplementaryRequest)
})
}
}
func _dumpTables(
_ tables: [String],
format: some DumpFormat,
tableHeader: DumpTableHeaderOptions,
stableOrder: Bool,
to stream: inout DumpStream)
throws
{
let header: Bool
switch tableHeader {
case .always: header = true
case .automatic: header = tables.count > 1
}
var first = true
for table in tables {
if first {
first = false
} else {
stream.write("\n")
}
if header {
stream.writeln(table)
}
if try tableExists(table) {
// Always sort tables by primary key
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
} else if stableOrder {
// View with stable order
try _dumpRequest(Table(table).all().withStableOrder(), format: format, to: &stream)
} else {
// Use view ordering, if any (no guarantee of stable order).
try _dumpRequest(Table(table).all(), format: format, to: &stream)
}
}
}
func _dumpContent(
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpSchema(to: &stream)
stream.margin()
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
try !ignoresObject(named: $0)
}
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
}
func _dumpSchema(
to stream: inout DumpStream)
throws
{
stream.writeln("sqlite_master")
let sqlRows = try Row.fetchAll(self, sql: """
SELECT sql || ';', name
FROM sqlite_master
WHERE sql IS NOT NULL
ORDER BY
tbl_name COLLATE NOCASE,
CASE type WHEN 'table' THEN 'a' WHEN 'index' THEN 'aa' ELSE type END,
name COLLATE NOCASE,
sql
""")
for row in sqlRows {
let name: String = row[1]
if try ignoresObject(named: name) {
continue
}
stream.writeln(row[0])
}
}
private func ignoresObject(named name: String) throws -> Bool {
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
}
return table.kind == .shadow
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
guard let table = try table(tableName) else {
// Not a table
return false
}
return table.kind == .shadow
}
#endif
// Don't know
return false
}
}
/// Options for printing table names.
public enum DumpTableHeaderOptions: Sendable {
/// Table names are only printed when several tables are printed.
case automatic
/// Table names are always printed.
case always
}
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff. Show more