mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
Merge branch 'development'
This commit is contained in:
commit
8330469ac3
114 files changed
+3831
-2191
No files matched your search
@@ -106,7 +106,6 @@ Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
.swiftpm/
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
#Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,134 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1410"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB"
|
||||
BuildableName = "GRDB"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB-dynamic"
|
||||
BuildableName = "GRDB-dynamic"
|
||||
BlueprintName = "GRDB-dynamic"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CSQLite"
|
||||
BuildableName = "CSQLite"
|
||||
BlueprintName = "CSQLite"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.4.x` Releases - [6.4.0](#640)
|
||||
- `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631)
|
||||
- `6.2.x` Releases - [6.2.0](#620)
|
||||
- `6.1.x` Releases - [6.1.0](#610)
|
||||
@@ -101,6 +102,19 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.4.0
|
||||
|
||||
Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.1...v6.4.0)
|
||||
|
||||
- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot.
|
||||
- **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product.
|
||||
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
|
||||
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
|
||||
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
|
||||
- **New**: `Database.registerAccess(to:)` has `ValueObservation` track a region. This helps building optimized observations of a constant database region with `ValueObservation.trackingConstantRegion(_:)`.
|
||||
- **New**: Open several connections to the same in-memory database with `DatabaseQueue(named:)`.
|
||||
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition)) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
|
||||
|
||||
## 6.3.1
|
||||
|
||||
Released November 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.0...v6.3.1)
|
||||
|
||||
@@ -511,7 +511,7 @@ When using class names composed of two or more words, the table name should use
|
||||
| Mouse | mouse | `mouse`, `mice`, `maxMouseSize` |
|
||||
| Person | person | `person`, `people`, `personCount` |
|
||||
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](http://github.com/groue/GRDB.swift/issues).
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](https://github.com/groue/GRDB.swift/issues).
|
||||
|
||||
See [The Structure of a Joined Request] for more information.
|
||||
|
||||
@@ -649,7 +649,7 @@ Here is the recommended [migration] for the **[HasOne]** association:
|
||||
```swift
|
||||
migrator.registerMigration("Countries") { db in
|
||||
try db.create(table: "country") { t in
|
||||
t.column("code", .text).primaryKey() // (1)
|
||||
t.primaryKey("code", .text) // (1)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "demographics") { t in
|
||||
@@ -3008,8 +3008,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Codable Records]: ../README.md#codable-records
|
||||
[persistence methods]: ../README.md#persistence-methods
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
|
||||
@@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
|
||||
|
||||
@@ -248,8 +248,6 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
|
||||
|
||||
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
|
||||
|
||||
|
||||
#### `SharedValueObservation.publisher()`
|
||||
|
||||
@@ -384,14 +382,14 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[Usage]: #usage
|
||||
[Asynchronous Database Access]: #asynchronous-database-access
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Database Changes Observation]: ../README.md#database-changes-observation
|
||||
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[Database Observation]: #database-observation
|
||||
[Combine and Data Consistency]: #combine-and-data-consistency
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[SharedValueObservation]: ../README.md#valueobservation-sharing
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
|
||||
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
|
||||
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
|
||||
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
|
||||
|
||||
@@ -5,7 +5,7 @@ By default, GRDB uses the version of SQLite that ships with the target operating
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
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).
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
@@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](../README.md#database-pools).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ struct AppDatabase {
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
|
||||
@@ -13,7 +13,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](../../../README.md#valueobservation).
|
||||
- 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 [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ struct AppDatabase {
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
|
||||
@@ -13,7 +13,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](../../../README.md#valueobservation) Combine publishers.
|
||||
- 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 [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ final class AppDatabase {
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
|
||||
@@ -13,14 +13,14 @@ 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](../../../README.md#valueobservation).
|
||||
- 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 [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) in order to let the application observe database changes.
|
||||
|
||||
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
|
||||
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
FetchedRecordsController has been removed in GRDB 5.
|
||||
|
||||
The [Database Observation](../README.md#database-changes-observation) chapter describes the other ways to observe the database.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
|
||||
@@ -726,10 +726,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
|
||||
|
||||
**You can define [record](../README.md#records) types around the full-text virtual tables.**
|
||||
|
||||
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
|
||||
|
||||
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
|
||||
|
||||
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
|
||||
|
||||
## Unicode Full-Text Gotchas
|
||||
|
||||
|
||||
@@ -499,10 +499,10 @@ let publisher = observation
|
||||
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
@@ -510,4 +510,4 @@ let publisher = observation
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
@@ -810,10 +810,10 @@ Instead, have a look at [Database Observation]:
|
||||
[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]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[TransactionObserver]: ../README.md#transactionobserver-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
|
||||
@@ -823,7 +823,7 @@ Instead, have a look at [Database Observation]:
|
||||
[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]: ../README.md#database-changes-observation
|
||||
[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
|
||||
|
||||
@@ -607,8 +607,8 @@ myRequest(Player.select(...).filter(...))
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: #databaseregionconvertible
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
|
||||
@@ -21,7 +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 http://github.com/groue/WWDCCompanion
|
||||
- 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`
|
||||
@@ -149,7 +149,7 @@ Next, you choose the dispatch queue on which notifications happen (generally the
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
See [Database Observation](../README.md#database-changes-observation) for further information.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
@@ -290,18 +290,17 @@ Happy GRDB! :gift:
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[GRDB]: https://github.com/groue/GRDB.swift
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[FetchableRecord]: ../README.md#records
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[SQLite.swift]: https://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
[Swift-Kuery]: https://github.com/IBM-Swift/Swift-Kuery
|
||||
[TableRecord]: ../README.md#records
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[associations]: AssociationsBasics.md
|
||||
[Codable records]: ../README.md#codable-records
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.3.1'
|
||||
s.version = '6.4.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -202,6 +202,8 @@
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.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 */; };
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
@@ -616,6 +618,8 @@
|
||||
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>"; };
|
||||
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>"; };
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
@@ -906,11 +910,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
566BD72F2927AFC300595649 /* Observers */,
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
sourceTree = "<group>";
|
||||
@@ -1232,6 +1235,15 @@
|
||||
path = Utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
566BD72F2927AFC300595649 /* Observers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
);
|
||||
path = Observers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1334,6 +1346,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1438,6 +1451,7 @@
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
@@ -1494,7 +1508,7 @@
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */ = {
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */,
|
||||
@@ -1503,7 +1517,7 @@
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */,
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
path = Reducers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
|
||||
@@ -1785,6 +1799,7 @@
|
||||
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
|
||||
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
|
||||
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */,
|
||||
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
|
||||
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */,
|
||||
@@ -2035,6 +2050,7 @@
|
||||
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */,
|
||||
5605F1631C672E4000235C62 /* Date.swift in Sources */,
|
||||
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
|
||||
+115
-44
@@ -19,6 +19,37 @@ import Foundation
|
||||
/// ```
|
||||
///
|
||||
/// See <doc:DatabaseConnections>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Configuration
|
||||
///
|
||||
/// - ``init()``
|
||||
///
|
||||
/// ### Configuring SQLite Connections
|
||||
///
|
||||
/// - ``acceptsDoubleQuotedStringLiterals``
|
||||
/// - ``busyMode``
|
||||
/// - ``foreignKeysEnabled``
|
||||
/// - ``readonly``
|
||||
///
|
||||
/// ### Configuring GRDB Connections
|
||||
///
|
||||
/// - ``allowsUnsafeTransactions``
|
||||
/// - ``defaultTransactionKind``
|
||||
/// - ``label``
|
||||
/// - ``maximumReaderCount``
|
||||
/// - ``observesSuspensionNotifications``
|
||||
/// - ``prepareDatabase(_:)``
|
||||
/// - ``publicStatementArguments``
|
||||
///
|
||||
/// ### Configuring the Quality of Service
|
||||
///
|
||||
/// - ``qos``
|
||||
/// - ``readQoS``
|
||||
/// - ``writeQoS``
|
||||
/// - ``targetQueue``
|
||||
/// - ``writeTargetQueue``
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
@@ -40,9 +71,9 @@ public struct Configuration {
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// ```swift
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
/// var config = Configuration()
|
||||
/// config.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
@@ -90,25 +121,24 @@ public struct Configuration {
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Error: no such column: foo
|
||||
/// // Error: no such column: missingColumn
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When true, or before SQLite version 3.29.0, such strings are interpreted
|
||||
/// as string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote):
|
||||
/// When true, or before SQLite version 3.29.0, double-quoted strings that
|
||||
/// do not match any valid identifier are interpreted as string literals,
|
||||
/// as in the example below. This is an SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Success: "foo"
|
||||
/// // MISFEATURE: This query succeeds with result "missingColumn"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
@@ -119,13 +149,10 @@ public struct Configuration {
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// Database suspension helps avoiding the
|
||||
/// [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a ``DatabaseError`` of code `SQLITE_INTERRUPT` or `SQLITE_ABORT`. You
|
||||
/// can check for those error codes with the
|
||||
/// ``DatabaseError/isInterruptionError`` property.
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// A boolean value indicating whether statement arguments are visible in
|
||||
@@ -133,25 +160,24 @@ public struct Configuration {
|
||||
///
|
||||
/// The default and recommended value is false: statement arguments are not
|
||||
/// visible in database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
///
|
||||
/// For example:
|
||||
/// information from leaking in unexpected places. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when a statement is traced:
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
///
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
@@ -163,19 +189,21 @@ public struct Configuration {
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// // Enable verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(event)
|
||||
/// }
|
||||
///
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -198,7 +226,8 @@ public struct Configuration {
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// // Prints all SQL statements
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -225,10 +254,25 @@ public struct Configuration {
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
/// The default kind of write transactions.
|
||||
///
|
||||
/// The default is ``Database/TransactionKind/deferred``.
|
||||
///
|
||||
/// You can change the default transaction kind. For example, you can force
|
||||
/// all write transactions to be `IMMEDIATE`:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.defaultTransactionKind = .immediate
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
|
||||
/// try dbQueue.write { db in ... }
|
||||
/// ```
|
||||
///
|
||||
/// This property is ignored for read-only transactions. Those always open
|
||||
/// `DEFERRED` SQLite transactions.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
@@ -286,20 +330,41 @@ public struct Configuration {
|
||||
///
|
||||
/// This configuration applies to ``DatabasePool`` only. The default value
|
||||
/// is 5.
|
||||
///
|
||||
/// You can query this value at runtime in order to get the actual capacity
|
||||
/// for concurrent reads of any ``DatabaseReader``. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.maximumReaderCount = 5
|
||||
///
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue(path: path, configuration: config)
|
||||
/// let dbPool = try DatabasePool(path: path, configuration: config)
|
||||
/// let dbSnapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// print(dbQueue.configuration.maximumReaderCount) // 1
|
||||
/// print(dbPool.configuration.maximumReaderCount) // 5
|
||||
/// print(dbSnapshot.configuration.maximumReaderCount) // 1
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service, or the execution priority, or database accesses.
|
||||
/// The quality of service of database accesses.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a ``targetQueue``.
|
||||
///
|
||||
/// The default is `userInitiated`.
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The quality of service of read accesses
|
||||
var readQoS: DispatchQoS {
|
||||
/// The effective quality of service of read-only database accesses.
|
||||
public var readQoS: DispatchQoS {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// The effective quality of service of write database accesses.
|
||||
public var writeQoS: DispatchQoS {
|
||||
writeTargetQueue?.qos ?? targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// The target dispatch queue for database accesses.
|
||||
///
|
||||
/// Database connections which are not read-only will prefer
|
||||
@@ -316,7 +381,7 @@ public struct Configuration {
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target dispatch queue for database accesses which are not read-only.
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled
|
||||
/// by ``targetQueue``.
|
||||
@@ -340,7 +405,13 @@ public struct Configuration {
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
var threadingMode: Database.ThreadingMode = .`default`
|
||||
/// The SQLite [threading mode](https://www.sqlite.org/threadsafe.html).
|
||||
///
|
||||
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
|
||||
/// supported, since all <doc:DatabaseConnections> access SQLite connections
|
||||
/// through a `SerializedDatabase`.
|
||||
var threadingMode = Database.ThreadingMode.default
|
||||
|
||||
var SQLiteConnectionDidOpen: (() -> Void)?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
|
||||
var SQLiteConnectionDidClose: (() -> Void)?
|
||||
|
||||
@@ -79,6 +79,13 @@ extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Returns the current schema version.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
|
||||
public func schemaVersion() throws -> Int32 {
|
||||
try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))!
|
||||
}
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// If the database schema is modified by another SQLite connection to the
|
||||
@@ -106,7 +113,7 @@ extension Database {
|
||||
// at offset 40 of the database header:
|
||||
// <https://sqlite.org/pragma.html#pragma_schema_version>
|
||||
// <https://sqlite.org/fileformat2.html#database_header>
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
let schemaVersion = try self.schemaVersion()
|
||||
if lastSchemaVersion != schemaVersion {
|
||||
lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
@@ -1317,13 +1324,6 @@ enum SchemaObjectType: String {
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
@@ -1352,3 +1352,12 @@ struct SchemaInfo: Equatable {
|
||||
var sql: String?
|
||||
}
|
||||
}
|
||||
|
||||
extension SchemaInfo {
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
}
|
||||
@@ -431,9 +431,7 @@ extension Database {
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
// Record the database region selected by the statement execution.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
try registerAccess(to: statement.databaseRegion)
|
||||
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker?.statementWillExecute(statement)
|
||||
|
||||
+90
-44
@@ -64,11 +64,12 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``TransactionCompletion``
|
||||
/// - ``TransactionKind``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
/// ### Database Observation
|
||||
///
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
///
|
||||
@@ -102,11 +103,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``DatabaseBackupProgress``
|
||||
/// - ``TraceEvent``
|
||||
/// - ``TracingOptions``
|
||||
///
|
||||
/// ### Sunsetted Methods
|
||||
///
|
||||
/// - ``create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
/// - ``create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// The Database class is not thread-safe. An instance should always be
|
||||
// used through a SerializedDatabase.
|
||||
@@ -216,6 +212,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Internal properties
|
||||
|
||||
let path: String
|
||||
|
||||
/// Support for schema changes performed with ``DatabasePool``: each read
|
||||
/// access needs to clear the schema cache if the schema has been modified
|
||||
/// by the writer connection since the previous read. This property is reset
|
||||
@@ -259,9 +257,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
/// Whether the database region selected by statement execution is
|
||||
/// recorded into `selectedRegion`.
|
||||
/// recorded into `selectedRegion` by `track(_:)`.
|
||||
///
|
||||
/// To record the selected region, use `recordingSelection(_:_:)`.
|
||||
/// To start recording the selected region, use `recordingSelection(_:_:)`.
|
||||
private(set) var isRecordingSelectedRegion = false
|
||||
|
||||
/// The database region selected by statement execution, when
|
||||
@@ -305,6 +303,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
// don't bother installing the observation broker for read-only connections.
|
||||
@@ -686,27 +685,66 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
readOnlyDepth > 0 || configuration.readonly
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure.
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var region = DatabaseRegion()
|
||||
/// try db.recordingSelection(®ion) {
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let team = try Team.fetchOne(db, id: 42)
|
||||
/// }
|
||||
/// print(region) // player(*),team(*)[42]
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // All changes to the 'player' and 'team' tables
|
||||
/// // will trigger the observation.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// try db.registerAccess(to: Team.all())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples
|
||||
/// of region reporting.
|
||||
///
|
||||
/// This method has no effect on a ``ValueObservation`` created with an
|
||||
/// explicit list of tracked regions. In the example below, only the
|
||||
/// `player` table is tracked:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observes the 'player' table only
|
||||
/// let observation = ValueObservation.tracking(region: Player.all()) { db in
|
||||
/// // Ignored
|
||||
/// try db.registerAccess(to: Team.all())
|
||||
/// }
|
||||
/// ```
|
||||
public func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws {
|
||||
if isRecordingSelectedRegion {
|
||||
try selectedRegion.formUnion(region().databaseRegion(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var region = DatabaseRegion()
|
||||
/// try db.recordingSelection(®ion) {
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let team = try Team.fetchOne(db, id: 42)
|
||||
/// try db.registerAccess(to: Table("awards"))
|
||||
/// }
|
||||
/// print(region) // awards,player(*),team(*)[42]
|
||||
/// ```
|
||||
///
|
||||
/// This method is used by ``ValueObservation``:
|
||||
///
|
||||
/// let playersObservation = ValueObservation.tracking { db in
|
||||
/// // Here all fetches are recorded, so that we know what is the
|
||||
/// // database region that must be observed.
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let playersObservation = ValueObservation.tracking { db in
|
||||
/// // Here all fetches are recorded, so that we know what is the
|
||||
/// // database region that must be observed.
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
if region.isFullDatabase {
|
||||
return try block()
|
||||
@@ -878,6 +916,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// are suspended.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A suspended database makes everything to avoid acquiring a lock on the
|
||||
/// database. All database operations may throw a ``DatabaseError`` of code
|
||||
/// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode.
|
||||
///
|
||||
/// See <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception> for
|
||||
/// more information.
|
||||
public static let suspendNotification = Notification.Name("GRDB.Database.Suspend")
|
||||
|
||||
/// When this notification is posted, databases which were opened with the
|
||||
@@ -1679,26 +1724,23 @@ extension Database {
|
||||
|
||||
/// An SQL column type.
|
||||
///
|
||||
/// You use column types when you modify the database schema. For example,
|
||||
/// the code below create a `player` table with a `name` column whose type
|
||||
/// is ``text`` (`TEXT` in SQL):
|
||||
/// You use column types when you modify the database schema. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// // name TEXT
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT,
|
||||
/// // creationDate DATETIME,
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.primaryKey("id", .integer)
|
||||
/// t.column("name", .text)
|
||||
/// t.column("creationDate", .datetime)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A `ColumnType` is an element of the SQL language, as is `TEXT` in the
|
||||
/// example above. The type comes with many built-in constants for
|
||||
/// frequently used types: ``text``, ``integer``, etc.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html>
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
|
||||
public let rawValue: String
|
||||
@@ -1708,34 +1750,34 @@ extension Database {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The `TEXT` SQL column type.
|
||||
/// The `TEXT` column type.
|
||||
public static let text = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `INTEGER` SQL column type.
|
||||
/// The `INTEGER` column type.
|
||||
public static let integer = ColumnType(rawValue: "INTEGER")
|
||||
|
||||
/// The `DOUBLE` SQL column type.
|
||||
/// The `DOUBLE` column type.
|
||||
public static let double = ColumnType(rawValue: "DOUBLE")
|
||||
|
||||
/// The `REAL` SQL column type.
|
||||
/// The `REAL` column type.
|
||||
public static let real = ColumnType(rawValue: "REAL")
|
||||
|
||||
/// The `NUMERIC` SQL column type.
|
||||
/// The `NUMERIC` column type.
|
||||
public static let numeric = ColumnType(rawValue: "NUMERIC")
|
||||
|
||||
/// The `BOOLEAN` SQL column type.
|
||||
/// The `BOOLEAN` column type.
|
||||
public static let boolean = ColumnType(rawValue: "BOOLEAN")
|
||||
|
||||
/// The `BLOB` SQL column type.
|
||||
/// The `BLOB` column type.
|
||||
public static let blob = ColumnType(rawValue: "BLOB")
|
||||
|
||||
/// The `DATE` SQL column type.
|
||||
/// The `DATE` column type.
|
||||
public static let date = ColumnType(rawValue: "DATE")
|
||||
|
||||
/// The `DATETIME` SQL column type.
|
||||
/// The `DATETIME` column type.
|
||||
public static let datetime = ColumnType(rawValue: "DATETIME")
|
||||
|
||||
/// The `ANY` SQL column type.
|
||||
/// The `ANY` column type.
|
||||
public static let any = ColumnType(rawValue: "ANY")
|
||||
}
|
||||
|
||||
@@ -1968,6 +2010,10 @@ extension Database {
|
||||
}
|
||||
|
||||
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
|
||||
///
|
||||
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
|
||||
/// supported, since all <doc:DatabaseConnections> access SQLite connections
|
||||
/// through a `SerializedDatabase`.
|
||||
enum ThreadingMode {
|
||||
case `default`
|
||||
case multiThread
|
||||
|
||||
@@ -46,10 +46,6 @@ import UIKit
|
||||
///
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshot
|
||||
///
|
||||
/// - ``makeSnapshot()``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
@@ -58,6 +54,11 @@ import UIKit
|
||||
/// - ``asyncConcurrentRead(_:)``
|
||||
/// - ``writeInTransaction(_:_:)``
|
||||
///
|
||||
/// ### Creating Database Snapshots
|
||||
///
|
||||
/// - ``makeSnapshot()``
|
||||
/// - ``makeSnapshotPool()``
|
||||
///
|
||||
/// ### Managing SQLite Connections
|
||||
///
|
||||
/// - ``invalidateReadOnlyConnections()``
|
||||
@@ -185,7 +186,7 @@ public final class DatabasePool {
|
||||
|
||||
/// Returns a Configuration suitable for readonly connections on a
|
||||
/// WAL database.
|
||||
static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
private static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
configuration.readonly = true
|
||||
@@ -194,7 +195,7 @@ public final class DatabasePool {
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
|
||||
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
// > But there are some obscure cases where a query against a WAL-mode
|
||||
// > database can return SQLITE_BUSY, so applications should be prepared
|
||||
// > for that happenstance.
|
||||
@@ -431,7 +432,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
@@ -474,10 +475,9 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
@@ -493,6 +493,8 @@ extension DatabasePool: DatabaseReader {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else if writer.onValidQueue {
|
||||
return try writer.execute(value)
|
||||
} else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -589,7 +591,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
@@ -830,10 +832,8 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
///
|
||||
/// The returned snapshot sees an unchanging database content, as it existed
|
||||
/// at the moment it was created.
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is opened:
|
||||
@@ -851,9 +851,10 @@ extension DatabasePool {
|
||||
/// the transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
@@ -861,8 +862,10 @@ extension DatabasePool {
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// }
|
||||
///
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// ```
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
@@ -876,8 +879,27 @@ extension DatabasePool {
|
||||
|
||||
return try DatabaseSnapshot(
|
||||
path: path,
|
||||
configuration: writer.configuration,
|
||||
configuration: DatabasePool.readerConfiguration(writer.configuration),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "snapshot.\($databaseSnapshotCount.increment())")
|
||||
}
|
||||
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
///
|
||||
/// - 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 database access where a write
|
||||
/// transaction is open.
|
||||
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
|
||||
try unsafeReentrantRead { db in
|
||||
try DatabaseSnapshotPool(db)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -35,7 +35,7 @@ import UIKit
|
||||
///
|
||||
/// ### Creating a DatabaseQueue
|
||||
///
|
||||
/// - ``init(configuration:)``
|
||||
/// - ``init(named:configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
@@ -83,6 +83,10 @@ public final class DatabaseQueue {
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
// DatabaseQueue can't perform parallel reads
|
||||
var configuration = configuration
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
@@ -101,13 +105,41 @@ public final class DatabaseQueue {
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
///
|
||||
/// The database memory is released when the database queue
|
||||
/// gets deallocated.
|
||||
/// To create an independent in-memory database, don't pass any name. The
|
||||
/// database memory is released when the database queue is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An independent in-memory database
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// ```
|
||||
///
|
||||
/// When you need to open several connections to the same in-memory
|
||||
/// database, give it a name:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A shared in-memory database
|
||||
/// let dbQueue = try DatabaseQueue(named: "myDatabase")
|
||||
/// ```
|
||||
///
|
||||
/// In this case, the database is automatically deleted and memory is
|
||||
/// reclaimed when the last connection to the database of the given
|
||||
/// name closes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/inmemorydb.html>
|
||||
///
|
||||
/// - parameter name: When nil, an independent in-memory database opens.
|
||||
/// Otherwise, the shared in-memory database of the given name opens.
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) throws {
|
||||
public init(named name: String? = nil, configuration: Configuration = Configuration()) throws {
|
||||
let path: String
|
||||
if let name {
|
||||
path = "file:\(name)?mode=memory&cache=shared"
|
||||
} else {
|
||||
path = ":memory:"
|
||||
}
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: ":memory:",
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
@@ -5,9 +5,8 @@ import Dispatch
|
||||
|
||||
/// A type that reads from an SQLite database.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the
|
||||
/// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are
|
||||
/// valid conforming types.
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the built-in
|
||||
/// conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// conforming types in a multithreaded application. See <doc:Concurrency> for
|
||||
@@ -206,7 +205,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -224,8 +225,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -241,7 +242,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -256,8 +259,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -273,10 +276,16 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// This method can be called from other database access methods. Reentrant
|
||||
/// database accesses are discouraged, though, because they muddle
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access (read or write),
|
||||
/// the `Database` argument to `value` is the same as the current
|
||||
/// database access.
|
||||
///
|
||||
/// Reentrant database accesses are discouraged because they muddle
|
||||
/// transaction boundaries
|
||||
/// (see <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information).
|
||||
@@ -293,8 +302,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -453,7 +462,9 @@ extension DatabaseReader {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -467,8 +478,8 @@ extension DatabaseReader {
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -675,3 +686,58 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that sees an unchanging database content.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the
|
||||
/// built-in conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with the same features and guarantees as
|
||||
/// ``DatabaseReader``. On top of them, a `DatabaseSnapshotReader` always sees
|
||||
/// the same state of the database.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``reentrantRead(_:)``
|
||||
public protocol DatabaseSnapshotReader: DatabaseReader { }
|
||||
|
||||
extension DatabaseSnapshotReader {
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access, the `Database`
|
||||
/// argument to `value` is the same as the current database access.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let count = try snapshot.reentrantRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
// Reentrant reads are safe in a snapshot
|
||||
try unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try read(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -344,8 +344,37 @@ private struct TableRegion: Equatable {
|
||||
|
||||
/// A type that operates on a specific ``DatabaseRegion``.
|
||||
///
|
||||
/// A `DatabaseRegionConvertible` instance feeds database observation tools such
|
||||
/// as ``DatabaseRegionObservation`` and ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation triggered by all changes to the database
|
||||
/// DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Table("player"))
|
||||
///
|
||||
/// // An observation triggered by all changes to the row
|
||||
/// // with rowid 1 in the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Player.filter(id: 1))
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'score' column
|
||||
/// // of the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player"))
|
||||
/// ```
|
||||
///
|
||||
/// Specifying a region from a ``FetchRequest`` does not execute the request.
|
||||
/// In the above example, `Player.filter(id: 1)` and `SELECT score FROM player`
|
||||
/// are only compiled by SQLite, so that GRDB can understand the tables, rows,
|
||||
/// and columns that constitute the database region.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseRegion
|
||||
///
|
||||
/// - ``fullDatabase``
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
|
||||
@@ -6,19 +6,95 @@ import Foundation
|
||||
/// `DatabaseRegionObservation` tracks transactions that modify a
|
||||
/// database region.
|
||||
///
|
||||
/// For example:
|
||||
/// ## Overview
|
||||
///
|
||||
/// Tracked changes are 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).
|
||||
///
|
||||
/// Changes to internal system tables (such as `sqlite_master`) and changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are
|
||||
/// not notified.
|
||||
///
|
||||
/// `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`.
|
||||
///
|
||||
/// ## DatabaseRegionObservation Usage
|
||||
///
|
||||
/// Create a `DatabaseRegionObservation` with one or several requests to track:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Track the player table
|
||||
/// // Tracks the full player table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
/// ```
|
||||
///
|
||||
/// Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// // Handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Enjoy the changes notifications:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// }
|
||||
/// // Prints "Players were changed"
|
||||
/// ```
|
||||
///
|
||||
/// You stop the observation by calling the ``DatabaseCancellable/cancel()``
|
||||
/// method on the object returned by the `start` method. Cancellation is
|
||||
/// automatic when the cancellable is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// cancellable.cancel()
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseRegionObservation` can also be turned into a Combine publisher, or
|
||||
/// an RxSwift observable (see the companion library
|
||||
/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
/// // Handle completion
|
||||
/// } receiveValue: { (db: Database) in
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can feed `DatabaseRegionObservation` with any type that conforms to
|
||||
/// the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``,
|
||||
/// ``DatabaseRegion``, ``Table``, etc. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observe the score column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Player.select(Column("score")))
|
||||
///
|
||||
/// // Observe the 'score' column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: SQLRequest("SELECT score FROM player"))
|
||||
///
|
||||
/// // Observe both the 'player' and 'team' tables
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Table("player"), Table("team"))
|
||||
///
|
||||
/// // Observe the full database
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: .fullDatabase)
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseRegionObservation
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
import Dispatch
|
||||
|
||||
/// A database connection that sees an unchanging database content, as it
|
||||
/// existed at the moment it was created.
|
||||
/// A database connection that serializes accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseSnapshot` creates one single SQLite connection. All database
|
||||
/// A `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// A snapshot creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial **reader dispatch queue**. The SQLite
|
||||
/// connection is closed when the `DatabaseSnapshot` is deallocated.
|
||||
///
|
||||
/// `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// lifetime, and yet it doesn't prevent database updates. This "magic" is made
|
||||
/// possible by SQLite's WAL mode. See
|
||||
/// [Isolation In SQLite](https://sqlite.org/isolation.html) for
|
||||
/// more information.
|
||||
/// A snapshot created on a [WAL](https://sqlite.org/wal.html) database doesn't
|
||||
/// prevent database modifications performed by other connections (but it won't
|
||||
/// see them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html)
|
||||
/// for more information.
|
||||
///
|
||||
/// On non-WAL databases, a snapshot prevents all database modifications as long
|
||||
/// as it exists, because of the
|
||||
/// [SHARED lock](https://www.sqlite.org/lockingv3.html) it holds.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, with
|
||||
/// ``DatabasePool/makeSnapshot()``. The number of snapshots is unlimited,
|
||||
/// regardless of the ``Configuration/maximumReaderCount`` configuration:
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``,
|
||||
/// with ``DatabasePool/makeSnapshot()``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
@@ -29,8 +35,8 @@ import Dispatch
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot,
|
||||
/// create the snapshot from within a write access, outside of any transaction.
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
@@ -46,7 +52,7 @@ import Dispatch
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// return dbPool.makeSnapshot()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// // <- Other threads may have created some players here
|
||||
@@ -61,78 +67,103 @@ import Dispatch
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
public final class DatabaseSnapshot {
|
||||
private let serializedDatabase: SerializedDatabase
|
||||
private let reader: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
serializedDatabase.configuration
|
||||
reader.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snapshot keeps a long-lived transaction
|
||||
/// The path to the database file.
|
||||
public var path: String {
|
||||
reader.path
|
||||
}
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration,
|
||||
defaultLabel: String = "GRDB.DatabaseSnapshot",
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
{
|
||||
let configuration = Self.configure(configuration)
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
try reader.sync { db in
|
||||
// Open transaction
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
reader.reentrantSync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshot can't perform parallel reads.
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
// DatabaseSnapshot is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshot uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshot keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseSnapshot: DatabaseReader {
|
||||
extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try serializedDatabase.sync { try $0.close() }
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
serializedDatabase.interrupt()
|
||||
reader.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(block)
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try serializedDatabase.reentrantSync(value)
|
||||
try reader.reentrantSync(value)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only
|
||||
/// SQLite connections. All read accesses are executed in **reader dispatch
|
||||
/// queues** (one per read-only SQLite connection). SQLite connections are
|
||||
/// closed when the `DatabasePool` is deallocated.
|
||||
///
|
||||
/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is
|
||||
/// required for creating a `DatabaseSnapshotPool`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create a `DatabaseSnapshotPool` from a
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html) database, such as databases
|
||||
/// created from a ``DatabasePool``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.makeSnapshotPool()
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from a database connection, outside of a write transaction. You can
|
||||
/// for example take snapshots from a ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation of the 'player' table
|
||||
/// // that notifies fresh database snapshots:
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // Don't fetch players now, and return a snapshot instead.
|
||||
/// // Register an access to the player table so that the
|
||||
/// // observation tracks changes to this table.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// return try DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Start observing the 'player' table
|
||||
/// let cancellable = try observation.start(in: dbPool) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (snapshot: DatabaseSnapshotPool) in
|
||||
/// // Handle a fresh snapshot
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_open.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshotPool
|
||||
///
|
||||
/// See also ``DatabasePool/makeSnapshotPool()``.
|
||||
///
|
||||
/// - ``init(_:configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
public final class DatabaseSnapshotPool {
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The path to the database file.
|
||||
public let path: String
|
||||
|
||||
/// The pool of reader connections.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
private var readerPool: Pool<SerializedDatabase>?
|
||||
|
||||
/// The WAL snapshot
|
||||
private let walSnapshot: WALSnapshot
|
||||
|
||||
/// A connection that prevents checkpoints and keeps the WAL snapshot valid.
|
||||
/// It is never used.
|
||||
private let snapshotHolder: DatabaseQueue
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // Create the snapshot after all players have been deleted.
|
||||
/// return DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
/// // The snapshot is guaranteed to see an empty table of players, though:
|
||||
/// let count = try snapshot.read(Player.fetchCount)
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
/// 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>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter configuration: A configuration. If nil, the configuration of
|
||||
/// `db` is used.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(_ db: Database, configuration: Configuration? = nil) throws {
|
||||
var configuration = Self.configure(configuration ?? db.configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = db.path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: db.path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// 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>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshotPool needs a non-empty pool of connections.
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// DatabaseSnapshotPool is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshotPool uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshotPool keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
// DatabaseSnapshotPool requires the WAL mode.
|
||||
// See <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
if configuration.readonlyBusyMode == nil {
|
||||
configuration.readonlyBusyMode = .timeout(10)
|
||||
}
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseSnapshotPool: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try readerPool?.barrier {
|
||||
defer { readerPool = nil }
|
||||
|
||||
try readerPool?.forEach { reader in
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func interrupt() {
|
||||
readerPool?.forEach { $0.interrupt() }
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
var completion: PoolCompletion!
|
||||
defer {
|
||||
releaseReader(completion)
|
||||
}
|
||||
return try reader.sync { db in
|
||||
do {
|
||||
let value = try value(db)
|
||||
completion = poolCompletion(db)
|
||||
return value
|
||||
} catch {
|
||||
completion = poolCompletion(db)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
releaseReader(self.poolCompletion(db))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync { db in
|
||||
let result = try value(db)
|
||||
if snapshotIsLost(db) {
|
||||
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
} else {
|
||||
/// There is no unsafe access to a snapshot.
|
||||
return try read(value)
|
||||
}
|
||||
}
|
||||
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
private func poolCompletion(_ db: Database) -> PoolCompletion {
|
||||
snapshotIsLost(db) ? .discard : .reuse
|
||||
}
|
||||
|
||||
private func snapshotIsLost(_ db: Database) -> Bool {
|
||||
do {
|
||||
let currentSnapshot = try WALSnapshot(db)
|
||||
if currentSnapshot.compare(walSnapshot) == 0 {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -5,8 +5,8 @@ import Dispatch
|
||||
|
||||
/// A type that writes into an SQLite database.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseWriter`. Only the
|
||||
/// ``DatabaseQueue`` and ``DatabasePool`` types are valid conforming types.
|
||||
/// Do not declare new conformances to `DatabaseWriter`. Only the built-in
|
||||
/// conforming types are valid.
|
||||
///
|
||||
/// A database writer creates one single SQLite connection dedicated to database
|
||||
/// updates. All updates are executed in a serial **writer dispatch queue**.
|
||||
@@ -42,15 +42,15 @@ import Dispatch
|
||||
/// - ``spawnConcurrentRead(_:)``
|
||||
/// - ``DatabaseFuture``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeReentrantWrite(_:)``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeReentrantWrite(_:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``erase()-w5n7``
|
||||
@@ -94,7 +94,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@@ -133,7 +134,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@@ -173,7 +175,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
@@ -206,7 +209,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
@@ -215,10 +219,9 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method can be called from other database access methods. Reentrant
|
||||
/// database accesses are discouraged, though, because they muddle
|
||||
/// transaction boundaries.
|
||||
/// (see <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information).
|
||||
/// database accesses are discouraged because they muddle transaction
|
||||
/// boundaries. See <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// A class that serializes accesses to a database.
|
||||
/// A class that serializes accesses to an SQLite connection.
|
||||
final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
|
||||
@@ -42,19 +42,42 @@ extension Database {
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completes.
|
||||
///
|
||||
/// For example:
|
||||
/// This method helps synchronizing the database with other resources,
|
||||
/// such as files, or system services.
|
||||
///
|
||||
/// In the example below, a `CLLocationManager` starts monitoring a
|
||||
/// `CLRegion` if and only if it has successfully been stored in
|
||||
/// the database:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// db.afterNextTransaction { _ in
|
||||
/// print("success")
|
||||
/// /// Inserts a region in the database, and start monitoring upon
|
||||
/// /// successful insertion.
|
||||
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
|
||||
/// // Make sure database is inside a transaction
|
||||
/// try db.inSavepoint {
|
||||
///
|
||||
/// // Save the region in the database
|
||||
/// try insert(...)
|
||||
///
|
||||
/// // Start monitoring if and only if the insertion is
|
||||
/// // eventually committed to disk
|
||||
/// db.afterNextTransaction { _ in
|
||||
/// // locationManager prefers the main queue:
|
||||
/// DispatchQueue.main.async {
|
||||
/// locationManager.startMonitoring(for: region)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ...
|
||||
/// } // prints "success"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Closure are executed in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
/// The method above won't trigger the location manager if the transaction
|
||||
/// is eventually rollbacked (explicitly, or because of an error).
|
||||
///
|
||||
/// The `onCommit` and `onRollback` closures are executed in the writer
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
///
|
||||
/// - precondition: Database connection is not read-only.
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
@@ -716,36 +739,305 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
/// A type that tracks all database changes and transactions performed in
|
||||
/// A type that tracks database changes and transactions performed in
|
||||
/// a database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// `TransactionObserver` is the low-level protocol that supports all
|
||||
/// <doc:DatabaseObservation> features.
|
||||
///
|
||||
/// A transaction observer is notified of individual changes (inserts, updates
|
||||
/// and deletes), before they are committed to disk, as well as transaction
|
||||
/// commits and rollbacks.
|
||||
///
|
||||
/// ## Activate a Transaction Observer
|
||||
///
|
||||
/// An observer starts receiving change notifications after it has been added to
|
||||
/// a database connection with the
|
||||
/// ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method,
|
||||
/// or the ``Database/add(transactionObserver:extent:)`` `Database` method.
|
||||
/// or the ``Database/add(transactionObserver:extent:)`` `Database` method:
|
||||
///
|
||||
/// All observer methods are called in the writer dispatch queue, serialized
|
||||
/// with all database updates (see ``DatabaseWriter``).
|
||||
/// ```swift
|
||||
/// let observer = MyObserver()
|
||||
/// dbQueue.add(transactionObserver: observer)
|
||||
/// ```
|
||||
///
|
||||
/// Some changes and transactions are not notified:
|
||||
/// By default, database holds weak references to its transaction observers:
|
||||
/// they are not retained, and stop getting notifications after they are
|
||||
/// deallocated. See <doc:TransactionObserver#Observation-Extent> for
|
||||
/// more options.
|
||||
///
|
||||
/// - Transactions performed in read-only database connections.
|
||||
/// - Changes and transactions performed by other database connections.
|
||||
/// - 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).
|
||||
/// ## Database Changes And Transactions
|
||||
///
|
||||
/// Database changes are notified to the ``databaseDidChange(with:)`` callback.
|
||||
/// This includes indirect changes triggered by `ON DELETE` and `ON UPDATE`
|
||||
/// actions associated to
|
||||
/// [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and
|
||||
/// [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
///
|
||||
/// Transaction completions are notified to the ``databaseWillCommit()-7mksu``,
|
||||
/// ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
///
|
||||
/// Read-only transactions, changes and transactions performed by external
|
||||
/// database connections, changes to internal system tables (such as
|
||||
/// `sqlite_master`), changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and 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) are
|
||||
/// not notified.
|
||||
///
|
||||
/// 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:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// } // 3. willCommit, 4. didCommit
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// return .rollback // 3. didRollback
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// throw SomeError()
|
||||
/// } // 2. didRollback
|
||||
/// ```
|
||||
///
|
||||
/// Database statements that are executed outside of any explicit transaction
|
||||
/// do not drop off the radar:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
/// try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Changes that are on hold because of a
|
||||
/// [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified
|
||||
/// after the savepoint has been released. This makes sure that notified events
|
||||
/// are only those that have an opportunity to be committed:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT foo")
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT bar")
|
||||
/// try db.execute(sql: "UPDATE ...") // not notified
|
||||
/// try db.execute(sql: "ROLLBACK TO SAVEPOINT bar")
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT bar")
|
||||
///
|
||||
/// return .commit // 4. willCommit, 5. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Eventual errors thrown from `databaseWillCommit` are exposed to the
|
||||
/// application code:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// ...
|
||||
/// return .commit // 1. willCommit (throws), 2. didRollback
|
||||
/// }
|
||||
/// } catch {
|
||||
/// // 3. The error thrown by the transaction observer.
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Note: All callbacks are called in the writer dispatch queue, and
|
||||
/// serialized with all database updates.
|
||||
///
|
||||
/// - 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
|
||||
///
|
||||
/// **Transaction observers can choose the database changes they are
|
||||
/// interested in.**
|
||||
///
|
||||
/// The filtering happens in the ``observes(eventsOfKind:)`` method, which tells
|
||||
/// whether the observer wants notifications of specific kinds of changes,
|
||||
/// or not.
|
||||
///
|
||||
/// The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can
|
||||
/// distinguish insertions from deletions and updates, and is also able to
|
||||
/// tell the columns that are about to be changed.
|
||||
///
|
||||
/// For example, an observer can focus on the changes that happen on the
|
||||
/// "player" database table only:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// // Only observe changes to the "player" table.
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// // This method is only called for changes that happen to
|
||||
/// // the "player" table.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the `observes(eventsOfKind:)` method returns false for all event kinds,
|
||||
/// the observer is still notified of transactions.
|
||||
///
|
||||
/// ## Observation Extent
|
||||
///
|
||||
/// **You can specify how long an observer is notified of database changes
|
||||
/// and transactions.**
|
||||
///
|
||||
/// The `remove(transactionObserver:)` method explicitly stops notifications,
|
||||
/// at any time:
|
||||
///
|
||||
/// ```swift
|
||||
/// // From a database queue or pool:
|
||||
/// dbQueue.remove(transactionObserver: observer)
|
||||
///
|
||||
/// // From a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.remove(transactionObserver: observer)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Alternatively, use the `extent` parameter of the
|
||||
/// `add(transactionObserver:extent:)` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observer = MyObserver()
|
||||
///
|
||||
/// // On a database queue or pool:
|
||||
/// dbQueue.add(transactionObserver: observer) // default extent
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
///
|
||||
/// // On a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.add(transactionObserver: ...)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - The default extent is `.observerLifetime`: the database holds a weak
|
||||
/// reference to the observer, and the observation automatically ends when the
|
||||
/// observer is deallocated. Meanwhile, the observer is notified of all changes
|
||||
/// and transactions.
|
||||
///
|
||||
/// - `.nextTransaction` activates the observer until the current or next
|
||||
/// transaction completes. The database keeps a strong reference to the observer
|
||||
/// until its `databaseDidCommit` or `databaseDidRollback` callback is called.
|
||||
/// Hereafter the observer won't get any further notification.
|
||||
///
|
||||
/// - `.databaseLifetime` has the database retain and notify the observer until
|
||||
/// the database connection is closed.
|
||||
///
|
||||
/// Finally, an observer can avoid processing database changes until the end
|
||||
/// of the current transaction. After
|
||||
/// ``stopObservingDatabaseChangesUntilNextTransaction()``, the
|
||||
/// `databaseDidChange` callback will not be called until the current
|
||||
/// transaction completes:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playerTableWasModified = false
|
||||
///
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### 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:
|
||||
///
|
||||
/// ```swift
|
||||
/// protocol TransactionObserver: AnyObject {
|
||||
/// #if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// /// Notifies before a database change (insert, update, or delete)
|
||||
/// /// with change information (initial / final values for the row's
|
||||
/// /// columns).
|
||||
/// ///
|
||||
/// /// The event is only valid for the duration of this method call. If you
|
||||
/// /// need to keep it longer, store a copy: event.copy().
|
||||
/// func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
/// #endif
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This extra API can be activated in two ways:
|
||||
///
|
||||
/// 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below.
|
||||
/// It uses the system SQLite, which is compiled with
|
||||
/// `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't
|
||||
/// know the minimum version of macOS, tvOS, watchOS):
|
||||
///
|
||||
/// ```ruby
|
||||
/// pod 'GRDB.swift'
|
||||
/// platform :ios, '11.0' # or above
|
||||
///
|
||||
/// post_install do |installer|
|
||||
/// installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
/// target.build_configurations.each do |config|
|
||||
/// # Enable extra GRDB APIs
|
||||
/// config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK"
|
||||
/// # Enable extra SQLite APIs
|
||||
/// config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
|
||||
/// end
|
||||
/// end
|
||||
/// end
|
||||
/// ```
|
||||
///
|
||||
/// **Warning**: make sure you use the right platform version! You will get
|
||||
/// runtime errors on devices with a lower version.
|
||||
///
|
||||
/// **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in
|
||||
/// `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that
|
||||
/// are lacking from the system `<sqlite3.h>` header. When Xcode eventually
|
||||
/// ships with an SDK that includes a complete header, you may get a
|
||||
/// compiler error about duplicate function definitions. When this happens,
|
||||
/// just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Handling Database Changes
|
||||
/// ### Filtering Database Changes
|
||||
///
|
||||
/// - ``observes(eventsOfKind:)``
|
||||
/// - ``DatabaseEventKind``
|
||||
///
|
||||
/// ### Handling Database Changes
|
||||
///
|
||||
/// - ``databaseDidChange(with:)``
|
||||
/// - ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
/// - ``DatabaseEvent``
|
||||
/// - ``DatabaseEventKind``
|
||||
///
|
||||
/// ### Handling Transactions
|
||||
///
|
||||
@@ -770,6 +1062,11 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When this method returns true for deletion events, the observer
|
||||
/// prevents the
|
||||
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
|
||||
/// from being applied.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
|
||||
+42
-28
@@ -19,40 +19,44 @@
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot {
|
||||
// Xcode 14 RC ships with a macOS SDK that misses snapshot support.
|
||||
// TODO: when Xcode ships with a macOS SDK that exposes snapshots, replace
|
||||
// the `os(macOS) || targetEnvironment(macCatalyst)` check with a compiler
|
||||
// version check.
|
||||
//
|
||||
// We can't enable snapshots for SQLCipher, since we don't know if they
|
||||
// are enabled.
|
||||
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
init?(_ db: Database) {
|
||||
return nil
|
||||
}
|
||||
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
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#else
|
||||
private let snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
/// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an
|
||||
/// error occurs.
|
||||
init?(_ db: Database) {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
init(_ db: Database) throws {
|
||||
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK, let snapshot else {
|
||||
return nil
|
||||
guard code == SQLITE_OK else {
|
||||
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is in autocommit mode.
|
||||
""")
|
||||
}
|
||||
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
|
||||
journalMode != "wal"
|
||||
{
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is not in WAL mode.
|
||||
""")
|
||||
}
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
self.snapshot = snapshot
|
||||
guard let sqliteSnapshot else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
self.sqliteSnapshot = sqliteSnapshot
|
||||
}
|
||||
|
||||
deinit {
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
sqlite3_snapshot_free(sqliteSnapshot)
|
||||
}
|
||||
|
||||
/// Compares two WAL snapshots.
|
||||
@@ -61,7 +65,17 @@ final class WALSnapshot {
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
}
|
||||
#endif // os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
#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
|
||||
}
|
||||
@@ -43,13 +43,11 @@ try dbQueue.write { db in
|
||||
try dbQueue.read { db
|
||||
// Inside a transaction
|
||||
}
|
||||
|
||||
let observation = ValueObservation.tracking { db
|
||||
// Inside a transaction
|
||||
}
|
||||
```
|
||||
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task.
|
||||
Alternatively, you can open an explicit transaction or savepoint with ``Database/inTransaction(_:_:)`` and ``Database/inSavepoint(_:)``.
|
||||
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> section below.
|
||||
|
||||
- *Practical advice* - Take the time to identify the invariants of your database. Some of them can be enforced in the database schema itself, such as "all books must have a non-empty title", or "all books must have an author" (see <doc:DatabaseSchema>). Some invariants can only be enforced by transactions, such as "all account credits must have a matching debit", or "all authors must have at least one book".
|
||||
|
||||
@@ -339,8 +337,9 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei
|
||||
|
||||
### Database Connections with Concurrency Guarantees
|
||||
|
||||
- ``DatabaseReader``
|
||||
- ``DatabaseWriter``
|
||||
- ``DatabaseReader``
|
||||
- ``DatabaseSnapshotReader``
|
||||
|
||||
### Advanced Concurrency
|
||||
|
||||
|
||||
@@ -28,11 +28,12 @@ The differences are:
|
||||
|
||||
- ``Configuration``
|
||||
|
||||
### Opening Database Connections
|
||||
### Database Connections
|
||||
|
||||
- ``DatabaseQueue``
|
||||
- ``DatabasePool``
|
||||
- ``DatabaseSnapshot``
|
||||
- ``DatabaseSnapshotPool``
|
||||
|
||||
### Using Database Connections
|
||||
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
Observe database changes and transactions.
|
||||
|
||||
## Overview
|
||||
|
||||
**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.**
|
||||
|
||||
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
|
||||
|
||||
- ``ValueObservation``: Get notified when database values change.
|
||||
- ``DatabaseRegionObservation``: Get notified when a transaction impacts a database region.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transactions commits or rollbacks, one by one.
|
||||
- ``TransactionObserver``: The low-level protocol that supports all database observation features.
|
||||
|
||||
## Topics
|
||||
|
||||
### Observing Database Values
|
||||
|
||||
@@ -1,33 +1,372 @@
|
||||
# The Database Schema
|
||||
|
||||
Learn how to define the database schema.
|
||||
|
||||
## Overview
|
||||
|
||||
SQLite directly supports a [set of schema alterations](https://www.sqlite.org/lang.html). Many of them are available as Swift methods such as ``Database/create(table:options:body:)``, ``Database/alter(table:body:)``, listed below.
|
||||
**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.
|
||||
|
||||
You can directly create tables when you open a database, as below:
|
||||
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player", options: .ifNotExists) { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
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 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.
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
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.
|
||||
|
||||
### Table names should be English, singular, and camelCased
|
||||
|
||||
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "players") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required because table name is not 'player'
|
||||
static let databaseTableName = "players"
|
||||
}
|
||||
|
||||
extension PostalAddress: TableRecord {
|
||||
// Required because table name is not 'postalAddress'
|
||||
static let databaseTableName = "postal_address"
|
||||
}
|
||||
|
||||
extension Award: TableRecord {
|
||||
// Required because table name is not 'award'
|
||||
static let databaseTableName = "Auszeichnung"
|
||||
}
|
||||
```
|
||||
|
||||
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Explicit association key because the table name is not 'postalAddress'
|
||||
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
|
||||
|
||||
// Explicit association key because the table name is not 'award'
|
||||
static let awards = hasMany(Award.self, key: "awards")
|
||||
}
|
||||
```
|
||||
|
||||
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
|
||||
|
||||
### Column names should be camelCased
|
||||
|
||||
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("fullName", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creationDate", .datetime).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("full_name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creation_date", .datetime).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
struct Player: Decodable, FetchableRecord {
|
||||
var id: Int64
|
||||
var fullName: String
|
||||
var score: Int
|
||||
var creationDate: Date
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, fullName = "full_name", score, creationDate = "creation_date"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
But you should prefer wrapping your schema changes in <doc:Migrations> when you plan to upgrade the database schema in future versions of your app.
|
||||
### Tables should have explicit primary keys
|
||||
|
||||
> Tip: When modifying the database schema, prefer Swift APIs over raw SQL queries. This helps the compiler check if features are available on the SQLite version that ships on the target operating system. For example:
|
||||
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// Auto-incremented primary key
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
// Single-column primary key
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
// Composite primary key
|
||||
t.primaryKey {
|
||||
t.column("playerId", .integer).references("player")
|
||||
t.column("teamId", .text).references("team")
|
||||
}
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .text).notNull().unique()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
t.column("playerId", .integer).notNull()
|
||||
t.column("teamId", .text).notNull()
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
|
||||
|
||||
See <doc:SingleRowTables> when you need to define a table that contains a single row.
|
||||
|
||||
> Important: Add not null constraints on primary key columns, as in the above recommended examples, or SQLite will allow null values. See <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls> for more information.
|
||||
|
||||
☝️ **If the database table does not define any explicit primary key**, the record type for this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html):
|
||||
|
||||
```swift
|
||||
// A table without any explicit primary key
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
var name: String
|
||||
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.
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
AllColumns(),
|
||||
Column.rowID]
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowid = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
// SELECT *, rowid FROM player WHERE rowid = 1
|
||||
let player = try Player.fetchOne(db, id: 1)
|
||||
}
|
||||
```
|
||||
|
||||
### Single-column primary keys should be named 'id'
|
||||
|
||||
This helps record types play well with the standard `Identifiable` protocol.
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("uuid", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
|
||||
|
||||
```swift
|
||||
// Custom coding keys
|
||||
struct Player: Codable, Identifiable {
|
||||
var id: String
|
||||
var name: String
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "uuid", name
|
||||
}
|
||||
}
|
||||
|
||||
// Extra property
|
||||
struct Player: Identifiable {
|
||||
var uuid: String
|
||||
var name: String
|
||||
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: String { uuid }
|
||||
}
|
||||
```
|
||||
|
||||
### Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
// 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(
|
||||
index: "playerTeamPosition",
|
||||
on: "player", columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
|
||||
>
|
||||
> - Dropping a table column requires SQLite 3.35+ (iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0).
|
||||
> - [Strict tables](https://www.sqlite.org/stricttables.html) require SQLite 3.37+ (iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5).
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
|
||||
>
|
||||
> When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
> ```swift
|
||||
> // Unique constraint on player(name) can not be dropped.
|
||||
> try db.create(table: "player") { t in
|
||||
> t.column("name", .text).unique()
|
||||
> }
|
||||
>
|
||||
> // Unique index on team(name) can be dropped.
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> 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.
|
||||
|
||||
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal error: table player has no unique index on columns ...
|
||||
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
|
||||
try Player.deleteOne(db, key: ["name": "Arthur"])
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
### Relations between tables should be supported by foreign keys
|
||||
|
||||
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
|
||||
|
||||
```swift
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("color", .text).notNull()
|
||||
}
|
||||
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// A player must refer to an existing team
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// No foreign key
|
||||
t.column("teamId", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
extension Player: TableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
}
|
||||
```
|
||||
|
||||
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
|
||||
|
||||
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let teamForeignKey = ForeignKey(["teamId"])
|
||||
static let team = belongsTo(Team.self,
|
||||
using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let players = hasMany(Player.self,
|
||||
using: Player.teamForeignKey)
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -62,6 +401,7 @@ But you should prefer wrapping your schema changes in <doc:Migrations> when you
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
- ``Database/primaryKey(_:)``
|
||||
- ``Database/schemaVersion()``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
- ``Database/tableExists(_:)``
|
||||
- ``Database/triggerExists(_:)``
|
||||
@@ -78,3 +418,10 @@ But you should prefer wrapping your schema changes in <doc:Migrations> when you
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
|
||||
|
||||
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
@@ -4,8 +4,15 @@ A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
## Overview
|
||||
|
||||
GRDB 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.
|
||||
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
|
||||
|
||||
@@ -21,11 +28,11 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti
|
||||
- <doc:Migrations>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Record Types and the Query Interface
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
|
||||
### Database Observation
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Record Types and the Query Interface
|
||||
# Records and the Query Interface
|
||||
|
||||
Record types and the query interface build SQL queries for you
|
||||
Record types and the query interface build SQL queries for you.
|
||||
|
||||
## Topics
|
||||
|
||||
|
||||
@@ -28,10 +28,8 @@ Those two cases can create a nagging question for the application. By default, i
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer)
|
||||
// Have inserts replace the existing row
|
||||
.primaryKey(onConflict: .replace)
|
||||
// Single row guarantee: have inserts replace the existing row
|
||||
t.primaryKey("id", .integer, onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
@@ -48,7 +46,7 @@ When you use <doc:Migrations>, you may wonder if it is a good idea or not to per
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
@@ -74,7 +72,7 @@ The recommended migration creates the table, nothing more:
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
@@ -175,7 +173,7 @@ We all love to copy and paste, don't we? Just customize the template code below:
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// The single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
|
||||
+3
-2
@@ -159,10 +159,11 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
|
||||
@available(*, unavailable, renamed: "Statement")
|
||||
public typealias UpdateStatement = Statement
|
||||
|
||||
extension ValueObservation<ValueReducers.Auto> {
|
||||
extension ValueObservation {
|
||||
@available(*, unavailable, renamed: "tracking(_:)")
|
||||
public static func trackingVaryingRegion<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(table: "country") { t in
|
||||
/// t.column("code", .text).primaryKey() // (1)
|
||||
/// t.primaryKey("code", .text) // (1)
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
/// try db.create(table: "demographics") { t in
|
||||
|
||||
@@ -498,7 +498,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter key: A unique key.
|
||||
/// - parameter key: A key dictionary.
|
||||
public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self {
|
||||
guard let key else {
|
||||
return none()
|
||||
@@ -526,7 +526,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter keys: A collection of unique keys
|
||||
/// - parameter keys: An array of key dictionaries.
|
||||
public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self {
|
||||
if keys.isEmpty {
|
||||
return none()
|
||||
|
||||
@@ -538,7 +538,7 @@ extension Table {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter key: A unique key.
|
||||
/// - parameter key: A key dictionary.
|
||||
public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest<RowDecoder> {
|
||||
all().filter(key: key)
|
||||
}
|
||||
@@ -566,7 +566,7 @@ extension Table {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter keys: A collection of unique keys
|
||||
/// - parameter keys: An array of key dictionaries.
|
||||
public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest<RowDecoder> {
|
||||
all().filter(keys: keys)
|
||||
}
|
||||
@@ -1611,7 +1611,7 @@ extension Table {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A unique key.
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: Whether a row exists for this key.
|
||||
public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
|
||||
try !filter(key: key).isEmpty(db)
|
||||
@@ -1842,7 +1842,7 @@ extension Table {
|
||||
/// key columns.
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: Whether a row was deleted.
|
||||
@discardableResult
|
||||
public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
|
||||
|
||||
@@ -21,7 +21,8 @@ extension Database {
|
||||
/// - <https://www.sqlite.org/lang_createtable.html>
|
||||
/// - <https://www.sqlite.org/withoutrowid.html>
|
||||
///
|
||||
/// - warning: This method is sunsetted. You should prefer
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(table:options:body:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -51,21 +52,207 @@ extension Database {
|
||||
|
||||
/// Creates a database table.
|
||||
///
|
||||
/// For example:
|
||||
/// ### Reference documentation
|
||||
///
|
||||
/// SQLite has many reference documents about table creation. They are a
|
||||
/// great learning material:
|
||||
///
|
||||
/// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html)
|
||||
/// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html)
|
||||
/// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)
|
||||
/// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html)
|
||||
/// - [Rowid Tables](https://www.sqlite.org/rowidtable.html)
|
||||
/// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html)
|
||||
/// - [STRICT Tables](https://www.sqlite.org/stricttables.html)
|
||||
///
|
||||
/// ### Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE place (
|
||||
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// // title TEXT,
|
||||
/// // isFavorite BOOLEAN NOT NULL DEFAULT 0,
|
||||
/// // latitude DOUBLE NOT NULL,
|
||||
/// // longitude DOUBLE NOT NULL
|
||||
/// // )
|
||||
/// try db.create(table: "place") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("title", .text)
|
||||
/// t.column("favorite", .boolean).notNull().default(false)
|
||||
/// t.column("isFavorite", .boolean).notNull().default(false)
|
||||
/// t.column("longitude", .double).notNull()
|
||||
/// t.column("latitude", .double).notNull()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/lang_createtable.html>
|
||||
/// - <https://www.sqlite.org/withoutrowid.html>
|
||||
/// ### Configure table creation
|
||||
///
|
||||
/// Use the `options` parameter to configure table creation
|
||||
/// (see ``TableOptions``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player ( ... )
|
||||
/// try db.create(table: "player") { t in ... }
|
||||
///
|
||||
/// // CREATE TEMPORARY TABLE player IF NOT EXISTS (
|
||||
/// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
|
||||
/// ```
|
||||
///
|
||||
/// ### Add columns
|
||||
///
|
||||
/// Add columns with their name and eventual type (`text`, `integer`,
|
||||
/// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`
|
||||
/// and `any`) - see ``Database/ColumnType``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE example (
|
||||
/// // a,
|
||||
/// // name TEXT,
|
||||
/// // creationDate DATETIME,
|
||||
/// try db.create(table: "example") { t in
|
||||
/// t.column("a")
|
||||
/// t.column("name", .text)
|
||||
/// t.column("creationDate", .datetime)
|
||||
/// ```
|
||||
///
|
||||
/// The `column()` method returns a ``ColumnDefinition`` that you can
|
||||
/// further configure:
|
||||
///
|
||||
/// ### Not null constraints, default values
|
||||
///
|
||||
/// ```swift
|
||||
/// // email TEXT NOT NULL,
|
||||
/// t.column("email", .text).notNull()
|
||||
///
|
||||
/// // name TEXT DEFAULT 'O''Reilly',
|
||||
/// t.column("name", .text).defaults(to: "O'Reilly")
|
||||
///
|
||||
/// // flag BOOLEAN NOT NULL DEFAULT 0,
|
||||
/// t.column("flag", .boolean).notNull().defaults(to: false)
|
||||
///
|
||||
/// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
/// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP")
|
||||
/// ```
|
||||
///
|
||||
/// ### Primary, unique, and foreign keys
|
||||
///
|
||||
/// Use an individual column as **primary**, **unique**, or **foreign key**.
|
||||
/// When defining a foreign key, the referenced column is the primary key of
|
||||
/// the referenced table (unless you specify otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
///
|
||||
/// // uuid TEXT NOT NULL PRIMARY KEY,
|
||||
/// t.primaryKey("uuid", .text)
|
||||
///
|
||||
/// // email TEXT UNIQUE,
|
||||
/// t.column("email", .text)
|
||||
/// .unique()
|
||||
///
|
||||
/// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
|
||||
/// t.column("countryCode", .text)
|
||||
/// .references("country", onDelete: .cascade)
|
||||
/// ```
|
||||
///
|
||||
/// Primary, unique and foreign keys can also be added on several columns:
|
||||
///
|
||||
/// ```swift
|
||||
/// // a INTEGER NOT NULL,
|
||||
/// // b TEXT NOT NULL,
|
||||
/// // PRIMARY KEY (a, b),
|
||||
/// t.primaryKey {
|
||||
/// t.column("a", .integer)
|
||||
/// t.column("b", .text)
|
||||
/// }
|
||||
///
|
||||
/// // a INTEGER,
|
||||
/// // b TEXT,
|
||||
/// // UNIQUE (a, b) ON CONFLICT REPLACE,
|
||||
/// t.column("a", .integer)
|
||||
/// t.column("b", .text)
|
||||
/// t.uniqueKey(["a", "b"], onConflict: .replace)
|
||||
///
|
||||
/// // a INTEGER,
|
||||
/// // b TEXT,
|
||||
/// // FOREIGN KEY (a, b) REFERENCES parents(c, d),
|
||||
/// t.column("a", .integer)
|
||||
/// t.column("b", .text)
|
||||
/// t.foreignKey(["a", "b"], references: "parents")
|
||||
/// ```
|
||||
///
|
||||
/// > Tip: when you need an integer primary key that automatically generates
|
||||
/// unique values, it is recommended that you use the
|
||||
/// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > try db.create(table: "example") { t in
|
||||
/// > t.autoIncrementedPrimaryKey("id")
|
||||
/// > ...
|
||||
/// > }
|
||||
/// > ```
|
||||
/// >
|
||||
/// > The reason for this recommendation is that auto-incremented primary
|
||||
/// > keys forbid the reuse of ids. This prevents your app or
|
||||
/// > <doc:DatabaseObservation> to think that a row was updated, when it was
|
||||
/// > actually deleted and replaced. Depending on your application needs,
|
||||
/// > this may be acceptable. But usually it is not.
|
||||
///
|
||||
/// ### Indexed columns
|
||||
///
|
||||
/// ```swift
|
||||
/// t.column("score", .integer).indexed()
|
||||
/// ```
|
||||
///
|
||||
/// For extra index options, see ``create(index:on:columns:options:condition:)``.
|
||||
///
|
||||
/// ### Integrity checks
|
||||
///
|
||||
/// SQLite will only let conforming rows in:
|
||||
///
|
||||
/// ```swift
|
||||
/// // name TEXT CHECK (LENGTH(name) > 0)
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
///
|
||||
/// // score INTEGER CHECK (score > 0)
|
||||
/// t.column("score", .integer).check(sql: "score > 0")
|
||||
///
|
||||
/// // CHECK (a + b < 10),
|
||||
/// t.check(Column("a") + Column("b") < 10)
|
||||
///
|
||||
/// // CHECK (a + b < 10)
|
||||
/// t.check(sql: "a + b < 10")
|
||||
/// ```
|
||||
///
|
||||
/// ### Generated columns
|
||||
///
|
||||
/// [Generated columns](https://sqlite.org/gencol.html) are available with a
|
||||
/// [custom SQLite build](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md):
|
||||
///
|
||||
/// ```swift
|
||||
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
|
||||
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
|
||||
/// ```
|
||||
///
|
||||
/// ### Raw SQL columns and constraints
|
||||
///
|
||||
/// Columns and constraints can be defined with raw sql:
|
||||
///
|
||||
/// ```swift
|
||||
/// t.column(sql: "name TEXT")
|
||||
/// t.constraint(sql: "CHECK (a + b < 10)")
|
||||
/// ```
|
||||
///
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// ```swift
|
||||
/// let defaultName = "O'Reilly"
|
||||
/// t.column(literal: "name TEXT DEFAULT \(defaultName)")
|
||||
///
|
||||
/// let forbiddenName = "admin"
|
||||
/// t.constraint(literal: "CHECK (name <> \(forbiddenName))")
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
@@ -146,7 +333,8 @@ extension Database {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
|
||||
///
|
||||
/// - warning: This method is sunsetted. You should prefer
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(index:on:columns:options:condition:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -252,7 +440,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// Table creation options
|
||||
/// Table creation options.
|
||||
public struct TableOptions: OptionSet {
|
||||
public let rawValue: Int
|
||||
|
||||
@@ -264,18 +452,16 @@ public struct TableOptions: OptionSet {
|
||||
/// Creates a temporary table.
|
||||
public static let temporary = TableOptions(rawValue: 1 << 1)
|
||||
|
||||
/// Creates a without rowid table. See <https://www.sqlite.org/withoutrowid.html>
|
||||
/// Creates a [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) table.
|
||||
///
|
||||
/// Such tables can not be tracked with <doc:DatabaseObservation> tools.
|
||||
public static let withoutRowID = TableOptions(rawValue: 1 << 2)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a STRICT table
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/stricttables.html>
|
||||
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
|
||||
public static let strict = TableOptions(rawValue: 1 << 3)
|
||||
#else
|
||||
/// Creates a STRICT table
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/stricttables.html>
|
||||
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
|
||||
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
|
||||
public static let strict = TableOptions(rawValue: 1 << 3)
|
||||
#endif
|
||||
@@ -302,11 +488,18 @@ public struct TableOptions: OptionSet {
|
||||
/// - ``column(sql:)``
|
||||
/// - ``ColumnDefinition``
|
||||
///
|
||||
/// ### Define Keys
|
||||
/// ### Define the Primary Key
|
||||
///
|
||||
/// - ``autoIncrementedPrimaryKey(_:onConflict:)``
|
||||
/// - ``primaryKey(_:_:onConflict:)``
|
||||
/// - ``primaryKey(onConflict:body:)``
|
||||
///
|
||||
/// ### Define a Foreign Key
|
||||
///
|
||||
/// - ``foreignKey(_:references:columns:onDelete:onUpdate:deferred:)``
|
||||
/// - ``primaryKey(_:onConflict:)``
|
||||
///
|
||||
/// ### Define a Unique Key
|
||||
///
|
||||
/// - ``uniqueKey(_:onConflict:)``
|
||||
///
|
||||
/// ### Define Others Constraints
|
||||
@@ -316,11 +509,17 @@ public struct TableOptions: OptionSet {
|
||||
/// - ``constraint(literal:)``
|
||||
/// - ``constraint(sql:)``
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
|
||||
/// ### Sunsetted Methods
|
||||
///
|
||||
/// Those are legacy interfaces that are preserved for backwards compatibility.
|
||||
/// Their use is not recommended.
|
||||
///
|
||||
/// - ``primaryKey(_:onConflict:)``
|
||||
public final class TableDefinition {
|
||||
private typealias KeyConstraint = (
|
||||
columns: [String],
|
||||
conflictResolution: Database.ConflictResolution?)
|
||||
struct KeyConstraint {
|
||||
var columns: [String]
|
||||
var conflictResolution: Database.ConflictResolution?
|
||||
}
|
||||
|
||||
private struct ForeignKeyConstraint {
|
||||
var columns: [String]
|
||||
@@ -356,6 +555,7 @@ public final class TableDefinition {
|
||||
private let name: String
|
||||
private let options: TableOptions
|
||||
private var columns: [ColumnItem] = []
|
||||
private var inPrimaryKeyBody = false
|
||||
private var primaryKeyConstraint: KeyConstraint?
|
||||
private var uniqueKeyConstraints: [KeyConstraint] = []
|
||||
private var foreignKeyConstraints: [ForeignKeyConstraint] = []
|
||||
@@ -401,6 +601,79 @@ public final class TableDefinition {
|
||||
column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true)
|
||||
}
|
||||
|
||||
/// Defines the primary key on a single column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE country (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // )
|
||||
/// try db.create(table: "country") { t in
|
||||
/// t.primaryKey("isoCode", .text)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
/// - returns: A ``ColumnDefinition`` that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func primaryKey(
|
||||
_ name: String,
|
||||
_ type: Database.ColumnType,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil)
|
||||
-> ColumnDefinition
|
||||
{
|
||||
let pk = column(name, type).primaryKey(onConflict: conflictResolution)
|
||||
if type == .integer {
|
||||
// INTEGER PRIMARY KEY is always NOT NULL
|
||||
return pk
|
||||
} else {
|
||||
// Add a not null constraint in order to fix an SQLite bug:
|
||||
// <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
|
||||
return pk.notNull()
|
||||
}
|
||||
}
|
||||
|
||||
/// Defines the primary key on multiple columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE passport (
|
||||
/// // citizenId INTEGER NOT NULL,
|
||||
/// // countryCode TEXT NOT NULL,
|
||||
/// // issueDate DATE NOT NULL,
|
||||
/// // PRIMARY KEY (citizenId, countryCode)
|
||||
/// // )
|
||||
/// try db.create(table: "passport") { t in
|
||||
/// t.primaryKey {
|
||||
/// t.column("citizenId", .integer)
|
||||
/// t.column("countryCode", .text)
|
||||
/// }
|
||||
/// t.column("issueDate", .date).notNull()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A NOT NULL constraint is always added to the primary key columns.
|
||||
public func primaryKey(
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
body: () throws -> Void)
|
||||
rethrows
|
||||
{
|
||||
guard primaryKeyConstraint == nil else {
|
||||
// Programmer error
|
||||
fatalError("can't define several primary keys")
|
||||
}
|
||||
primaryKeyConstraint = KeyConstraint(columns: [], conflictResolution: conflictResolution)
|
||||
|
||||
let oldValue = inPrimaryKeyBody
|
||||
inPrimaryKeyBody = true
|
||||
defer { inPrimaryKeyBody = oldValue }
|
||||
try body()
|
||||
}
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// For example:
|
||||
@@ -418,12 +691,20 @@ public final class TableDefinition {
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the eventual column type.
|
||||
/// - returns: An ``ColumnDefinition`` that allows you to refine the
|
||||
/// - returns: A ``ColumnDefinition`` that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
columns.append(.definition(column))
|
||||
|
||||
if inPrimaryKeyBody {
|
||||
// Add a not null constraint in order to fix an SQLite bug:
|
||||
// <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
|
||||
column.notNull()
|
||||
primaryKeyConstraint!.columns.append(name)
|
||||
}
|
||||
|
||||
return column
|
||||
}
|
||||
|
||||
@@ -440,6 +721,7 @@ public final class TableDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
public func column(sql: String) {
|
||||
GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL")
|
||||
columns.append(.literal(SQL(sql: sql)))
|
||||
}
|
||||
|
||||
@@ -458,6 +740,7 @@ public final class TableDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
public func column(literal: SQL) {
|
||||
GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL")
|
||||
columns.append(.literal(literal))
|
||||
}
|
||||
|
||||
@@ -467,20 +750,25 @@ public final class TableDefinition {
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE citizenship (
|
||||
/// // citizenID INTEGER NOT NULL,
|
||||
/// // citizenId INTEGER NOT NULL,
|
||||
/// // countryCode TEXT NOT NULL,
|
||||
/// // PRIMARY KEY (citizenID, countryCode)
|
||||
/// // PRIMARY KEY (citizenId, countryCode)
|
||||
/// // )
|
||||
/// try db.create(table: "citizenship") { t in
|
||||
/// t.column("citizenID", .integer).notNull()
|
||||
/// t.column("citizenId", .integer).notNull()
|
||||
/// t.column("countryCode", .text).notNull()
|
||||
/// t.primaryKey(["citizenID", "countryCode"])
|
||||
/// t.primaryKey(["citizenId", "countryCode"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/lang_createtable.html#primkeyconst>
|
||||
/// - <https://www.sqlite.org/lang_createtable.html#rowid>
|
||||
/// - important: Make sure you add not null constraints on your primary key
|
||||
/// columns, as in the above example, or SQLite will allow null values.
|
||||
/// See <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
|
||||
/// for more information.
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``TableDefinition/primaryKey(onConflict:body:)`` instead.
|
||||
///
|
||||
/// - parameter columns: The primary key columns.
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
@@ -490,7 +778,7 @@ public final class TableDefinition {
|
||||
// Programmer error
|
||||
fatalError("can't define several primary keys")
|
||||
}
|
||||
primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution)
|
||||
primaryKeyConstraint = KeyConstraint(columns: columns, conflictResolution: conflictResolution)
|
||||
}
|
||||
|
||||
/// Adds a unique constraint.
|
||||
@@ -510,13 +798,25 @@ public final class TableDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When defining a unique constraint on a single column, you can use the
|
||||
/// ``ColumnDefinition/unique(onConflict:)`` shortcut:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // email TEXT UNIQUE
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("email", .text).unique()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#uniqueconst>
|
||||
///
|
||||
/// - parameter columns: The unique key columns.
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) {
|
||||
uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution))
|
||||
uniqueKeyConstraints.append(KeyConstraint(columns: columns, conflictResolution: conflictResolution))
|
||||
}
|
||||
|
||||
/// Adds a foreign key.
|
||||
@@ -526,17 +826,27 @@ public final class TableDefinition {
|
||||
/// ```swift
|
||||
/// // CREATE TABLE passport (
|
||||
/// // issueDate DATE NOT NULL,
|
||||
/// // citizenID INTEGER NOT NULL,
|
||||
/// // citizenId INTEGER NOT NULL,
|
||||
/// // countryCode INTEGER NOT NULL,
|
||||
/// // FOREIGN KEY (citizenID, countryCode)
|
||||
/// // REFERENCES citizenship(citizenID, countryCode)
|
||||
/// // FOREIGN KEY (citizenId, countryCode)
|
||||
/// // REFERENCES citizenship(citizenId, countryCode)
|
||||
/// // ON DELETE CASCADE
|
||||
/// // )
|
||||
/// try db.create(table: "passport") { t in
|
||||
/// t.column("issueDate", .date).notNull()
|
||||
/// t.column("citizenID", .integer).notNull()
|
||||
/// t.column("citizenId", .integer).notNull()
|
||||
/// t.column("countryCode", .text).notNull()
|
||||
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade)
|
||||
/// t.foreignKey(["citizenId", "countryCode"], references: "citizenship", onDelete: .cascade)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When defining a foreign key on a single column, you can use the
|
||||
/// ``ColumnDefinition/references(_:column:onDelete:onUpdate:deferred:)``
|
||||
/// shortcut:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("teamId", .integer).references("team", onDelete: .cascade)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -588,6 +898,18 @@ public final class TableDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When defining a check constraint on a single column, you can use the
|
||||
/// ``ColumnDefinition/check(_:)`` shortcut:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // name TEXT CHECK (LENGTH(name) > 0)
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter condition: The checked condition.
|
||||
@@ -612,6 +934,18 @@ public final class TableDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When defining a check constraint on a single column, you can use the
|
||||
/// ``ColumnDefinition/check(sql:)`` shortcut:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // name TEXT CHECK (LENGTH(name) > 0)
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter sql: An SQL snippet
|
||||
@@ -642,8 +976,8 @@ public final class TableDefinition {
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// // CREATE TABLE player (
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player (
|
||||
/// // score INTEGER,
|
||||
/// // CHECK (score >= 0)
|
||||
/// // )
|
||||
@@ -673,8 +1007,8 @@ public final class TableDefinition {
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
if let primaryKeyConstraint {
|
||||
primaryKeyColumns = primaryKeyConstraint.columns
|
||||
} else if let column = columns.lazy.compactMap(\.columnDefinition).first(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [column.name]
|
||||
} else {
|
||||
@@ -693,22 +1027,22 @@ public final class TableDefinition {
|
||||
try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns)
|
||||
})
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
if let constraint = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
|
||||
if let conflictResolution = constraint.conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
for constraint in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
|
||||
if let conflictResolution = constraint.conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
@@ -1043,9 +1377,8 @@ public final class TableAlteration {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Keys
|
||||
/// ### Foreign Keys
|
||||
///
|
||||
/// - ``primaryKey(onConflict:autoincrement:)``
|
||||
/// - ``references(_:column:onDelete:onUpdate:deferred:)``
|
||||
///
|
||||
/// ### Indexes
|
||||
@@ -1068,6 +1401,13 @@ public final class TableAlteration {
|
||||
/// - ``check(_:)``
|
||||
/// - ``check(sql:)``
|
||||
/// - ``notNull(onConflict:)``
|
||||
///
|
||||
/// ### Sunsetted Methods
|
||||
///
|
||||
/// Those are legacy interfaces that are preserved for backwards compatibility.
|
||||
/// Their use is not recommended.
|
||||
///
|
||||
/// - ``primaryKey(onConflict:autoincrement:)``
|
||||
public final class ColumnDefinition {
|
||||
enum Index {
|
||||
case none
|
||||
@@ -1122,21 +1462,19 @@ public final class ColumnDefinition {
|
||||
/// // id TEXT NOT NULL PRIMARY KEY
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("id", .text).notNull().primaryKey()
|
||||
/// t.primaryKey("id", .text)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Make sure you add a not null constraint on your primary key
|
||||
/// - important: Make sure you add a not null constraint on your primary key
|
||||
/// column, as in the above example, or SQLite will allow null values.
|
||||
/// See <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
|
||||
/// for more information.
|
||||
///
|
||||
/// When you want to define a primary key on multiple columns, do not use
|
||||
/// this method. Use ``TableDefinition/primaryKey(_:onConflict:)`` instead.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/lang_createtable.html#primkeyconst>
|
||||
/// - <https://www.sqlite.org/lang_createtable.html#rowid>
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``TableDefinition/primaryKey(_:_:onConflict:)``
|
||||
/// instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - conflictResolution: An optional ``Database/ConflictResolution``.
|
||||
@@ -1603,7 +1941,7 @@ public final class ColumnDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
/// Table creation options
|
||||
/// Index creation options
|
||||
public struct IndexOptions: OptionSet {
|
||||
public let rawValue: Int
|
||||
|
||||
|
||||
@@ -374,7 +374,7 @@ extension TableRecord {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter key: A unique key.
|
||||
/// - parameter key: A key dictionary.
|
||||
public static func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest<Self> {
|
||||
all().filter(key: key)
|
||||
}
|
||||
@@ -402,7 +402,7 @@ extension TableRecord {
|
||||
/// When executed, this request raises a fatal error if no unique index
|
||||
/// exists on a subset of the key columns.
|
||||
///
|
||||
/// - parameter keys: A collection of unique keys
|
||||
/// - parameter keys: An array of key dictionaries.
|
||||
public static func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest<Self> {
|
||||
all().filter(keys: keys)
|
||||
}
|
||||
|
||||
@@ -266,7 +266,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let player = try Player.fetchOne(db, id: 123)
|
||||
/// let country = try Country.fetchOne(db, key: "FR")
|
||||
/// let country = try Country.fetchOne(db, id: "FR")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -421,7 +421,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
|
||||
|
||||
@@ -362,7 +362,7 @@ extension TableRecord {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A unique key.
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: Whether a record exists for this key.
|
||||
public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
|
||||
try !filter(key: key).isEmpty(db)
|
||||
@@ -552,7 +552,7 @@ extension TableRecord {
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Deletes the record identified by its primary or unique keys, and returns
|
||||
/// Deletes the record identified by its primary or unique key, and returns
|
||||
/// whether a record was deleted.
|
||||
///
|
||||
/// For example:
|
||||
@@ -580,7 +580,7 @@ extension TableRecord {
|
||||
/// key columns.
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: Whether a record was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
|
||||
|
||||
@@ -66,3 +66,5 @@ extension LockedBox where T: Numeric {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LockedBox: @unchecked Sendable where T: Sendable { }
|
||||
+25
-10
@@ -75,7 +75,7 @@ final class Pool<T> {
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client must call release(), only once, after the element has been used.
|
||||
func get() throws -> (element: T, release: () -> Void) {
|
||||
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
|
||||
try barrierQueue.sync {
|
||||
itemsSemaphore.wait()
|
||||
itemsGroup.enter()
|
||||
@@ -91,7 +91,7 @@ final class Pool<T> {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return (element: item.element, release: { self.release(item) })
|
||||
return (element: item.element, release: { self.release(item, completion: $0) })
|
||||
} catch {
|
||||
itemsSemaphore.signal()
|
||||
itemsGroup.leave()
|
||||
@@ -107,7 +107,7 @@ final class Pool<T> {
|
||||
///
|
||||
/// - important: The `execute` argument is executed in a serial dispatch
|
||||
/// queue, so make sure you use the element asynchronously.
|
||||
func asyncGet(_ execute: @escaping (Result<(element: T, release: () -> Void), Error>) -> Void) {
|
||||
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
|
||||
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
// > We wait on the semaphore in the serial queue, which means that
|
||||
// > we’ll have at most one blocked thread when we reach maximum
|
||||
@@ -122,16 +122,24 @@ final class Pool<T> {
|
||||
/// Performs a synchronous block with an element. The element turns
|
||||
/// available after the block has executed.
|
||||
func get<U>(block: (T) throws -> U) throws -> U {
|
||||
let (element, release) = try get()
|
||||
defer { release() }
|
||||
let (element, completion) = try get()
|
||||
defer { completion(.reuse) }
|
||||
return try block(element)
|
||||
}
|
||||
|
||||
private func release(_ item: Item) {
|
||||
$items.update { _ in
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
// release it without having to find in it the items array.
|
||||
item.isAvailable = true
|
||||
private func release(_ item: Item, completion: PoolCompletion) {
|
||||
$items.update { items in
|
||||
switch completion {
|
||||
case .reuse:
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
// release it without having to find in it the items array.
|
||||
item.isAvailable = true
|
||||
case .discard:
|
||||
// Discard should be rare: perform lookup.
|
||||
if let index = items.firstIndex(where: { $0 === item }) {
|
||||
items.remove(at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
itemsSemaphore.signal()
|
||||
itemsGroup.leave()
|
||||
@@ -171,3 +179,10 @@ final class Pool<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum PoolCompletion {
|
||||
// Reuse the element
|
||||
case reuse
|
||||
// Discard the element
|
||||
case discard
|
||||
}
|
||||
+15
-23
@@ -250,16 +250,6 @@ extension ValueConcurrentObserver {
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT)
|
||||
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
@@ -271,11 +261,9 @@ extension ValueConcurrentObserver {
|
||||
//
|
||||
// Fetch value & tracked region in a synchronous way.
|
||||
//
|
||||
// TODO: we currently perform the initial read from a snapshot, because
|
||||
// We perform the initial read from a DatabaseSnapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions. The problem is that
|
||||
// we do not control the number of created shapshots: we should instead
|
||||
// use a reader from the pool.
|
||||
// write access, and compare the database versions.
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read {
|
||||
db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in
|
||||
@@ -286,12 +274,12 @@ extension ValueConcurrentObserver {
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion, WALSnapshot(db))
|
||||
return (fetchedValue, initialRegion, try? WALSnapshot(db))
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db)
|
||||
return (fetchedValue, initialRegion, WALSnapshot(db))
|
||||
return (fetchedValue, initialRegion, try? WALSnapshot(db))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,11 +310,9 @@ extension ValueConcurrentObserver {
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// TODO: we currently perform the initial read from a snapshot, because
|
||||
// We perform the initial read from a DatabaseSnapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions. The problem is that
|
||||
// we do not control the number of created shapshots: we should instead
|
||||
// use a reader from the pool.
|
||||
// write access, and compare the database versions.
|
||||
do {
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
initialSnapshot.asyncRead { dbResult in
|
||||
@@ -377,7 +363,7 @@ extension ValueConcurrentObserver {
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialWALSnapshot: WALSnapshot(db),
|
||||
initialWALSnapshot: try? WALSnapshot(db),
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
@@ -403,13 +389,13 @@ extension ValueConcurrentObserver {
|
||||
|
||||
// Transaction is needed for comparing version snapshots
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// Keep initialSnapshot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps WAL snapshots (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let isModified = withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialWALSnapshot,
|
||||
let currentWALSnapshot = WALSnapshot(writerDB)
|
||||
let currentWALSnapshot = try? WALSnapshot(writerDB)
|
||||
else {
|
||||
return true
|
||||
}
|
||||
@@ -477,6 +463,12 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
File renamed without changes.
File renamed without changes.
+15
-1
@@ -2,6 +2,20 @@ extension ValueObservation {
|
||||
/// Transforms all values from the upstream observation with a
|
||||
/// provided closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Turn an observation of Player? into an observation of UIImage?
|
||||
/// let observation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchOne(db, id: 42) }
|
||||
/// .map { player in player?.image }
|
||||
/// ```
|
||||
///
|
||||
/// The `transform` closure does not run on the main thread, and does not
|
||||
/// block any database access This makes the `map` operator a tool that
|
||||
/// helps reducing database contention
|
||||
/// (see <doc:ValueObservation#ValueObservation-Performance>).
|
||||
///
|
||||
/// - parameter transform: A closure that takes one value as its parameter
|
||||
/// and returns a new value.
|
||||
public func map<T>(_ transform: @escaping (Reducer.Value) throws -> T)
|
||||
@@ -32,7 +46,7 @@ extension ValueReducers {
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueReducers.Map: _DatabaseValueReducer where Base: _DatabaseValueReducer {
|
||||
extension ValueReducers.Map: ValueReducer where Base: ValueReducer {
|
||||
public func _fetch(_ db: Database) throws -> Base.Fetched {
|
||||
try base._fetch(db)
|
||||
}
|
||||
+42
-1
@@ -14,6 +14,47 @@ extension ValueObservation {
|
||||
|
||||
extension ValueObservation where Reducer.Value: Equatable {
|
||||
/// Notifies only values that don’t match the previously observed value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation of distinct Player?
|
||||
/// let observation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchOne(db, id: 42) }
|
||||
/// .removeDuplicates()
|
||||
/// ```
|
||||
///
|
||||
/// > Tip: When the observed value does not adopt `Equatable`, and it is
|
||||
/// > impractical to provide a custom comparison function, you can observe
|
||||
/// > distinct raw database values such as ``Row`` or ``DatabaseValue``,
|
||||
/// > before converting them to the desired type. For example, the previous
|
||||
/// > observation can be rewritten as below:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > // An observation of distinct `Player?`
|
||||
/// > let request = Player.filter(id: 42)
|
||||
/// > let observation = ValueObservation
|
||||
/// > .tracking { db in try Row.fetchOne(db, request) }
|
||||
/// > .removeDuplicates()
|
||||
/// > .map { row in try row.map(Player.init(row:)) }
|
||||
/// > ```
|
||||
/// >
|
||||
/// > This technique is also available for requests that
|
||||
/// > involve associations:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > struct TeamInfo: Decodable, FetchableRecord {
|
||||
/// > var team: Team
|
||||
/// > var players: [Player]
|
||||
/// > }
|
||||
/// >
|
||||
/// > // An observation of distinct `[TeamInfo]`
|
||||
/// > let request = Team.including(all: Team.players)
|
||||
/// > let observation = ValueObservation
|
||||
/// > .tracking { db in try Row.fetchAll(db, request) }
|
||||
/// > .removeDuplicates() // Row adopts Equatable
|
||||
/// > .map { rows in try rows.map(TeamInfo.init(row:)) }
|
||||
/// > ```
|
||||
public func removeDuplicates()
|
||||
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
|
||||
{
|
||||
@@ -50,7 +91,7 @@ extension ValueReducers {
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueReducers.RemoveDuplicates: _DatabaseValueReducer where Base: _DatabaseValueReducer {
|
||||
extension ValueReducers.RemoveDuplicates: ValueReducer where Base: ValueReducer {
|
||||
public func _fetch(_ db: Database) throws -> Base.Fetched {
|
||||
try base._fetch(db)
|
||||
}
|
||||
+1
-1
@@ -20,7 +20,7 @@ extension ValueReducers {
|
||||
// swiftlint:enable line_length
|
||||
}
|
||||
|
||||
extension ValueReducers.Trace: _DatabaseValueReducer where Base: _DatabaseValueReducer {
|
||||
extension ValueReducers.Trace: ValueReducer where Base: ValueReducer {
|
||||
public func _fetch(_ db: Database) throws -> Base.Fetched {
|
||||
willFetch()
|
||||
return try base._fetch(db)
|
||||
+7
-22
@@ -21,15 +21,6 @@ public protocol _ValueReducer {
|
||||
mutating func _value(_ fetched: Fetched) throws -> Value?
|
||||
}
|
||||
|
||||
/// Implementation details of `ValueReducer`, able to observe from any database
|
||||
/// reader (``DatabaseQueue``, ``DatabasePool``).
|
||||
public protocol _DatabaseValueReducer: _ValueReducer {
|
||||
/// Fetches database values upon changes in an observed database region.
|
||||
///
|
||||
/// This method must does not depend on the state of the reducer.
|
||||
func _fetch(_ db: Database) throws -> Fetched
|
||||
}
|
||||
|
||||
/// `ValueReducer` supports ``ValueObservation``.
|
||||
///
|
||||
/// A `ValueReducer` fetches and transforms the database values
|
||||
@@ -40,18 +31,12 @@ public protocol _DatabaseValueReducer: _ValueReducer {
|
||||
/// ### Support
|
||||
///
|
||||
/// - ``ValueReducers``
|
||||
public typealias ValueReducer = _ValueReducer & _DatabaseValueReducer
|
||||
public protocol ValueReducer: _ValueReducer {
|
||||
/// Fetches database values upon changes in an observed database region.
|
||||
///
|
||||
/// This method must does not depend on the state of the reducer.
|
||||
func _fetch(_ db: Database) throws -> Fetched
|
||||
}
|
||||
|
||||
/// A namespace for concrete types that adopt the ``ValueReducer`` protocol.
|
||||
public enum ValueReducers {
|
||||
// ValueReducers.Auto allows us to define ValueObservation factory methods.
|
||||
//
|
||||
// For example, ValueObservation.tracking(_:) is, practically,
|
||||
// ValueObservation<ValueReducers.Auto>.tracking(_:).
|
||||
/// `Auto` supports ``ValueObservation`` factory methods.
|
||||
///
|
||||
/// Do not use this type.
|
||||
public enum Auto: _ValueReducer {
|
||||
public mutating func _value(_ fetched: Never) -> Never? { }
|
||||
}
|
||||
}
|
||||
public enum ValueReducers { }
|
||||
@@ -59,7 +59,29 @@ extension ValueObservation {
|
||||
/// A shared observation starts observing the database as soon as it is
|
||||
/// subscribed. You can choose if database observation should stop, or not,
|
||||
/// when its number of subscriptions drops down to zero, with the `extent`
|
||||
/// parameter.
|
||||
/// parameter:
|
||||
///
|
||||
/// ```swift
|
||||
/// // The default: stops observing the database when the number of
|
||||
/// // subscriptions drops down to zero, and restart database observation
|
||||
/// // on the next subscription.
|
||||
/// //
|
||||
/// // Database errors can be recovered by resubscribing to the
|
||||
/// // shared observation.
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue, extent: .whileObserved)
|
||||
///
|
||||
/// // Only stops observing the database when the shared observation
|
||||
/// // is deinitialized, and all subscriptions are cancelled.
|
||||
/// //
|
||||
/// // This extent prevents the shared observation from recovering
|
||||
/// // from database errors. To recover from database errors, create a new
|
||||
/// // shared SharedValueObservation instance.
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue, extent: .observationLifetime)
|
||||
/// ```
|
||||
///
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main dispatch queue. You can change this behavior by providing a
|
||||
@@ -68,7 +90,9 @@ extension ValueObservation {
|
||||
/// For example, the ``ValueObservationScheduler/immediate`` scheduler
|
||||
/// notifies all values on the main dispatch queue, and notifies the first
|
||||
/// one immediately when the
|
||||
/// ``SharedValueObservation/start(onError:onChange:)`` method is called:
|
||||
/// ``SharedValueObservation/start(onError:onChange:)`` method is called.
|
||||
/// The `immediate` scheduling requires that the observation starts from the
|
||||
/// main thread (a fatal error is raised otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
@@ -82,9 +106,9 @@ extension ValueObservation {
|
||||
/// let cancellable = try sharedObservation.start { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// // <- here "fresh players" is already printed.
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the observation is
|
||||
|
||||
@@ -7,21 +7,298 @@ import Foundation
|
||||
/// `ValueObservation` tracks changes in the results of database requests, and
|
||||
/// notifies fresh values whenever the database changes.
|
||||
///
|
||||
/// For example:
|
||||
/// ## Overview
|
||||
///
|
||||
/// Tracked changes are 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).
|
||||
///
|
||||
/// Changes to internal system tables (such as `sqlite_master`) and changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are
|
||||
/// not notified.
|
||||
///
|
||||
/// ## ValueObservation Usage
|
||||
///
|
||||
/// 1. Make sure that a unique database connection, ``DatabaseQueue`` or
|
||||
/// ``DatabasePool``, is kept open during the whole duration of
|
||||
/// the observation.
|
||||
///
|
||||
/// `ValueObservation` does not notify changes performed by
|
||||
/// external connections.
|
||||
/// See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation>
|
||||
/// for more information.
|
||||
///
|
||||
/// 2. Create a `ValueObservation` with a closure that fetches the
|
||||
/// observed value:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // Fetch and return the observed value
|
||||
/// }
|
||||
///
|
||||
/// // For example, an observation of [Player], which tracks all players:
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// // The same observation, using shorthand notation:
|
||||
/// let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
/// ```
|
||||
///
|
||||
/// There is no limit on the values that can be observed. An observation
|
||||
/// can perform multiple requests, from multiple database tables, and use
|
||||
/// raw SQL. See ``tracking(_:)`` for some examples.
|
||||
///
|
||||
/// 3. Start the observation in order to be notified of changes:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 4. Stop the observation by calling the ``DatabaseCancellable/cancel()``
|
||||
/// method on the object returned by the `start` method. Cancellation is
|
||||
/// automatic when the cancellable is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// cancellable.cancel()
|
||||
/// ```
|
||||
///
|
||||
/// `ValueObservation` can also be turned into an async sequence, a Combine
|
||||
/// publisher, or an RxSwift observable (see the companion library
|
||||
/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
///
|
||||
/// - Async sequence:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// for try await players in observation.values(in: dbQueue) {
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Combine Publisher:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
/// // Handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("Fresh players", players)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## ValueObservation Behavior
|
||||
///
|
||||
/// `ValueObservation` notifies an initial value before the eventual changes.
|
||||
///
|
||||
/// `ValueObservation` only notifies changes committed to disk.
|
||||
///
|
||||
/// By default, `ValueObservation` notifies a fresh value whenever any component
|
||||
/// of its fetched value is modified (any fetched column, row, etc.). This can
|
||||
/// be configured:
|
||||
/// see <doc:ValueObservation#Specifying-the-Tracked-Region>.
|
||||
///
|
||||
/// By default, `ValueObservation` notifies the initial value, as well as
|
||||
/// eventual changes and errors, on the main dispatch queue, asynchronously.
|
||||
/// This can be configured:
|
||||
/// see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
///
|
||||
/// `ValueObservation` may coalesce subsequent changes into a
|
||||
/// single notification.
|
||||
///
|
||||
/// `ValueObservation` may notify consecutive identical values. You can filter
|
||||
/// out the undesired duplicates with the ``removeDuplicates()`` method.
|
||||
///
|
||||
/// Starting an observation retains the database connection, until it is
|
||||
/// stopped. As long as the observation is active, the database connection
|
||||
/// won't be deallocated.
|
||||
///
|
||||
/// The database observation stops when the cancellable returned by the `start`
|
||||
/// method is cancelled or deallocated, or if an error occurs.
|
||||
///
|
||||
/// Take care that there are use cases that `ValueObservation` is unfit for.
|
||||
/// For example, an application may need to process absolutely all changes,
|
||||
/// and avoid any coalescing. An application may also need to process changes
|
||||
/// before any further modifications could be performed in the database file. In
|
||||
/// those cases, the application needs to track *individual transactions*, not
|
||||
/// values: use ``DatabaseRegionObservation``. If you need to process
|
||||
/// changes before they are committed to disk, use ``TransactionObserver``.
|
||||
///
|
||||
/// ## ValueObservation Scheduling
|
||||
///
|
||||
/// By default, `ValueObservation` notifies the initial value, as well as
|
||||
/// eventual changes and errors, on the main dispatch queue, asynchronously:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Track all players
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("Fresh players: \(players)")
|
||||
/// // The default scheduling
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // Called asynchronously on the main dispatch queue
|
||||
/// } onChange: { value in
|
||||
/// // Called asynchronously on the main dispatch queue
|
||||
/// print("Fresh value", value)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can change this behavior by adding a `scheduling` argument to the
|
||||
/// `start()` method.
|
||||
///
|
||||
/// For example, the ``ValueObservationScheduler/immediate`` scheduler
|
||||
/// notifies all values on the main dispatch queue, and notifies the first
|
||||
/// one immediately when the observation starts.
|
||||
///
|
||||
/// It is very useful in graphic applications, because you can configure views
|
||||
/// right away, without waiting for the initial value to be fetched eventually.
|
||||
/// You don't have to implement any empty or loading screen, or to prevent some
|
||||
/// undesired initial animation.
|
||||
///
|
||||
/// The `immediate` scheduling requires that the observation starts from the
|
||||
/// main dispatch queue (a fatal error is raised otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
/// // Called on the main dispatch queue
|
||||
/// } onChange: { value in
|
||||
/// // Called on the main dispatch queue
|
||||
/// print("Fresh value", value)
|
||||
/// }
|
||||
/// // <- Here "Fresh value" has already been printed.
|
||||
/// ```
|
||||
///
|
||||
/// The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)``
|
||||
/// asynchronously schedules values and errors on the dispatch queue of
|
||||
/// your choice.
|
||||
///
|
||||
/// ## ValueObservation Sharing
|
||||
///
|
||||
/// Sharing a `ValueObservation` spares database resources. When a database
|
||||
/// change happens, a fresh value is fetched only once, and then notified to
|
||||
/// all clients of the shared observation.
|
||||
///
|
||||
/// You build a shared observation with ``shared(in:scheduling:extent:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SharedValueObservation<[Player]>
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
/// ```
|
||||
///
|
||||
/// `ValueObservation` and `SharedValueObservation` are nearly identical, but
|
||||
/// the latter has no operator such as `map`. As a replacement, you may
|
||||
/// for example use Combine apis:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = try sharedObservation
|
||||
/// .publisher() // Turn shared observation into a Combine Publisher
|
||||
/// .map { ... } // The map operator from Combine
|
||||
/// .sink(...)
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
/// ## Specifying the Tracked Region
|
||||
///
|
||||
/// 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:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// // Define what database region constitutes a "change"
|
||||
/// region: Player.select(Column("score")).filter(id: 1),
|
||||
/// // Define what to fetch upon such change
|
||||
/// fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
/// )
|
||||
/// ```
|
||||
///
|
||||
/// This overload of `ValueObservation` lets you entirely separate the
|
||||
/// **observed region** from the **fetched value** itself, providing utmost
|
||||
/// flexibility. See ``DatabaseRegionConvertible`` for more information about
|
||||
/// the regions that can be tracked.
|
||||
///
|
||||
/// ## ValueObservation Performance
|
||||
///
|
||||
/// This section further describes runtime aspects of `ValueObservation`, and
|
||||
/// provides some optimization tips for demanding applications.
|
||||
///
|
||||
/// **`ValueObservation` is triggered by database transactions that may modify
|
||||
/// the tracked value.**
|
||||
///
|
||||
/// Precisely speaking, `ValueObservation` tracks changes in a
|
||||
/// ``DatabaseRegion``, not changes in values.
|
||||
///
|
||||
/// For example, if you track the maximum score of players, all transactions
|
||||
/// that impact the `score` column of the `player` database table (any update,
|
||||
/// insertion, or deletion) trigger the observation, even if the maximum score
|
||||
/// itself is not changed.
|
||||
///
|
||||
/// You can filter out undesired duplicate notifications with the
|
||||
/// ``removeDuplicates()`` method.
|
||||
///
|
||||
/// **ValueObservation can create database contention.** In other words, active
|
||||
/// observations take a toll on the constrained database resources. When
|
||||
/// triggered by impactful transactions, observations fetch fresh values, and
|
||||
/// can delay read and write database accesses of other application components.
|
||||
///
|
||||
/// When needed, you can help GRDB optimize observations and reduce
|
||||
/// database contention:
|
||||
///
|
||||
/// > Tip: Stop observations when possible.
|
||||
/// >
|
||||
/// > For example, if a `UIViewController` needs to display database values, it
|
||||
/// > can start the observation in `viewWillAppear`, and stop it in
|
||||
/// > `viewWillDisappear`.
|
||||
/// >
|
||||
/// > In a SwiftUI application, you can profit from the
|
||||
/// > [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its
|
||||
/// > [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation)
|
||||
/// > method.
|
||||
///
|
||||
/// > Tip: Share observations when possible.
|
||||
/// >
|
||||
/// > Each call to `ValueObservation.start` method triggers independent values
|
||||
/// > refreshes. When several components of your app are interested in the same
|
||||
/// > value, consider sharing the observation
|
||||
/// > with ``shared(in:scheduling:extent:)``.
|
||||
///
|
||||
/// > Tip: Use a ``DatabasePool``, because it can perform multi-threaded
|
||||
/// > database accesses.
|
||||
///
|
||||
/// > Tip: When the observation processes some raw fetched values, use the
|
||||
/// > ``map(_:)`` operator:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > // Plain observation
|
||||
/// > let observation = ValueObservation.tracking { db -> MyValue in
|
||||
/// > let players = try Player.fetchAll(db)
|
||||
/// > return computeMyValue(players)
|
||||
/// > }
|
||||
/// >
|
||||
/// > // Optimized observation
|
||||
/// > let observation = ValueObservation
|
||||
/// > .tracking { db try Player.fetchAll(db) }
|
||||
/// > .map { players in computeMyValue(players) }
|
||||
/// > ```
|
||||
/// >
|
||||
/// > The `map` operator helps reducing database contention because it performs
|
||||
/// > its job without blocking database accesses.
|
||||
///
|
||||
/// > 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.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a ValueObservation
|
||||
@@ -31,7 +308,7 @@ import Foundation
|
||||
/// - ``tracking(region:fetch:)``
|
||||
/// - ``tracking(regions:fetch:)``
|
||||
///
|
||||
/// ### Creating A Shared Observation
|
||||
/// ### Creating a Shared Observation
|
||||
///
|
||||
/// - ``shared(in:scheduling:extent:)``
|
||||
/// - ``SharedValueObservationExtent``
|
||||
@@ -69,11 +346,22 @@ public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
var events = ValueObservationEvents()
|
||||
|
||||
/// A boolean value indicating whether the observation requires write access
|
||||
/// when it fetch fresh values.
|
||||
/// when it fetches fresh values.
|
||||
///
|
||||
/// The default is false. Setting it to true can disable scheduling
|
||||
/// optimizations when the observation is started in
|
||||
/// a ``DatabasePool``.
|
||||
/// The `requiresWriteAccess` property is false by default. When true, a
|
||||
/// `ValueObservation` has a write access to the database, and its fetches
|
||||
/// are automatically wrapped in a savepoint:
|
||||
///
|
||||
/// ```swift
|
||||
/// var observation = ValueObservation.tracking { db in
|
||||
/// // write access allowed
|
||||
/// ...
|
||||
/// }
|
||||
/// observation.requiresWriteAccess = true
|
||||
/// ```
|
||||
///
|
||||
/// Setting the `requiresWriteAccess` flag can disable scheduling
|
||||
/// optimizations when the observation is started in a ``DatabasePool``.
|
||||
public var requiresWriteAccess = false
|
||||
|
||||
var trackingMode: ValueObservationTrackingMode
|
||||
@@ -155,7 +443,7 @@ extension ValueObservation: Refinable {
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -165,21 +453,19 @@ extension ValueObservation: Refinable {
|
||||
///
|
||||
/// For example, the ``ValueObservationScheduler/immediate`` scheduler
|
||||
/// notifies all values on the main dispatch queue, and notifies the first
|
||||
/// one immediately when the ``start(in:scheduling:onError:onChange:)``
|
||||
/// method is called:
|
||||
/// one immediately when the observation starts. The `immediate` scheduling
|
||||
/// requires that the observation starts from the main dispatch queue (a
|
||||
/// fatal error is raised otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = try observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// // <- here "fresh players" is already printed.
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the observation is
|
||||
/// subscribed from the main thread. It raises a fatal error otherwise.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationScheduler. By default, fresh
|
||||
/// values are dispatched asynchronously on the main queue.
|
||||
@@ -209,7 +495,7 @@ extension ValueObservation: Refinable {
|
||||
|
||||
/// Performs the specified closures when observation events occur.
|
||||
///
|
||||
/// All closures run on unspecified dispatch queues - don't make
|
||||
/// All closures run on unspecified dispatch queues: don't make
|
||||
/// any assumption.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -257,6 +543,30 @@ extension ValueObservation: Refinable {
|
||||
}
|
||||
|
||||
/// Prints log messages for all observation events.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = ValueObservation
|
||||
/// .tracking(Player.fetchCount)
|
||||
/// .print("Observe player count")
|
||||
/// .start(in: dbQueue, onError: { _ in }, onChange: { _ in })
|
||||
///
|
||||
/// // Prints:
|
||||
/// // Observe player count: start
|
||||
/// // Observe player count: fetch
|
||||
/// // Observe player count: tracked region: player(*)
|
||||
/// // Observe player count: value: 0
|
||||
/// // Observe player count: database did change
|
||||
/// // Observe player count: fetch
|
||||
/// // Observe player count: value: 1
|
||||
/// ```
|
||||
///
|
||||
/// - parameter prefix: A string —- which defaults to empty -— with which to
|
||||
/// prefix all log messages.
|
||||
/// - parameter stream: A stream for text output that receives messages, and
|
||||
/// which directs output to the console by default. A custom stream can be
|
||||
/// used to log messages to other destinations.
|
||||
public func print(
|
||||
_ prefix: String = "",
|
||||
to stream: TextOutputStream? = nil)
|
||||
@@ -432,7 +742,7 @@ extension ValueObservation {
|
||||
/// let cancellable = publisher.sink { completion in
|
||||
/// // handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -442,7 +752,9 @@ extension ValueObservation {
|
||||
///
|
||||
/// For example, the ``ValueObservationScheduler/immediate`` scheduler
|
||||
/// notifies all values on the main dispatch queue, and notifies the first
|
||||
/// one immediately when the publisher is subscribed:
|
||||
/// one immediately when the observation starts. The `immediate` scheduling
|
||||
/// requires that the observation starts from the main dispatch queue (a
|
||||
/// fatal error is raised otherwise):
|
||||
///
|
||||
/// ```swift
|
||||
/// let publisher = observation.publisher(in: dbQueue, scheduling: .immediate)
|
||||
@@ -450,14 +762,11 @@ extension ValueObservation {
|
||||
/// let cancellable = publisher.sink { completion in
|
||||
/// // handle completion
|
||||
/// } receiveValue: { (players: [Player]) in
|
||||
/// print("fresh players: \(players)")
|
||||
/// print("Fresh players: \(players)")
|
||||
/// }
|
||||
/// // <- here "fresh players" is already printed.
|
||||
/// // <- here "Fresh players" is already printed.
|
||||
/// ```
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the publisher is
|
||||
/// subscribed from the main thread. It raises a fatal error otherwise.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A ValueObservationScheduler. By default, fresh
|
||||
/// values are dispatched asynchronously on the main dispatch queue.
|
||||
@@ -616,7 +925,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
extension ValueObservation {
|
||||
|
||||
// MARK: - Creating ValueObservation
|
||||
|
||||
@@ -693,10 +1002,48 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can turn them into optimized observations of a constant region with
|
||||
/// the ``Database/registerAccess(to:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Player? in
|
||||
/// // Track all players so that the observed region does not depend on
|
||||
/// // the rowid of the favorite player.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// return try Player.fetchOne(db, id: pref.favoritePlayerId)
|
||||
/// }
|
||||
///
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> [User] in
|
||||
/// // Track all players so that the observed region does not change
|
||||
/// // even if there is no favorite player at all.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty
|
||||
/// return try Player.fetchAll(db, ids: playerIds)
|
||||
/// }
|
||||
///
|
||||
/// let observation = ValueObservation.trackingConstantRegion { db -> Int in
|
||||
/// // Track foods and beverages so that the observed region does not
|
||||
/// // depend on preferences.
|
||||
/// try db.registerAccess(to: Food.all())
|
||||
/// try db.registerAccess(to: Beverage.all())
|
||||
///
|
||||
/// let pref = try Preference.fetchOne(db) ?? .default
|
||||
/// switch pref.selection {
|
||||
/// case .food: return try Food.fetchCount(db)
|
||||
/// case .beverage: return try Beverage.fetchCount(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func trackingConstantRegion<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
.init(
|
||||
trackingMode: .constantRegionRecordedFromSelection,
|
||||
@@ -753,7 +1100,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
public static func tracking<Value>(
|
||||
region: any DatabaseRegionConvertible...,
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
tracking(regions: region, fetch: fetch)
|
||||
}
|
||||
@@ -808,7 +1156,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
public static func tracking<Value>(
|
||||
regions: [any DatabaseRegionConvertible],
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
.init(
|
||||
trackingMode: .constantRegion(regions),
|
||||
@@ -832,10 +1181,40 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// An observation can perform multiple requests, from multiple database
|
||||
/// tables, and even use raw SQL:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct HallOfFame {
|
||||
/// var totalPlayerCount: Int
|
||||
/// var bestPlayers: [Player]
|
||||
/// }
|
||||
///
|
||||
/// // An observation of HallOfFame
|
||||
/// let observation = ValueObservation.tracking { db -> HallOfFame in
|
||||
/// let totalPlayerCount = try Player.fetchCount(db)
|
||||
///
|
||||
/// let bestPlayers = try Player
|
||||
/// .order(Column("score").desc)
|
||||
/// .limit(10)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// return HallOfFame(
|
||||
/// totalPlayerCount: totalPlayerCount,
|
||||
/// bestPlayers: bestPlayers)
|
||||
/// }
|
||||
///
|
||||
/// // An observation of the maximum score
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
.init(
|
||||
trackingMode: .nonConstantRegionRecordedFromSelection,
|
||||
|
||||
@@ -92,7 +92,6 @@
|
||||
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
@@ -172,6 +171,8 @@
|
||||
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */; };
|
||||
566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */; };
|
||||
566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; };
|
||||
566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; };
|
||||
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
@@ -190,7 +191,6 @@
|
||||
5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; };
|
||||
5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; };
|
||||
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; };
|
||||
@@ -199,6 +199,8 @@
|
||||
56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
|
||||
56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
|
||||
56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; };
|
||||
568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */; };
|
||||
568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */; };
|
||||
568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; };
|
||||
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; };
|
||||
5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -522,7 +524,6 @@
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -606,6 +607,8 @@
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = "<group>"; };
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -629,7 +632,6 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
5679533727E0A305004D18BD /* 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>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
|
||||
@@ -639,6 +641,8 @@
|
||||
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
|
||||
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
|
||||
568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
|
||||
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
|
||||
@@ -918,11 +922,10 @@
|
||||
children = (
|
||||
563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233D027243A9100529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */,
|
||||
5613ED5921A95E6100DC7A68 /* ValueObservation.swift */,
|
||||
563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */,
|
||||
5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56C0538822ACEECD0029D27D /* ValueReducer */,
|
||||
566BD7302927AFD600595649 /* Observers */,
|
||||
56C0538822ACEECD0029D27D /* Reducers */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
sourceTree = "<group>";
|
||||
@@ -1243,6 +1246,15 @@
|
||||
path = Utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
566BD7302927AFD600595649 /* Observers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */,
|
||||
566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */,
|
||||
);
|
||||
path = Observers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1330,6 +1342,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1434,6 +1447,7 @@
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
@@ -1490,7 +1504,7 @@
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56C0538822ACEECD0029D27D /* ValueReducer */ = {
|
||||
56C0538822ACEECD0029D27D /* Reducers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56C0538A22ACEECD0029D27D /* Fetch.swift */,
|
||||
@@ -1499,7 +1513,7 @@
|
||||
563B8F99249E74E5007A48C9 /* Trace.swift */,
|
||||
56C0538C22ACEECD0029D27D /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
path = Reducers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
|
||||
@@ -1825,8 +1839,8 @@
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */,
|
||||
56158786288D878500A67323 /* Optional.swift in Sources */,
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -1861,6 +1875,7 @@
|
||||
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
|
||||
56C0539322ACEECD0029D27D /* Fetch.swift in Sources */,
|
||||
56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */,
|
||||
568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */,
|
||||
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
|
||||
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
@@ -1936,12 +1951,12 @@
|
||||
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
|
||||
56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56D110ED28AFC90800E64463 /* PersistableRecord+Insert.swift in Sources */,
|
||||
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
|
||||
564D4F93261E1D3300F55856 /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
@@ -2080,6 +2095,7 @@
|
||||
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
5691D96F27256C490021D540 /* AvailableElements.swift in Sources */,
|
||||
56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */,
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */,
|
||||
F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */,
|
||||
5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
|
||||
|
||||
+7
-2
@@ -16,8 +16,12 @@ if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
|
||||
cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK"))
|
||||
}
|
||||
|
||||
// Don't rely on this environment variable. It is only a convenience:
|
||||
// $ make docs-localhost
|
||||
// The SPI_BUILDER environment variable enables documentation building
|
||||
// on <https://swiftpackageindex.com/groue/GRDB.swift>. See
|
||||
// <https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/2122>
|
||||
// for more information.
|
||||
//
|
||||
// SPI_BUILDER also enables the `make docs-localhost` command.
|
||||
var dependencies: [PackageDescription.Package.Dependency] = []
|
||||
if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" {
|
||||
dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"))
|
||||
@@ -33,6 +37,7 @@ let package = Package(
|
||||
.watchOS(.v4),
|
||||
],
|
||||
products: [
|
||||
.library(name: "CSQLite", targets: ["CSQLite"]),
|
||||
.library(name: "GRDB", targets: ["GRDB"]),
|
||||
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
|
||||
],
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.3.1</string>
|
||||
<string>6.4.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -44,6 +44,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -146,6 +149,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -183,6 +189,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -220,6 +229,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -258,6 +270,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
@@ -283,6 +298,9 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -46,17 +46,17 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("teamId", .integer).references("team")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
}
|
||||
try db.create(table: "award") { t in
|
||||
t.column("customPrimaryKey", .integer).primaryKey()
|
||||
t.primaryKey("customPrimaryKey", .integer)
|
||||
t.column("teamId", .integer).references("team")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -50,11 +50,11 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "teams") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -52,11 +52,11 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "teams") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -22,11 +22,11 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "teams") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -30,11 +30,11 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
@@ -326,7 +326,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
@@ -542,7 +542,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
@@ -1767,7 +1767,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
@@ -2033,7 +2033,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "author") { t in
|
||||
t.column("id", .text).primaryKey()
|
||||
t.primaryKey("id", .text)
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
|
||||
@@ -38,20 +38,20 @@ class AssociationChainRowScopesTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("did", .integer).references("d")
|
||||
t.column("name", .text)
|
||||
|
||||
@@ -33,17 +33,17 @@ class AssociationChainSQLTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("did", .integer).references("d")
|
||||
}
|
||||
|
||||
@@ -31,11 +31,11 @@ class AssociationHasManyOrderingTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("position", .integer).notNull()
|
||||
|
||||
@@ -118,7 +118,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parentId", .integer)
|
||||
@@ -214,7 +214,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parentId", .integer).references("parents")
|
||||
@@ -343,7 +343,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parent1Id", .integer).references("parents")
|
||||
|
||||
@@ -32,11 +32,11 @@ class AssociationHasManyThroughOrderingTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "playerRole") { t in
|
||||
|
||||
@@ -310,10 +310,10 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "muscleGroup") { table in
|
||||
table.column("id", .text).notNull().primaryKey()
|
||||
table.primaryKey("id", .text)
|
||||
}
|
||||
try db.create(table: "exercise") { table in
|
||||
table.column("id", .text).notNull().primaryKey()
|
||||
table.primaryKey("id", .text)
|
||||
}
|
||||
try db.create(table: "primaryMuscleGroup") { table in
|
||||
table.column("muscleGroupId", .text).notNull().references("muscleGroup", onDelete: .cascade)
|
||||
|
||||
@@ -30,10 +30,10 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("aid", .integer).references("a")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parentId", .integer)
|
||||
@@ -186,7 +186,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parentId", .integer).references("parents")
|
||||
@@ -296,7 +296,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.column("parent1Id", .integer).references("parents")
|
||||
|
||||
@@ -48,15 +48,15 @@ class AssociationParallelDecodableRecordTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("did", .integer).references("d")
|
||||
t.column("name", .text)
|
||||
|
||||
@@ -46,21 +46,21 @@ class AssociationParallelRowScopesTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("did", .integer).references("d")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
@@ -31,18 +31,18 @@ class AssociationParallelSQLTests: GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
t.column("did", .integer).references("d")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,19 +34,19 @@ class AssociationRowScopeSearchTests: GRDBTestCase {
|
||||
try dbWriter.write { db in
|
||||
// 1. Prepare data
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("aid", .integer).references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("aid", .integer).references("a")
|
||||
t.column("bid", .integer).references("b")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid", .integer).references("b")
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO a (id) VALUES (1)")
|
||||
|
||||
@@ -24,10 +24,10 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
override func setup(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.create(table: "b") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("bid1", .integer).references("b")
|
||||
t.column("bid2", .integer).references("b")
|
||||
t.column("parentId", .integer).references("a")
|
||||
|
||||
@@ -40,6 +40,9 @@ class DatabaseAbortedTransactionTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testReadTransactionAbortedByInterruptDoesNotPreventFurtherRead() throws {
|
||||
@@ -82,6 +85,9 @@ class DatabaseAbortedTransactionTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testWriteTransactionAbortedByInterrupt() throws {
|
||||
|
||||
@@ -26,6 +26,11 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
|
||||
try pool.makeSnapshot().read { _ in }
|
||||
XCTAssertEqual(connectionCount, 5)
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try pool.makeSnapshotPool().read { _ in }
|
||||
XCTAssertEqual(connectionCount, 6)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testPrepareDatabaseError() throws {
|
||||
@@ -68,6 +73,14 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
_ = try pool.makeSnapshot()
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
do {
|
||||
error = TestError()
|
||||
_ = try pool.makeSnapshotPool()
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -222,7 +222,7 @@ extension DatabaseDateEncodingStrategyTests {
|
||||
extension DatabaseDateEncodingStrategyTests {
|
||||
func testFilterKey() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .datetime) }
|
||||
|
||||
do {
|
||||
let request = Table<RecordWithDate<StrategyDeferredToDate>>("t").filter(key: testedDates[0])
|
||||
@@ -260,7 +260,7 @@ extension DatabaseDateEncodingStrategyTests {
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .datetime) }
|
||||
|
||||
do {
|
||||
let request = Table<RecordWithDate<StrategyDeferredToDate>>("t").filter(id: testedDates[0])
|
||||
@@ -340,7 +340,7 @@ extension DatabaseDateEncodingStrategyTests {
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .datetime) }
|
||||
|
||||
do {
|
||||
try Table<RecordWithDate<StrategyDeferredToDate>>("t").deleteOne(db, id: testedDates[0])
|
||||
|
||||
@@ -827,7 +827,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue(filename: dbName)
|
||||
|
||||
try dbPool.write { db in
|
||||
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .integer) }
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
|
||||
@@ -1095,7 +1095,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { db in
|
||||
try db.create(table: "persons") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1172,7 +1172,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { db in
|
||||
try db.create(table: "persons") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,44 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
class DatabaseQueueInMemoryTests : GRDBTestCase
|
||||
{
|
||||
func testInMemoryDatabase() throws {
|
||||
let dbQueue = try DatabaseQueue()
|
||||
try dbQueue.inTransaction { db in
|
||||
class DatabaseQueueInMemoryTests : GRDBTestCase {
|
||||
func test_independent_in_memory_database() throws {
|
||||
let baz = try DatabaseQueue().write { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (bar TEXT)")
|
||||
try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')")
|
||||
let baz = try String.fetchOne(db, sql: "SELECT bar FROM foo")!
|
||||
XCTAssertEqual(baz, "baz")
|
||||
return .rollback
|
||||
return try String.fetchOne(db, sql: "SELECT bar FROM foo")!
|
||||
}
|
||||
XCTAssertEqual(baz, "baz")
|
||||
}
|
||||
|
||||
func test_independent_in_memory_databases_are_independent() throws {
|
||||
try DatabaseQueue().write { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (bar TEXT)")
|
||||
}
|
||||
|
||||
try XCTAssertFalse(DatabaseQueue().read { try $0.tableExists("foo") })
|
||||
}
|
||||
|
||||
func test_shared_in_memory_database() throws {
|
||||
let name = UUID().uuidString
|
||||
let baz = try DatabaseQueue(named: name).write { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (bar TEXT)")
|
||||
try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')")
|
||||
return try String.fetchOne(db, sql: "SELECT bar FROM foo")!
|
||||
}
|
||||
XCTAssertEqual(baz, "baz")
|
||||
}
|
||||
|
||||
func test_shared_in_memory_databases_are_shared_by_name() throws {
|
||||
let nameA = UUID().uuidString
|
||||
let dbA = try DatabaseQueue(named: nameA)
|
||||
try dbA.write { db in
|
||||
try db.execute(sql: "CREATE TABLE foo (bar TEXT)")
|
||||
}
|
||||
|
||||
try withExtendedLifetime(dbA) {
|
||||
try XCTAssertTrue(DatabaseQueue(named: nameA).read { try $0.tableExists("foo") })
|
||||
try XCTAssertFalse(DatabaseQueue(named: UUID().uuidString).read { try $0.tableExists("foo") })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabaseQueue()))
|
||||
try test(setup(makeDatabasePool()))
|
||||
try test(setup(makeDatabasePool()).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(setup(makeDatabasePool()).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@@ -48,6 +51,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try await test(setup(makeDatabaseQueue()))
|
||||
try await test(setup(makeDatabasePool()))
|
||||
try await test(setup(makeDatabasePool()).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try await test(setup(makeDatabasePool()).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testReadPreventsDatabaseModification() throws {
|
||||
@@ -64,6 +70,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@@ -81,6 +90,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try await test(makeDatabaseQueue())
|
||||
try await test(makeDatabasePool())
|
||||
try await test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try await test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - UnsafeRead
|
||||
@@ -102,6 +114,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabaseQueue()))
|
||||
try test(setup(makeDatabasePool()))
|
||||
try test(setup(makeDatabasePool()).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(setup(makeDatabasePool()).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@@ -122,6 +137,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try await test(setup(makeDatabaseQueue()))
|
||||
try await test(setup(makeDatabasePool()))
|
||||
try await test(setup(makeDatabasePool()).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try await test(setup(makeDatabasePool()).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - UnsafeReentrantRead
|
||||
@@ -143,6 +161,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabaseQueue()))
|
||||
try test(setup(makeDatabasePool()))
|
||||
try test(setup(makeDatabasePool()).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(setup(makeDatabasePool()).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testUnsafeReentrantReadIsReentrant() throws {
|
||||
@@ -160,6 +181,25 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testUnsafeReentrantReadIsReentrantFromWrite() throws {
|
||||
func test(_ dbWriter: DatabaseWriter) throws {
|
||||
try dbWriter.write { db1 in
|
||||
try dbWriter.unsafeReentrantRead { db2 in
|
||||
try dbWriter.unsafeReentrantRead { db3 in
|
||||
XCTAssertTrue(db1 === db2)
|
||||
XCTAssertTrue(db2 === db3)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
// MARK: - AsyncRead
|
||||
@@ -188,6 +228,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
func testAsyncReadPreventsDatabaseModification() throws {
|
||||
@@ -214,6 +257,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Function
|
||||
@@ -231,6 +277,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Collation
|
||||
@@ -248,6 +297,9 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(makeDatabasePool().makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Backup
|
||||
@@ -272,5 +324,8 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabaseQueue(configuration: Configuration())))
|
||||
try test(setup(makeDatabasePool(configuration: Configuration())))
|
||||
try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot())
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool())
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -234,7 +234,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
// let dbQueue = try makeDatabaseQueue()
|
||||
// try dbQueue.write { db in
|
||||
// try db.create(table: "gallery") { t in
|
||||
// t.column("id", .integer).primaryKey()
|
||||
// t.primaryKey("id", .integer)
|
||||
// t.column("status", .integer)
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
// test create from non-wal (read-only) snapshot
|
||||
final class DatabaseSnapshotPoolTests: GRDBTestCase {
|
||||
/// A helper type
|
||||
private struct Counter {
|
||||
init(dbPool: DatabasePool) throws {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
}
|
||||
|
||||
func increment(_ db: Database) throws {
|
||||
try db.execute(sql: "INSERT INTO counter DEFAULT VALUES")
|
||||
}
|
||||
|
||||
func value(_ db: Database) throws -> Int {
|
||||
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")!
|
||||
}
|
||||
}
|
||||
|
||||
func test_creation_from_new_DatabasePool() throws {
|
||||
_ = try makeDatabasePool().makeSnapshotPool()
|
||||
}
|
||||
|
||||
func test_creation_from_non_WAL_DatabasePool() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
let dbPool = try DatabasePool(path: dbQueue.path, configuration: config)
|
||||
|
||||
do {
|
||||
_ = try dbPool.makeSnapshotPool()
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_ERROR { }
|
||||
}
|
||||
|
||||
func test_creation_from_DatabasePool_write_and_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.write { db in try DatabaseSnapshotPool(db) } // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_creation_from_DatabasePool_writeWithoutTransaction_and_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.writeWithoutTransaction { db in try DatabaseSnapshotPool(db) } // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_creation_from_DatabasePool_uncommitted_write() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
do {
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
_ = try DatabaseSnapshotPool(db)
|
||||
}
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_ERROR { }
|
||||
}
|
||||
|
||||
func test_creation_from_DatabasePool_read_and_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.read { db in try DatabaseSnapshotPool(db) } // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_creation_from_DatabasePool_unsafeRead_and_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.unsafeRead { db in try DatabaseSnapshotPool(db) } // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_discarded_transaction() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try snapshot.read { db in
|
||||
try XCTAssertEqual(counter.value(db), 1)
|
||||
try db.commit() // lose snapshot
|
||||
try XCTAssertEqual(counter.value(db), 2)
|
||||
}
|
||||
|
||||
// Try to invalidate the snapshot
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) }
|
||||
|
||||
// Snapshot is not lost, and previous connection is not reused.
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
|
||||
func test_replaced_transaction() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try snapshot.read { db in
|
||||
try XCTAssertEqual(counter.value(db), 1)
|
||||
try db.commit() // lose snapshot
|
||||
try db.beginTransaction()
|
||||
try XCTAssertEqual(counter.value(db), 2)
|
||||
}
|
||||
|
||||
// Try to invalidate the snapshot
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) }
|
||||
|
||||
// Snapshot is not lost, and previous connection is not reused.
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
|
||||
func test_concurrent_read() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
// Block 1 Block 2
|
||||
// snapshot.read {
|
||||
// SELECT COUNT(*) FROM counter
|
||||
// >
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
// snapshot.read {
|
||||
// SELECT COUNT(*) FROM counter
|
||||
// <
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
// end end
|
||||
// }
|
||||
|
||||
let block1: () -> Void = {
|
||||
try! snapshot.read { db -> Void in
|
||||
try XCTAssertEqual(counter.value(db), 1)
|
||||
s1.signal()
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
}
|
||||
}
|
||||
let block2: () -> Void = {
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
try! snapshot.read { db -> Void in
|
||||
try XCTAssertEqual(counter.value(db), 1)
|
||||
s2.signal()
|
||||
}
|
||||
}
|
||||
let blocks = [block1, block2]
|
||||
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
|
||||
blocks[index]()
|
||||
}
|
||||
}
|
||||
|
||||
func test_unsafeRead() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.unsafeRead(counter.value), 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
func test_unsafeReentrantRead() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try dbPool.write(counter.increment) // 2
|
||||
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
try XCTAssertEqual(snapshot.unsafeReentrantRead { _ in try snapshot.unsafeReentrantRead(counter.value) }, 1)
|
||||
// Reuse the last connection
|
||||
try XCTAssertEqual(dbPool.read(counter.value), 2)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func test_read_async() async throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try await dbPool.write { try counter.increment($0) } // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try await dbPool.write { try counter.increment($0) } // 2
|
||||
|
||||
do {
|
||||
let count = try await dbPool.read { try counter.value($0) }
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
do {
|
||||
let count = try await snapshot.read { try counter.value($0) }
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
do {
|
||||
// Reuse the last connection
|
||||
let count = try await dbPool.read { try counter.value($0) }
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
func testPassiveCheckpointDoesNotInvalidateSnapshotPool() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
try dbPool.write(counter.increment) // 2
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
|
||||
func testFullCheckpointDoesNotInvalidateSnapshotPool() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
try dbPool.write(counter.increment) // 2
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
|
||||
func testRestartCheckpointDoesNotInvalidateSnapshotPool() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
try dbPool.write(counter.increment) // 2
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
|
||||
func testTruncateCheckpointDoesNotInvalidateSnapshotPool() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
let counter = try Counter(dbPool: dbPool) // 0
|
||||
try dbPool.write(counter.increment) // 1
|
||||
let snapshot = try dbPool.makeSnapshotPool() // locked at 1
|
||||
try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
try dbPool.write(counter.increment) // 2
|
||||
try XCTAssertEqual(snapshot.read(counter.value), 1)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -2,12 +2,9 @@ import XCTest
|
||||
@testable import GRDB
|
||||
|
||||
class DatabaseSnapshotTests: GRDBTestCase {
|
||||
|
||||
/// A helper class
|
||||
private class Counter {
|
||||
let dbPool: DatabasePool
|
||||
/// A helper type
|
||||
private struct Counter {
|
||||
init(dbPool: DatabasePool) throws {
|
||||
self.dbPool = dbPool
|
||||
try dbPool.write { db in
|
||||
try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ extension DatabaseUUIDEncodingStrategyTests {
|
||||
extension DatabaseUUIDEncodingStrategyTests {
|
||||
func testFilterKey() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .blob) }
|
||||
let uuids = [
|
||||
UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!,
|
||||
UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!,
|
||||
@@ -185,7 +185,7 @@ extension DatabaseUUIDEncodingStrategyTests {
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .blob) }
|
||||
let uuids = [
|
||||
UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!,
|
||||
UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!,
|
||||
@@ -304,7 +304,7 @@ extension DatabaseUUIDEncodingStrategyTests {
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { $0.column("id").primaryKey() }
|
||||
try db.create(table: "t") { $0.primaryKey("id", .blob) }
|
||||
let uuids = [
|
||||
UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!,
|
||||
UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!,
|
||||
|
||||
@@ -7,7 +7,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.unsafeReentrantWrite { db1 in
|
||||
try db1.create(table: "table1") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try dbQueue.unsafeReentrantWrite { db2 in
|
||||
try db2.execute(sql: "INSERT INTO table1 (id) VALUES (NULL)")
|
||||
@@ -25,7 +25,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.unsafeReentrantWrite { db1 in
|
||||
try db1.create(table: "table1") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try dbPool.unsafeReentrantWrite { db2 in
|
||||
try db2.execute(sql: "INSERT INTO table1 (id) VALUES (NULL)")
|
||||
|
||||
@@ -164,7 +164,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
@@ -198,7 +198,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
|
||||
@@ -215,7 +215,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
@@ -244,7 +244,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
|
||||
@@ -222,7 +222,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
@@ -256,7 +256,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
|
||||
@@ -280,7 +280,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
@@ -309,7 +309,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "documents") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("content", .text)
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
|
||||
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user