diff --git a/.gitignore b/.gitignore
index 6d0da4123..cd1383aee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -106,7 +106,6 @@ Podfile.lock
# SPM
.build
-.swiftpm/
GRDB.xcworkspace/xcshareddata/swiftpm
#Package.resolved
Tests/SPM/Packages
diff --git a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 000000000..919434a62
--- /dev/null
+++ b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme
new file mode 100644
index 000000000..b60345c20
--- /dev/null
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme
@@ -0,0 +1,134 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45a2bfdf6..eda40803d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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)
diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md
index b7fc7d696..7f8158d44 100644
--- a/Documentation/AssociationsBasics.md
+++ b/Documentation/AssociationsBasics.md
@@ -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
diff --git a/Documentation/Combine.md b/Documentation/Combine.md
index aa0647d24..a9004214a 100644
--- a/Documentation/Combine.md
+++ b/Documentation/Combine.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
diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md
index 7873c5852..5df56ab8f 100644
--- a/Documentation/CustomSQLiteBuilds.md
+++ b/Documentation/CustomSQLiteBuilds.md
@@ -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.
diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift
index 03f7d14b0..0d4b2227c 100644
--- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift
+++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift
@@ -34,7 +34,7 @@ struct AppDatabase {
migrator.registerMigration("createPlayer") { db in
// Create a table
- // See https://github.com/groue/GRDB.swift#create-tables
+ // See
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
diff --git a/Documentation/DemoApps/GRDBAsyncDemo/README.md b/Documentation/DemoApps/GRDBAsyncDemo/README.md
index 5740eee91..6fc5a85e2 100644
--- a/Documentation/DemoApps/GRDBAsyncDemo/README.md
+++ b/Documentation/DemoApps/GRDBAsyncDemo/README.md
@@ -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.
diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift
index 3c8370907..b9516f3d0 100644
--- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift
+++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift
@@ -35,7 +35,7 @@ struct AppDatabase {
migrator.registerMigration("createPlayer") { db in
// Create a table
- // See https://github.com/groue/GRDB.swift#create-tables
+ // See
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md
index a51bbe7c0..5bb162284 100644
--- a/Documentation/DemoApps/GRDBCombineDemo/README.md
+++ b/Documentation/DemoApps/GRDBCombineDemo/README.md
@@ -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.
diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift
index 7543a31e5..ff56eec1f 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift
+++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift
@@ -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
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md
index 210022c97..098f37d79 100644
--- a/Documentation/DemoApps/GRDBDemoiOS/README.md
+++ b/Documentation/DemoApps/GRDBDemoiOS/README.md
@@ -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)
diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md
index 23df660a3..baf6c945a 100644
--- a/Documentation/FetchedRecordsController.md
+++ b/Documentation/FetchedRecordsController.md
@@ -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.
diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md
index 631b0e7b2..b0c2f61a0 100644
--- a/Documentation/FullTextSearch.md
+++ b/Documentation/FullTextSearch.md
@@ -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
diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md
index 41ef70dd5..8ff58693f 100644
--- a/Documentation/GRDB5MigrationGuide.md
+++ b/Documentation/GRDB5MigrationGuide.md
@@ -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
diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md
index a681e6fc8..60f4e73eb 100644
--- a/Documentation/GoodPracticesForDesigningRecordTypes.md
+++ b/Documentation/GoodPracticesForDesigningRecordTypes.md
@@ -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
diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md
index bbb04b82d..f1c27f714 100644
--- a/Documentation/QueryInterfaceOrganization.md
+++ b/Documentation/QueryInterfaceOrganization.md
@@ -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
diff --git a/Documentation/ReleaseProcess.md b/Documentation/ReleaseProcess.md
index 0ae106b56..e8aa77fb7 100644
--- a/Documentation/ReleaseProcess.md
+++ b/Documentation/ReleaseProcess.md
@@ -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`
diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md
index 062895a40..24cd883b3 100644
--- a/Documentation/WhyAdoptGRDB.md
+++ b/Documentation/WhyAdoptGRDB.md
@@ -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
diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec
index 11654db6e..35ae05b93 100644
--- a/GRDB.swift.podspec
+++ b/GRDB.swift.podspec
@@ -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.'
diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj
index 06012b132..089a9fd2a 100755
--- a/GRDB.xcodeproj/project.pbxproj
+++ b/GRDB.xcodeproj/project.pbxproj
@@ -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 = ""; };
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; };
+ 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; };
+ 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; };
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; };
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; };
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; };
@@ -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 = "";
@@ -1232,6 +1235,15 @@
path = Utils;
sourceTree = "";
};
+ 566BD72F2927AFC300595649 /* Observers */ = {
+ isa = PBXGroup;
+ children = (
+ 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
+ 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
+ );
+ path = Observers;
+ sourceTree = "";
+ };
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 = "";
};
- 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 = "";
};
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 */,
diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift
index 6c139d36e..174e96965 100644
--- a/GRDB/Core/Configuration.swift
+++ b/GRDB/Core/Configuration.swift
@@ -19,6 +19,37 @@ import Foundation
/// ```
///
/// See .
+///
+/// ## 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
+ /// . 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:
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 access SQLite connections
+ /// through a `SerializedDatabase`.
+ var threadingMode = Database.ThreadingMode.default
+
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift
index 8a66e2585..a4350e39f 100644
--- a/GRDB/Core/Database+Schema.swift
+++ b/GRDB/Core/Database+Schema.swift
@@ -79,6 +79,13 @@ extension Database {
// MARK: - Database Schema
+ /// Returns the current schema version.
+ ///
+ /// Related SQLite documentation:
+ 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:
//
//
- 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
- /// - 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)
+ """)
+ }
+}
diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift
index 25993284b..6a8d52f01 100644
--- a/GRDB/Core/Database+Statements.swift
+++ b/GRDB/Core/Database+Statements.swift
@@ -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)
diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift
index 780ecd549..fb0e129c2 100644
--- a/GRDB/Core/Database.swift
+++ b/GRDB/Core/Database.swift
@@ -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(_ 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 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:
+ /// 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 .
+ ///
+ /// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
+ /// supported, since all access SQLite connections
+ /// through a `SerializedDatabase`.
enum ThreadingMode {
case `default`
case multiThread
diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift
index 8dabe85ea..5c5afa1d1 100644
--- a/GRDB/Core/DatabasePool.swift
+++ b/GRDB/Core/DatabasePool.swift
@@ -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
+ //
// > 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(_ 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
}
diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift
index e2d38695b..1e8268467 100644
--- a/GRDB/Core/DatabaseQueue.swift
+++ b/GRDB/Core/DatabaseQueue.swift
@@ -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:
+ ///
+ /// - 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")
}
diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift
index ae0f3663a..aa1851cd4 100644
--- a/GRDB/Core/DatabaseReader.swift
+++ b/GRDB/Core/DatabaseReader.swift
@@ -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 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
+ /// 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
+ /// 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
+ /// 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 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
+ /// 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(_ 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(_ 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) -> Void) {
+ asyncRead(value)
+ }
+}
diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift
index a293aea6f..384a9e414 100644
--- a/GRDB/Core/DatabaseRegion.swift
+++ b/GRDB/Core/DatabaseRegion.swift
@@ -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``
diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift
index 9e87d403f..eb95739af 100644
--- a/GRDB/Core/DatabaseRegionObservation.swift
+++ b/GRDB/Core/DatabaseRegionObservation.swift
@@ -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 .
+/// 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
diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift
index c4a36b361..9ab92e592 100644
--- a/GRDB/Core/DatabaseSnapshot.swift
+++ b/GRDB/Core/DatabaseSnapshot.swift
@@ -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(_ block: (Database) throws -> T) rethrows -> T {
- try serializedDatabase.sync(block)
+ try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result) -> Void) {
- serializedDatabase.async { value(.success($0)) }
+ reader.async { value(.success($0)) }
}
public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T {
- try serializedDatabase.sync(value)
+ try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) {
- serializedDatabase.async { value(.success($0)) }
+ reader.async { value(.success($0)) }
}
public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T {
- try serializedDatabase.reentrantSync(value)
+ try reader.reentrantSync(value)
}
// MARK: - Database Observation
diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift
new file mode 100644
index 000000000..8f635c244
--- /dev/null
+++ b/GRDB/Core/DatabaseSnapshotPool.swift
@@ -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:
+///
+/// -
+/// -
+///
+/// ## 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?
+
+ /// 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:
+ ///
+ /// - 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:
+ ///
+ /// - 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
+ 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(_ 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) -> 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(_ 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(
+ observation: ValueObservation,
+ 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
diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift
index 927324f24..fb264a6b3 100644
--- a/GRDB/Core/DatabaseWriter.swift
+++ b/GRDB/Core/DatabaseWriter.swift
@@ -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
+ /// 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
+ /// 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
+ /// 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
+ /// 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 for
- /// more information).
+ /// database accesses are discouraged because they muddle transaction
+ /// boundaries. See for
+ /// more information.
///
/// For example:
///
diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift
index 0927f9fc1..bcec3e9f7 100644
--- a/GRDB/Core/SerializedDatabase.swift
+++ b/GRDB/Core/SerializedDatabase.swift
@@ -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
diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift
index 6df6651b8..e16a0f12d 100644
--- a/GRDB/Core/TransactionObserver.swift
+++ b/GRDB/Core/TransactionObserver.swift
@@ -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
+/// 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 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 `` 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
diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift
index 29c811b51..7ce291061 100644
--- a/GRDB/Core/WALSnapshot.swift
+++ b/GRDB/Core/WALSnapshot.swift
@@ -19,40 +19,44 @@
/// Yes, this is an awfully complex logic.
///
/// See .
-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?
+ let sqliteSnapshot: UnsafeMutablePointer
- /// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an
- /// error occurs.
- init?(_ db: Database) {
- var snapshot: UnsafeMutablePointer?
- let code = withUnsafeMutablePointer(to: &snapshot) {
+ init(_ db: Database) throws {
+ var sqliteSnapshot: UnsafeMutablePointer?
+ 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 .
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
}
diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md
index ec48c0623..4f6efbe02 100644
--- a/GRDB/Documentation.docc/Concurrency.md
+++ b/GRDB/Documentation.docc/Concurrency.md
@@ -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 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 ). 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
diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md
index 6e5f61819..db6321bd9 100644
--- a/GRDB/Documentation.docc/DatabaseConnections.md
+++ b/GRDB/Documentation.docc/DatabaseConnections.md
@@ -28,11 +28,12 @@ The differences are:
- ``Configuration``
-### Opening Database Connections
+### Database Connections
- ``DatabaseQueue``
- ``DatabasePool``
- ``DatabaseSnapshot``
+- ``DatabaseSnapshotPool``
### Using Database Connections
diff --git a/GRDB/Documentation.docc/DatabaseObservation.md b/GRDB/Documentation.docc/DatabaseObservation.md
index 1fddaa39b..e2ce7e5a2 100644
--- a/GRDB/Documentation.docc/DatabaseObservation.md
+++ b/GRDB/Documentation.docc/DatabaseObservation.md
@@ -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
diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md
index c187cff9d..d1743166f 100644
--- a/GRDB/Documentation.docc/DatabaseSchema.md
+++ b/GRDB/Documentation.docc/DatabaseSchema.md
@@ -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 .
+
+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 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 ) 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 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 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 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 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 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 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 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:)``
diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md
index fe2c23bf4..e6531907b 100644
--- a/GRDB/Documentation.docc/Documentation.md
+++ b/GRDB/Documentation.docc/Documentation.md
@@ -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
-
-
-### Record Types and the Query Interface
+### Records and the Query Interface
-
-### Database Observation
+### Responding to Database Changes
-
diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md
index 0c7bcd7ad..f06c18af7 100644
--- a/GRDB/Documentation.docc/QueryInterface.md
+++ b/GRDB/Documentation.docc/QueryInterface.md
@@ -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
diff --git a/GRDB/Documentation.docc/SingleRowTables.md b/GRDB/Documentation.docc/SingleRowTables.md
index 37241c099..cf90c6995 100644
--- a/GRDB/Documentation.docc/SingleRowTables.md
+++ b/GRDB/Documentation.docc/SingleRowTables.md
@@ -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 , 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()
diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift
index fb7e12b0d..8ff802b97 100644
--- a/GRDB/Fixits.swift
+++ b/GRDB/Fixits.swift
@@ -159,10 +159,11 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
@available(*, unavailable, renamed: "Statement")
public typealias UpdateStatement = Statement
-extension ValueObservation {
+extension ValueObservation {
@available(*, unavailable, renamed: "tracking(_:)")
public static func trackingVaryingRegion(
_ fetch: @escaping (Database) throws -> Value)
- -> ValueObservation>
+ -> Self
+ where Reducer == ValueReducers.Fetch
{ preconditionFailure() }
}
diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift
index b3ac2cded..36f9e7708 100644
--- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift
+++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift
@@ -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
diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift
index 2ee094189..553511e19 100644
--- a/GRDB/QueryInterface/Request/RequestProtocols.swift
+++ b/GRDB/QueryInterface/Request/RequestProtocols.swift
@@ -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()
diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift
index 6b5b578a6..d6ec258be 100644
--- a/GRDB/QueryInterface/SQL/Table.swift
+++ b/GRDB/QueryInterface/SQL/Table.swift
@@ -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 {
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 {
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 {
diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift
index 219aad488..e755deea2 100644
--- a/GRDB/QueryInterface/Schema/TableDefinition.swift
+++ b/GRDB/QueryInterface/Schema/TableDefinition.swift
@@ -21,7 +21,8 @@ extension Database {
/// -
/// -
///
- /// - 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:
- /// -
- /// -
+ /// ### 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
+ /// > 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:
///
- /// - 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
+ /// Creates a [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) table.
+ ///
+ /// Such tables can not be tracked with tools.
public static let withoutRowID = TableOptions(rawValue: 1 << 2)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
- /// Creates a STRICT table
- ///
- /// Related SQLite documentation:
+ /// 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:
+ /// 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:
+/// ### 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:
+ //
+ 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:
+ //
+ 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:
- /// -
- /// -
+ /// - 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
+ /// 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:
///
/// - parameter columns: The unique key columns.
/// - parameter conflictResolution: An optional conflict resolution
/// (see ).
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:
///
/// - 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:
///
/// - 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
/// 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:
- /// -
- /// -
+ /// - 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
diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift
index 21af9630b..00ec06396 100644
--- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift
+++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift
@@ -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 {
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 {
all().filter(keys: keys)
}
diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift
index ceb76c048..7dcc3daa7 100644
--- a/GRDB/Record/FetchableRecord+TableRecord.swift
+++ b/GRDB/Record/FetchableRecord+TableRecord.swift
@@ -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? {
diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift
index cb3f26c74..2c91dd50a 100644
--- a/GRDB/Record/TableRecord.swift
+++ b/GRDB/Record/TableRecord.swift
@@ -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 {
diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift
index f9c72785a..79388ae12 100644
--- a/GRDB/Utils/LockedBox.swift
+++ b/GRDB/Utils/LockedBox.swift
@@ -66,3 +66,5 @@ extension LockedBox where T: Numeric {
}
}
}
+
+extension LockedBox: @unchecked Sendable where T: Sendable { }
diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift
index 8c7e84994..d6303f4e7 100644
--- a/GRDB/Utils/Pool.swift
+++ b/GRDB/Utils/Pool.swift
@@ -75,7 +75,7 @@ final class Pool {
/// 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 {
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 {
///
/// - 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 {
/// Performs a synchronous block with an element. The element turns
/// available after the block has executed.
func get(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 {
}
}
}
+
+enum PoolCompletion {
+ // Reuse the element
+ case reuse
+ // Discard the element
+ case discard
+}
diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
similarity index 96%
rename from GRDB/ValueObservation/ValueConcurrentObserver.swift
rename to GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
index 5ccbfb6ab..63c2f4df1 100644
--- a/GRDB/ValueObservation/ValueConcurrentObserver.swift
+++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
@@ -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
diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift
similarity index 100%
rename from GRDB/ValueObservation/ValueWriteOnlyObserver.swift
rename to GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift
diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift
similarity index 100%
rename from GRDB/ValueObservation/ValueReducer/Fetch.swift
rename to GRDB/ValueObservation/Reducers/Fetch.swift
diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift
similarity index 67%
rename from GRDB/ValueObservation/ValueReducer/Map.swift
rename to GRDB/ValueObservation/Reducers/Map.swift
index 453f84db0..b69984b24 100644
--- a/GRDB/ValueObservation/ValueReducer/Map.swift
+++ b/GRDB/ValueObservation/Reducers/Map.swift
@@ -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 ).
+ ///
/// - parameter transform: A closure that takes one value as its parameter
/// and returns a new value.
public func map(_ 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)
}
diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift
similarity index 55%
rename from GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift
rename to GRDB/ValueObservation/Reducers/RemoveDuplicates.swift
index 31ac711f9..df1eb0ab2 100644
--- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift
+++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift
@@ -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>
{
@@ -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)
}
diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift
similarity index 91%
rename from GRDB/ValueObservation/ValueReducer/Trace.swift
rename to GRDB/ValueObservation/Reducers/Trace.swift
index da41cfd73..bb2db4f62 100644
--- a/GRDB/ValueObservation/ValueReducer/Trace.swift
+++ b/GRDB/ValueObservation/Reducers/Trace.swift
@@ -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)
diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift
similarity index 64%
rename from GRDB/ValueObservation/ValueReducer/ValueReducer.swift
rename to GRDB/ValueObservation/Reducers/ValueReducer.swift
index d26f544c7..0a4706057 100644
--- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift
+++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift
@@ -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.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 { }
diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift
index 2732c077b..cbcf065eb 100644
--- a/GRDB/ValueObservation/SharedValueObservation.swift
+++ b/GRDB/ValueObservation/SharedValueObservation.swift
@@ -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
diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift
index 13dac99cc..9db7ef096 100644
--- a/GRDB/ValueObservation/ValueObservation.swift
+++ b/GRDB/ValueObservation/ValueObservation.swift
@@ -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 .
+/// 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
+/// 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 .
+///
+/// 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 .
+///
+/// `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 {
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(
_ fetch: @escaping (Database) throws -> Value)
- -> ValueObservation>
+ -> Self
+ where Reducer == ValueReducers.Fetch
{
.init(
trackingMode: .constantRegionRecordedFromSelection,
@@ -753,7 +1100,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
public static func tracking(
region: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
- -> ValueObservation>
+ -> Self
+ where Reducer == ValueReducers.Fetch
{
tracking(regions: region, fetch: fetch)
}
@@ -808,7 +1156,8 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
public static func tracking(
regions: [any DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
- -> ValueObservation>
+ -> Self
+ where Reducer == ValueReducers.Fetch
{
.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(
_ fetch: @escaping (Database) throws -> Value)
- -> ValueObservation>
+ -> Self
+ where Reducer == ValueReducers.Fetch
{
.init(
trackingMode: .nonConstantRegionRecordedFromSelection,
diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj
index ffef388ad..3b15a8f99 100755
--- a/GRDBCustom.xcodeproj/project.pbxproj
+++ b/GRDBCustom.xcodeproj/project.pbxproj
@@ -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 = ""; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; };
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; };
- 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; };
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; };
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; };
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; };
@@ -606,6 +607,8 @@
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; };
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; };
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; };
+ 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; };
+ 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; };
566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; };
566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = ""; };
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; };
@@ -629,7 +632,6 @@
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; };
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; };
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = ""; };
- 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; };
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = ""; };
@@ -639,6 +641,8 @@
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; };
56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; };
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; };
+ 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; };
+ 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; };
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; };
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; };
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; };
@@ -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 = "";
@@ -1243,6 +1246,15 @@
path = Utils;
sourceTree = "";
};
+ 566BD7302927AFD600595649 /* Observers */ = {
+ isa = PBXGroup;
+ children = (
+ 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */,
+ 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */,
+ );
+ path = Observers;
+ sourceTree = "";
+ };
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 = "";
};
- 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 = "";
};
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 */,
diff --git a/Package.swift b/Package.swift
index cfcd74ed6..521f5799f 100644
--- a/Package.swift
+++ b/Package.swift
@@ -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 . See
+//
+// 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"]),
],
diff --git a/README.md b/README.md
index 157225250..49cda67fe 100644
--- a/README.md
+++ b/README.md
@@ -11,13 +11,13 @@
---
-**Latest release**: November 11, 2022 • [version 6.3.1](https://github.com/groue/GRDB.swift/tree/v6.3.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
+**Latest release**: November 28, 2022 • [version 6.4.0](https://github.com/groue/GRDB.swift/tree/v6.4.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
| Swift version | GRDB version |
| -------------- | ----------------------------------------------------------- |
-| **Swift 5.7+** | **v6.3.1** |
+| **Swift 5.7+** | **v6.4.0** |
| Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) |
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -42,7 +42,7 @@
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.
-Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://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.
+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.
It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), and it is [fast](https://github.com/groue/GRDB.swift/wiki/Performance).
@@ -80,9 +80,9 @@ Programming tools for both database beginners and SQLite experts:
In-depth integration with our programming environment:
- [Swift Concurrency](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency): `try await` your database.
-- [SwiftUI](http://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views.
+- [SwiftUI](https://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views.
- [Combine](Documentation/Combine.md): Access and observe the database with Combine publishers.
-- [RxSwift](http://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables.
+- [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables.
## Usage
@@ -336,7 +336,7 @@ Documentation
#### Records and the Query Interface
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies
-- [Query Interface](#the-query-interface): A swift way to generate SQL • [table creation](#database-schema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
+- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
#### Application Tools
@@ -2449,7 +2449,7 @@ try dbQueue.write { db in
}
```
-Of course, you need to open a [database connection](#database-connections), and [create database tables](#database-schema) first.
+Of course, you need to open a [database connection](#database-connections), and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) first.
To define your custom records, you subclass the ready-made `Record` class, or you extend your structs and classes with protocols that come with focused sets of features: fetching methods, persistence methods, record comparison...
@@ -2952,7 +2952,7 @@ For more information about batch updates, see [Update Requests](#update-requests
- `delete` and `deleteOne` returns whether a database row was deleted or not. `deleteAll` returns the number of deleted rows. `updateAll` returns the number of updated rows. `updateChanges` returns whether a database row was updated or not.
-**All primary keys are supported**, including composite primary keys that span several columns, and the [implicit rowid primary key](#the-implicit-rowid-primary-key).
+**All primary keys are supported**, including composite primary keys that span several columns, and the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html).
**To customize persistence methods**, you provide [Persistence Callbacks], described below. Do not attempt at overriding the ready-made persistence methods.
@@ -3248,7 +3248,7 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut
>
> **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL.
>
-> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [Transaction Hook](#transaction-hook). For example:
+> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [afterNextTransaction(onCommit:onRollback:)](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). For example:
>
> ```swift
> struct PictureFile: PersistableRecord {
@@ -3309,7 +3309,7 @@ Some database tables have a single-column primary key which is not called "id":
```swift
try db.create(table: "country") { t in
- t.column("isoCode", .text).notNull().primaryKey()
+ t.primaryKey("isoCode", .text)
t.column("name", .text).notNull()
t.column("population", .integer).notNull()
}
@@ -3773,7 +3773,6 @@ GRDB records come with many default behaviors, that are designed to fit most sit
- [Persistence Callbacks]: define what happens when you call a persistence method such as `player.insert(db)`
- [Conflict Resolution]: Run `INSERT OR REPLACE` queries, and generally define what happens when a persistence method violates a unique index.
-- [The Implicit RowID Primary Key]: all about the special `rowid` column.
- [Columns Selected by a Request]: define which columns are selected by requests such as `Player.fetchAll(db)`.
- [Beyond FetchableRecord]: the FetchableRecord protocol is not the end of the story.
@@ -3865,126 +3864,7 @@ try player.insert(db)
> }
> ```
>
-> **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](#transactionobserver-protocol) (this might change in a future release of SQLite).
-
-
-### The Implicit RowID Primary Key
-
-**All SQLite tables have a primary key.** Even when the primary key is not explicit:
-
-```swift
-// No explicit primary key
-try db.create(table: "event") { t in
- t.column("message", .text)
- t.column("date", .datetime)
-}
-
-// No way to define an explicit primary key
-try db.create(virtualTable: "book", using: FTS4()) { t in
- t.column("title")
- t.column("author")
- t.column("body")
-}
-```
-
-The implicit primary key is stored in the hidden column `rowid`. Hidden means that `SELECT *` does not select it, and yet it can be selected and queried: `SELECT *, rowid ... WHERE rowid = 1`.
-
-Some GRDB methods will automatically use this hidden column when a table has no explicit primary key:
-
-```swift
-// SELECT * FROM event WHERE rowid = 1
-let event = try Event.fetchOne(db, id: 1)
-
-// DELETE FROM book WHERE rowid = 1
-try Book.deleteOne(db, id: 1)
-```
-
-
-#### Exposing the RowID Column
-
-**By default, a record type that wraps a table without any explicit primary key doesn't know about the hidden rowid column.**
-
-Without primary key, records don't have any identity, and the [persistence method](#persistence-methods) can behave in undesired fashion: `update()` throws errors, `save()` always performs insertions and may break constraints, `exists()` is always false.
-
-When SQLite won't let you provide an explicit primary key (as in [full-text](Documentation/FullTextSearch.md) tables, for example), you may want to make your record type fully aware of the hidden rowid column:
-
-1. Have the `databaseSelection` static property (from the [TableRecord] protocol) return the hidden rowid column:
-
- ```swift
- struct Event : TableRecord {
- static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
- }
-
- // When you subclass Record, you need an override:
- class Book : Record {
- override class var databaseSelection: [any SQLSelectable] {
- [AllColumns(), Column.rowID]
- }
- }
- ```
-
- GRDB will then select the `rowid` column by default:
-
- ```swift
- // SELECT *, rowid FROM event
- let events = try Event.fetchAll(db)
- ```
-
-2. Have `init(row:)` from the [FetchableRecord] protocol consume the "rowid" column:
-
- ```swift
- struct Event : FetchableRecord {
- var id: Int64?
-
- init(row: Row) {
- id = row[Column.rowID] // or `row[.rowID]` with Swift 5.5+
- }
- }
- ```
-
- Your fetched records will then know their ids:
-
- ```swift
- let event = try Event.fetchOne(db)!
- event.id // some value
- ```
-
-3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(_:)` callback (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols):
-
- ```swift
- struct Event : MutablePersistableRecord {
- var id: Int64?
-
- func encode(to container: inout PersistenceContainer) {
- container[Column.rowID] = id // or `container[.rowID]` with Swift 5.5+
- container["message"] = message
- container["date"] = date
- }
-
- // Update auto-incremented id upon successful insertion
- mutating func didInsert(_ inserted: InsertionSuccess) {
- id = inserted.rowID
- }
- }
- ```
-
- You will then be able to track your record ids, update them, or check for their existence:
-
- ```swift
- let event = Event(message: "foo", date: Date())
-
- // Insertion sets the record id:
- try event.insert(db)
- event.id // some value
-
- // Record can be updated:
- event.message = "bar"
- try event.update(db)
-
- // Record knows if it exists:
- event.exists(db) // true
- ```
-
+> **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) (this might change in a future release of SQLite).
### Beyond FetchableRecord
@@ -4401,7 +4281,7 @@ This is the list of record methods, along with their required protocols. The [Re
| `record.databaseChanges` | [Record](#record-class) | |
| `record.updateChanges(db)` | [Record](#record-class) | |
-¹ All unique keys are supported: primary keys (single-column, composite, [implicit RowID](#the-implicit-rowid-primary-key)) and unique indexes:
+¹ All unique keys are supported: primary keys (single-column, composite, [`rowid`](https://www.sqlite.org/rowidtable.html)) and unique indexes:
```swift
try Player.fetchOne(db, id: 1) // Player?
@@ -4495,7 +4375,7 @@ So don't miss the [SQL API](#sqlite-api).
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
-- [Database Schema](#database-schema)
+- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Requests](#requests)
- [Expressions](#expressions)
- [SQL Operators](#sql-operators)
@@ -4512,211 +4392,6 @@ So don't miss the [SQL API](#sqlite-api).
- :blue_book: [Common Table Expressions]
- :blue_book: [Query Interface Organization]
-
-## Database Schema
-
-Once granted with a [database connection](#database-connections), you can setup your database schema without writing SQL:
-
-- [Create Tables](#create-tables)
-- [Modify Tables](#modify-tables)
-- [Drop Tables](#drop-tables)
-- [Create Indexes](#create-indexes)
-
-
-### Create Tables
-
-```swift
-// CREATE TABLE place (
-// id INTEGER PRIMARY KEY AUTOINCREMENT,
-// title TEXT,
-// favorite 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().defaults(to: false)
- t.column("longitude", .double).notNull()
- t.column("latitude", .double).notNull()
-}
-```
-
-The `create(table:)` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search], or use raw SQL.
-
-SQLite itself has many reference documents about table creation: [CREATE TABLE](https://www.sqlite.org/lang_createtable.html), [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html), [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html), [ON CONFLICT](https://www.sqlite.org/lang_conflict.html), [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html).
-
-**Configure table creation**:
-
-```swift
-// CREATE TABLE example ( ... )
-try db.create(table: "example") { t in ... }
-
-// CREATE TEMPORARY TABLE example IF NOT EXISTS (
-try db.create(table: "example", options: [.temporary, .ifNotExists]) { t in ... }
-```
-
-> :bulb: **Tip**: database table names should be singular, and camelCased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, `httpRequest`.
->
-> This will help you using [Associations] when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
->
-> **Note**: [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables can not be tracked with [Database Observation] tools.
-
-**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` and `any`) - see [SQLite data types](https://www.sqlite.org/datatype3.html):
-
-```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)
-```
-
-Define **not null** columns, and set **default** values:
-
-```swift
- // email TEXT NOT NULL,
- t.column("email", .text).notNull()
-
- // name TEXT NOT NULL DEFAULT 'Anonymous',
- t.column("name", .text).notNull().defaults(to: "Anonymous")
-```
-
-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 PRIMARY KEY,
- t.column("uuid", .text).primaryKey()
-
- // email TEXT UNIQUE,
- t.column("email", .text).unique()
-
- // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
- t.column("countryCode", .text).references("country", onDelete: .cascade)
-```
-
-> :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method:
->
-> ```swift
-> try db.create(table: "example") { t in
-> t.autoIncrementedPrimaryKey("id")
-> ...
-> }
-> ```
->
-> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be acceptable. But usually it is not.
-
-**Create an index** on the column:
-
-```swift
- t.column("score", .integer).indexed()
-```
-
-For extra index options, see [Create Indexes](#create-indexes) below.
-
-**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL [expression](#expressions).
-
-```swift
- // name TEXT CHECK (LENGTH(name) > 0)
- // score INTEGER CHECK (score > 0)
- t.column("name", .text).check { length($0) > 0 }
- t.column("score", .integer).check(sql: "score > 0")
-```
-
-Columns can also be defined with a raw sql String, or an [SQL literal] in which you can safely embed raw values without any risk of syntax errors or SQL injection:
-
-```swift
- t.column(sql: "name TEXT")
-
- let defaultName: String = ...
- t.column(literal: "name TEXT DEFAULT \(defaultName)")
-```
-
-Other **table constraints** can involve several columns:
-
-```swift
- // PRIMARY KEY (a, b),
- t.primaryKey(["a", "b"])
-
- // UNIQUE (a, b) ON CONFLICT REPLACE,
- t.uniqueKey(["a", "b"], onConflict: .replace)
-
- // FOREIGN KEY (a, b) REFERENCES parents(c, d),
- t.foreignKey(["a", "b"], references: "parents")
-
- // CHECK (a + b < 10),
- t.check(Column("a") + Column("b") < 10)
-
- // CHECK (a + b < 10)
- t.check(sql: "a + b < 10")
-
- // Raw SQL constraints
- t.constraint(sql: "CHECK (a + b < 10)")
- t.constraint(literal: "CHECK (a + b < \(10))")
-```
-
-[Generated columns](https://sqlite.org/gencol.html) are available with a [custom SQLite build]:
-
-```swift
- t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
- t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
-}
-```
-
-### Modify Tables
-
-SQLite lets you modify existing tables:
-
-```swift
-// ALTER TABLE referer RENAME TO referrer
-try db.rename(table: "referer", to: "referrer")
-
-// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN
-// ALTER TABLE player RENAME COLUMN url TO homeURL
-// ALTER TABLE player DROP COLUMN score
-try db.alter(table: "player") { t in
- t.add(column: "hasBonus", .boolean)
- t.rename(column: "url", to: "homeURL") // SQLite 3.25+
- t.drop(column: "score") // SQLite 3.35+
-}
-```
-
-> **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details.
-
-
-### Drop Tables
-
-Drop tables with the `drop(table:)` method:
-
-```swift
-try db.drop(table: "obsolete")
-```
-
-### Create Indexes
-
-Create indexes with the `create(index:)` method:
-
-```swift
-// CREATE INDEX byName ON users(lastName, firstName)
-try db.create(index: "byName", on: "users", columns: ["lastName, "firstName"])
-
-// CREATE UNIQUE INDEX byEmail IF NOT EXISTS ON users(email)
-try db.create(index: "byEmail", on: "users", columns: ["email"], options: [.unique, .ifNotExists])
-```
-
-Relevant SQLite documentation:
-
-- [CREATE INDEX](https://www.sqlite.org/lang_createindex.html)
-- [Indexes On Expressions](https://www.sqlite.org/expridx.html)
-- [Partial Indexes](https://www.sqlite.org/partialindex.html)
-
-
## Requests
**The query interface requests** let you fetch values from the database:
@@ -5634,7 +5309,7 @@ try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Play
try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship?
```
-When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key):
+When the table has no explicit primary key, GRDB uses the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html):
```swift
// SELECT * FROM document WHERE rowid = 1
@@ -5778,7 +5453,7 @@ try Player.deleteOne(db, key: ["email": "arthur@example.com"])
try Citizenship.deleteOne(db, key: ["citizenId": 1, "countryCode": "FR"])
```
-When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key):
+When the table has no explicit primary key, GRDB uses the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html):
```swift
// DELETE FROM document WHERE rowid = 1
@@ -6226,1110 +5901,6 @@ let playerInfos = try dbQueue.read { db in
> :bulb: In this chapter, we have learned how to use the `Decodable` protocol and its associated `CodingKeys` enum in order to dry up our code.
-Database Changes Observation
-============================
-
-**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:
-
-- [Transaction Hook](#transaction-hook): Handle transactions commits or rollbacks, one by one.
-- [ValueObservation]: Track changes of database values.
-- [DatabaseRegionObservation]: Tracking transactions that impact a database region.
-- [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation.
-- :blue_book: [Combine Support]: Automated tracking of database changes, with [Combine].
-- :blue_book: [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift).
-
-Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage.
-
-
-## Transaction Hook
-
-When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransaction(onCommit:onRollback:)` method.
-
-```swift
-try dbQueue.write { db in
- db.afterNextTransaction { db in
- print("successful commit")
- }
- ...
-} // prints "successful commit"
-```
-
-**This hook helps synchronizing the database with other resources, such as files, or system sensors.**
-
-In the example below, a [location manager](https://developer.apple.com/documentation/corelocation/cllocationmanager) starts monitoring a CLRegion if and only if it has successfully been stored in the database:
-
-```swift
-/// 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
- db.afterNextTransaction { _ in
- // locationManager prefers the main queue:
- DispatchQueue.main.async {
- locationManager.startMonitoring(for: region)
- }
- }
-
- return .commit
- }
-}
-```
-
-The method above won't trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below:
-
-```swift
-try dbQueue.write { db in
- // success
- try startMonitoring(db, region)
-
- // On error, the transaction is rollbacked, the region is not inserted, and
- // the location manager is not invoked.
- try failableMethod(db)
-}
-```
-
-
-## ValueObservation
-
-**ValueObservation tracks changes in database values**. It automatically notifies your application with fresh values whenever changes are committed in the database.
-
-Tracked changes are insertions, updates, and deletions that impact the tracked value, performed with the [query interface](#the-query-interface), or [raw SQL](#sqlite-api). 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).
-
-> **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite\_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
-
-**ValueObservation is the preferred GRDB tool for keeping your user interface synchronized with the database.** See the [Demo Applications] for sample code.
-
-- [ValueObservation Usage](#valueobservation-usage)
-- [ValueObservation Scheduling](#valueobservation-scheduling)
-- [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ...
-- [ValueObservation Sharing](#valueobservation-sharing)
-- [Specifying the Region Tracked by ValueObservation](#specifying-the-region-tracked-by-valueobservation)
-- [ValueObservation Performance](#valueobservation-performance)
-- :blue_book: [Combine Publisher](Documentation/Combine.md#database-observation)
-
-### ValueObservation Usage
-
-1. Make sure that a unique [database connection](#database-connections) is kept open during the whole duration of the observation.
-
- ValueObservation does not notify changes performed by external connections.
-
-2. Define a ValueObservation by providing a function 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)
- ```
-
- The observation can perform multiple requests, from multiple database tables, and even use raw SQL.
-
-
- Example of a more complex ValueObservation
-
- ```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)
- }
- ```
-
-
-
-
- Example of a SQL ValueObservation
-
- ```swift
- // An observation of the maximum score
- let observation = ValueObservation.tracking { db in
- try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player")
- }
- ```
-
-
-
-3. Start the observation in order to be notified of changes:
-
- ```swift
- // Start observing the database
- let cancellable: DatabaseCancellable = observation.start(
- in: dbQueue, // or dbPool
- onError: { error in print("players could not be fetched") },
- onChange: { (players: [Player]) in print("fresh players", players) })
- ```
-
-4. Stop the observation by calling the `cancel()` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deinitialized:
-
- ```swift
- cancellable.cancel()
- ```
-
-**As a convenience**, ValueObservation can be turned into an async sequence, a Combine publisher, or an RxSwift observable:
-
-
- Async sequence example
-
-[**:fire: EXPERIMENTAL**](#what-are-experimental-features)
-
-```swift
-let observation = ValueObservation.tracking(Player.fetchAll)
-for try await players in observation.values(in: dbQueue) {
- print("fresh players", players)
-}
-```
-
-
-
-
- Combine example
-
-```swift
-import Combine
-import GRDB
-
-let observation = ValueObservation.tracking(Player.fetchAll)
-
-let cancellable = observation.publisher(in: dbQueue).sink(
- receiveCompletion: { completion in ... },
- receiveValue: { (players: [Player]) in
- print("fresh players", players)
- })
-```
-
-See [Combine Support] for more information.
-
-
-
-
- RxSwift example
-
-```swift
-import GRDB
-import RxGRDB
-import RxSwift
-
-let observation = ValueObservation.tracking(Player.fetchAll)
-
-let disposable = observation.rx.observe(in: dbQueue).subscribe(
- onNext: { (players: [Player]) in
- print("fresh players", players)
- },
- onError: { error in ... })
-```
-
-See the companion library [RxGRDB] for more information.
-
-
-
-**Generally speaking**:
-
-- 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 of its component is modified (any fetched column, row, etc.). This can be [configured](#specifying-the-region-tracked-by-valueobservation).
-- By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. This can be [configured](#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](#valueobservationremoveduplicates) 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 any of those conditions is met:
- - The cancellable returned by the `start` method is cancelled or deinitialized.
- - An error occurs.
-
-Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation]. If you need to process uncommitted changes, see [TransactionObserver](#transactionobserver-protocol).
-
-
-### ValueObservation Scheduling
-
-By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously:
-
-```swift
-// The default scheduling
-let cancellable = observation.start(
- in: dbQueue,
- onError: { error in ... }, // called asynchronously on the main thread
- onChange: { value in print("fresh value") }) // called asynchronously on the main thread
-```
-
-You can change this behavior by adding a `scheduling` argument to the `start()` method.
-
-For example, `scheduling: .immediate` makes sure the initial value is notified immediately when the observation starts. It helps your application update the user interface without having to wait for any asynchronous notifications:
-
-```swift
-class PlayersViewController: UIViewController {
- private var cancellable: DatabaseCancellable?
-
- override func viewWillAppear(_ animated: Bool) {
- super.viewWillAppear(animated)
-
- // Start observing the database
- let observation = ValueObservation.tracking(Player.fetchAll)
- cancellable = observation.start(
- in: dbQueue,
- scheduling: .immediate, // <- immediate scheduler
- onError: { error in ... },
- onChange: { [weak self] (players: [Player]) in
- guard let self else { return }
- self.updateView(players)
- })
- // <- Here the view has already been updated.
- }
-
- override func viewWillDisappear(_ animated: Bool) {
- super.viewWillDisappear(animated)
-
- // Stop observing the database
- cancellable?.cancel()
- }
-
- private func updateView(_ players: [Player]) { ... }
-}
-```
-
-Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
-
-The other built-in scheduler `.async(onQueue:)` asynchronously schedules values and errors on the dispatch queue of your choice:
-
-```swift
-let queue: DispatchQueue = ...
-let cancellable = observation.start(
- in: dbQueue,
- scheduling: .async(onQueue: queue)
- onError: { error in ... }, // called asynchronously on queue
- onChange: { value in print("fresh value") }) // called asynchronously on queue
-```
-
-
-### ValueObservation Operators
-
-**Operators** are methods that transform and configure value observations so that they better fit the needs of your application.
-
-- [ValueObservation.map](#valueobservationmap)
-- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates)
-- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess)
-
-**Debugging Operators**
-
-- [ValueObservation.handleEvents](#valueobservationhandleevents)
-- [ValueObservation.print](#valueobservationprint)
-
-
-#### ValueObservation.map
-
-The `map` operator transforms the values notified by a ValueObservation.
-
-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 transformation function does not block any database access. This makes the `map` operator a tool which helps reducing [database contention](#valueobservation-performance).
-
-
-#### ValueObservation.removeDuplicates
-
-The `removeDuplicates()` and `removeDuplicates(by:)` operators filter out consecutive equal values:
-
-For example:
-
-```swift
-// An observation of distinct Player?
-let observation = ValueObservation
- .tracking { db in try Player.fetchOne(db, id: 42) }
- .removeDuplicates()
-```
-
-:bulb: **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](#row-queries) or [DatabaseValue](#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() // Row adopts Equatable
- .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:) }
-```
-
-
-#### ValueObservation.requiresWriteAccess
-
-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](#transactions-and-savepoints):
-
-```swift
-var observation = ValueObservation.tracking { db in
- // write access allowed
- ...
-}
-observation.requiresWriteAccess = true
-```
-
-When you use a [database pool](#database-pools), this flag has a performance hit.
-
-
-#### ValueObservation.handleEvents
-
-The `handleEvents` operator lets your application observe the lifetime of a ValueObservation:
-
-```swift
-let observation = ValueObservation
- .tracking { db in ... }
- .handleEvents(
- willStart: {
- // The observation starts.
- },
- willFetch: {
- // The observation will perform a database fetch.
- },
- willTrackRegion: { databaseRegion in
- // The observation starts tracking a database region.
- },
- databaseDidChange: {
- // The observation was impacted by a database change.
- },
- didReceiveValue: { value in
- // A fresh value was observed.
- // NOTE: This closure runs on an unspecified DispatchQueue.
- },
- didFail: { error in
- // The observation completes with an error.
- },
- didCancel: {
- // The observation was cancelled.
- })
-```
-
-See also [ValueObservation.print](#valueobservationprint).
-
-
-#### ValueObservation.print
-
-The `print` operator logs messages for all ValueObservation events.
-
-```swift
-let observation = ValueObservation
- .tracking { db in ... }
- .print()
-```
-
-See also [ValueObservation.handleEvents](#valueobservationhandleevents).
-
-
-### ValueObservation Sharing
-
-[**:fire: EXPERIMENTAL**](#what-are-experimental-features)
-
-**Sharing a ValueObservation allows several components of your app to be notified of database changes, in an efficient way.**
-
-A shared observation spares database resources. For example, when a database change happens, a fresh value is fetched only once, and then notified to all subscriptions.
-
-Usage:
-
-```swift
-// SharedValueObservation<[Player]>
-let sharedObservation = ValueObservation
- .tracking { db in try Player.fetchAll(db) }
- .shared(in: dbQueue)
-// ~~~~~~~~~~~~~~~~~~~~
-
-let cancellable = try sharedObservation.start(
- onError: { error in ... },
- onChange: { players: [Player] in
- print("fresh players: \(players)")
- })
-```
-
-The sharing only applies if you start observing the database from the same `SharedValueObservation` instance:
-
-```swift
-// NOT shared
-let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
-let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
-
-// Shared
-let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue)
-let cancellable1 = sharedObservation.start(...)
-let cancellable2 = sharedObservation.start(...)
-```
-
-By default, fresh values are dispatched asynchronously on the main queue. You can change this behavior (see [ValueObservation Scheduling](#valueobservation-scheduling) for more information):
-
-```swift
-let sharedObservation = ValueObservation
- .tracking { db in try Player.fetchAll(db) }
- .shared(in: dbQueue, scheduling: .immediate)
-// ~~~~~~~~~~~~~~~~~~~~~~
-```
-
-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:
-
-```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)
-// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-```
-
-> **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there is a difference you should be aware of. `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may, for example, use Combine apis:
->
-> ```swift
-> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
-> let cancellable = try sharedObservation
-> .publisher() // Turn shared observation into a Combine Publisher
-> .map { ... } // The map operator from Combine
-> .sink(...)
-> ```
-
-
-### Specifying the Region Tracked by ValueObservation
-
-While the standard `ValueObservation.tracking { db in ... }` 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.
-
-### ValueObservation Performance
-
-This chapter 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.**
-
-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](#valueobservationremoveduplicates) 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:
-
-1. :bulb: **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`. Check the sample code [above](#valueobservation-scheduling).
-
-2. :bulb: **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](#valueobservation-sharing).
-
-3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses.
-
-4. :bulb: **Tip**: When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) 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 concurrent database reads.
-
-4. :bulb: **Tip**: When the observation tracks a constant database region, create an optimized observation with the `ValueObservation.trackingConstantRegion(_:)` method.
-
- The optimization only kicks in when the observation is started from a [database pool](#database-pools): fresh values are fetched concurrently, and do not block database writes.
-
- The `ValueObservation.trackingConstantRegion(_:)` has a precondition: the observed requests must fetch from a single and constant database region. The tracked region is made of tables, columns, and, when possible, rowids of individual rows. All changes that happen outside of this region do not impact the observation.
-
- For example:
-
- ```swift
- // Tracks the full 'player' table (only)
- let observation = ValueObservation.trackingConstantRegion { db -> [Player] in
- try Player.fetchAll(db)
- }
-
- // Tracks the row with id 42 in the 'player' table (only)
- let observation = ValueObservation.trackingConstantRegion { db -> Player? in
- try Player.fetchOne(db, id: 42)
- }
-
- // Tracks the 'score' column in the 'player' table (only)
- let observation = ValueObservation.trackingConstantRegion { db -> Int? in
- try Player.select(max(Column("score"))).fetchOne(db)
- }
-
- // Tracks both the 'player' and 'team' tables (only)
- let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in
- let teams = try Team.fetchAll(db)
- let players = try Player.fetchAll(db)
- return (teams, players)
- }
- ```
-
- When you want to observe a varying database region, make sure you use the plain `ValueObservation.tracking(_:)` method instead, or else some changes will not be notified.
-
- For example, consider those three observations below that depend on some user preference. They all track a varying region, and must use `ValueObservation.tracking(_:)`:
-
- ```swift
- // Does not always track the same row in the player table.
- let observation = ValueObservation.tracking { db -> Player? in
- let pref = try Preference.fetchOne(db) ?? .default
- return try Player.fetchOne(db, id: pref.favoritePlayerId)
- }
-
- // Only tracks the 'user' table if there are some blocked emails.
- let observation = ValueObservation.tracking { db -> [User] in
- let pref = try Preference.fetchOne(db) ?? .default
- let blockedEmails = pref.blockedEmails
- return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db)
- }
-
- // Sometimes tracks the 'food' table, and sometimes the 'beverage' table.
- let observation = ValueObservation.tracking { db -> Int in
- let pref = try Preference.fetchOne(db) ?? .default
- switch pref.selection {
- case .food: return try Food.fetchCount(db)
- case .beverage: return try Beverage.fetchCount(db)
- }
- }
- ```
-
- When you are in doubt, add the [`print()` method](#valueobservationprint) to your observation before starting it, and look in your application logs for lines that start with `tracked region`. Make sure the printed database region covers the changes you expect to be tracked.
-
-
- Examples of tracked regions
-
- - `empty`: The empty region, which tracks nothing and never triggers the observation.
- - `player(*)`: The full `player` table
- - `player(id,name)`: The `id` and `name` columns of the `player` table
- - `player(id,name)[1]`: The `id` and `name` columns of the row with id 1 in the `player` table
- - `player(*),preference(*)`: Both the full `player` and `preference` tables
-
-
-
-
-## DatabaseRegionObservation
-
-**DatabaseRegionObservation notifies all [transactions](#transactions-and-savepoints) that impact the tracked [requests](#requests).**
-
-Tracked changes are insertions, updates, and deletions that impact the tracked requests, performed with the [query interface](#the-query-interface), or [raw SQL](#sqlite-api). 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).
-
-> **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), and changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
-
-DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation.
-
-
-### DatabaseRegionObservation Usage
-
-Define an observation by providing one or several requests to track:
-
-```swift
-// Track the full player table
-let observation = DatabaseRegionObservation(tracking: Player.all())
-```
-
-Then start the observation from a [database queue](#database-queues) or [pool](#database-pools):
-
-```swift
-let cancellable = try observation.start(
- in: dbQueue,
- onError: { error in ... },
- onChange: { (db: Database) in
- print("Players were changed")
- })
-}
-```
-
-Enjoy the changes notifications:
-
-```swift
-try dbQueue.write { db in
- try Player(name: "Arthur").insert(db)
-}
-// Prints "Players were changed"
-```
-
-If the `start` method is called from a writing database access method, the observation of impactful transactions starts immediately. Otherwise, it blocks the current thread until a write access can be established.
-
-**You stop the observation** by calling the `cancel()` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deinitialized:
-
-```swift
-cancellable.cancel()
-```
-
-**You can feed DatabaseRegionObservation** with any type that conforms to the [DatabaseRegionConvertible] protocol: requests, [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)
-```
-
-**As a convenience**, DatabaseRegionObservation can be turned into a Combine publisher, or an RxSwift observable:
-
-
- Combine example
-
-```swift
-import Combine
-import GRDB
-
-let observation = DatabaseRegionObservation.tracking(Player.all())
-
-let cancellable = observation.publisher(in: dbQueue).sink(
- receiveCompletion: { completion in ... },
- receiveValue: { (db: Database) in
- print("Players were changed")
- })
-```
-
-See [Combine Support] for more information.
-
-
-
-
- RxSwift example
-
-```swift
-import GRDB
-import RxGRDB
-import RxSwift
-
-let observation = DatabaseRegionObservation.tracking(Player.all())
-
-let disposable = observation.rx.changes(in: dbQueue).subscribe(
- onNext: { (db: Database) in
- print("Players were changed")
- },
- onError: { error in ... })
-```
-
-See the companion library [RxGRDB] for more information.
-
-
-
-
-## TransactionObserver Protocol
-
-The `TransactionObserver` protocol lets you **observe individual database changes and transactions**:
-
-```swift
-protocol TransactionObserver : class {
- /// Notifies a database change:
- /// - event.kind (insert, update, or delete)
- /// - event.tableName
- /// - event.rowID
- ///
- /// For performance reasons, 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 databaseDidChange(with event: DatabaseEvent)
-
- /// Filters the database changes that should be notified to the
- /// `databaseDidChange(with:)` method.
- func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
-
- /// An opportunity to rollback pending changes by throwing an error.
- func databaseWillCommit() throws
-
- /// Database changes have been committed.
- func databaseDidCommit(_ db: Database)
-
- /// Database changes have been rollbacked.
- func databaseDidRollback(_ db: Database)
-}
-```
-
-- [Activate a Transaction Observer](#activate-a-transaction-observer)
-- [Database Changes And Transactions](#database-changes-and-transactions)
-- [Filtering Database Events](#filtering-database-events)
-- [Observation Extent](#observation-extent)
-- [DatabaseRegion]
-- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
-
-
-### Activate a Transaction Observer
-
-**To activate a transaction observer, add it to the database queue or pool:**
-
-```swift
-let observer = MyObserver()
-dbQueue.add(transactionObserver: observer)
-```
-
-By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deinitialized. See [Observation Extent](#observation-extent) for more options.
-
-
-### Database Changes And Transactions
-
-**A transaction observer is notified of all database changes**: inserts, updates and deletes. 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).
-
-> **Note**: Some changes are not notified: 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).
->
-> **Note**: Transactions performed during read-only database accesses are not notified.
-
-Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) 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 transaction do not drop off the radar:
-
-```swift
-try dbQueue.inDatabase { 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 events 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 foo")
- try db.execute(sql: "UPDATE ...") // not notified
- try db.execute(sql: "ROLLBACK TO SAVEPOINT foo")
-
- 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 a protected dispatch queue, and serialized with all database updates.
->
-> **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
-
-
-[DatabaseRegionObservation] and [ValueObservation] are based on the TransactionObserver protocol.
-
-See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
-
-
-### Filtering Database Events
-
-**Transaction observers can avoid being notified of database changes they are not interested in.**
-
-The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table:
-
-```swift
-class PlayerObserver: TransactionObserver {
- func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
- // Only observe changes to the "player" table.
- return eventKind.tableName == "player"
- }
-
- func databaseDidChange(with event: DatabaseEvent) {
- // This method is only called for changes that happen to
- // the "player" table.
- }
-}
-```
-
-Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:
-
-```swift
-class PlayerScoreObserver: TransactionObserver {
- func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
- // Only observe changes to the "score" column of the "player" table.
- switch eventKind {
- case .insert(let tableName):
- return tableName == "player"
- case .delete(let tableName):
- return tableName == "player"
- case .update(let tableName, let columnNames):
- return tableName == "player" && columnNames.contains("score")
- }
- }
-}
-```
-
-When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks (except during read-only database accesses):
-
-```swift
-class PureTransactionObserver: TransactionObserver {
- func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
- // Ignore all individual changes
- return false
- }
-
- func databaseDidChange(with event: DatabaseEvent) { /* Never called */ }
- func databaseWillCommit() throws { /* Called before commit */ }
- func databaseDidRollback(_ db: Database) { /* Called on rollback */ }
- func databaseDidCommit(_ db: Database) { /* Called on commit */ }
-}
-```
-
-For more information about event filtering, see [DatabaseRegion].
-
-
-### 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 deinitialized. Meanwhile, 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` method is eventually 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 may ignore all database changes until the end of the current transaction:
-
-```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()
- }
-}
-```
-
-After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
-
-
-### DatabaseRegion
-
-A `DatabaseRegion` is a reunion of database tables, and combination of columns and rows (identified by their rowid):
-
- |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
- |-------| |-------| |-------| |-------| |-------|
- |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
- |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
- |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
- |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
-
-DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track changes in the database through the [TransactionObserver](#transactionobserver-protocol) protocol.
-
-**Note that observing a database region spots *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.
-
-For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
-
-For more details, see the [reference](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion/).
-
-
-#### The DatabaseRegionConvertible Protocol
-
-**DatabaseRegionConvertible** is a protocol for all types that can turn into a [DatabaseRegion]:
-
-```swift
-protocol DatabaseRegionConvertible {
- func databaseRegion(_ db: Database) throws -> DatabaseRegion
-}
-```
-
-All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation].
-
-For example:
-
-```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"))
-```
-
-Note that specifying a region as a request _does not run the request_. In the above example, `Player.filter(id: 1)` and `SELECT score FROM player` are never executed. They are only _compiled_ by SQLite, so that GRDB understands the tables, rows, and columns that constitute the database region.
-
-### Support for SQLite Pre-Update Hooks
-
-When SQLite is built with the SQLITE_ENABLE_PREUPDATE_HOOK option, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
-
-```swift
-protocol TransactionObserverType : class {
- #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 `` 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] and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
-
-
Encryption
==========
@@ -7846,7 +6417,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are
let name: String = row["name"]
```
- Solution: fix the contents of the database, use [NOT NULL constraints](#create-tables), or load an optional:
+ Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional:
```swift
let name: String? = row["name"]
@@ -8616,7 +7187,7 @@ When this is the case, there are two possible explanations:
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
```
-For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
+For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
@@ -8677,7 +7248,7 @@ Sample Code
**Thanks**
- [Pierlis](http://pierlis.com), where we write great software.
-- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@guidedways](https://github.com/guidedways), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
+- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](https://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@guidedways](https://github.com/guidedways), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
- [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL.
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
@@ -8685,18 +7256,58 @@ Sample Code
[URIs don't change: people change them.](https://www.w3.org/Provider/Style/URI)
+#### Adding support for missing SQL functions or operators
+
+This chapter was renamed to [Embedding SQL in Query Interface Requests].
+
+#### Advanced DatabasePool
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
+#### After Commit Hook
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
+
+#### Asynchronous APIs
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
#### Changes Tracking
This chapter has been renamed [Record Comparison].
+#### Concurrency
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
#### Customized Decoding of Database Rows
This chapter has been renamed [Beyond FetchableRecord].
+#### Customizing the Persistence Methods
+
+This chapter was replaced with [Persistence Callbacks].
+
+#### Database Changes Observation
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation).
+
+#### Database Snapshots
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
+#### DatabaseWriter and DatabaseReader Protocols
+
+This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter).
+
#### Dealing with External Connections
This chapter has been superseded by the [Sharing a Database] guide.
+#### Differences between Database Queues and Pools
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
#### Enabling FTS5 Support
This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support).
@@ -8711,6 +7322,10 @@ The [Database Observation] chapter describes the other ways to observe the datab
This chapter has [moved](Documentation/FullTextSearch.md).
+#### Guarantees and Rules
+
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+
#### Migrations
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
@@ -8731,53 +7346,25 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0.
This protocol has been renamed [TableRecord] in GRDB 3.0.
-#### Customizing the Persistence Methods
+#### Transaction Hook
-This chapter was replaced with [Persistence Callbacks].
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
-#### After Commit Hook
+#### TransactionObserver Protocol
-This chapter was replaced with [Transaction Hook].
-
-#### ValueObservation and DatabaseRegionObservation
-
-This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation].
-
-#### Concurrency
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-
-#### Guarantees and Rules
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-
-#### Differences between Database Queues and Pools
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-
-#### Advanced DatabasePool
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-
-#### Database Snapshots
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-
-#### DatabaseWriter and DatabaseReader Protocols
-
-This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter).
-
-#### Asynchronous APIs
-
-This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
#### Unsafe Concurrency APIs
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
-### Adding support for missing SQL functions or operators
+#### ValueObservation
-This chapter was renamed to [Embedding SQL in Query Interface Requests].
+This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
+
+#### ValueObservation and DatabaseRegionObservation
+
+This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation].
[Associations]: Documentation/AssociationsBasics.md
[Beyond FetchableRecord]: #beyond-fetchablerecord
@@ -8793,7 +7380,6 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests
[Full-Text Search]: Documentation/FullTextSearch.md
[Migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
-[The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key
[The userInfo Dictionary]: #the-userinfo-dictionary
[JSON Columns]: #json-columns
[FetchableRecord]: #fetchablerecord-protocol
@@ -8804,11 +7390,10 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Persistence Callbacks]: #persistence-callbacks
[persistence callbacks]: #persistence-callbacks
[TableRecord]: #tablerecord-protocol
-[ValueObservation]: #valueobservation
-[DatabaseRegionObservation]: #databaseregionobservation
-[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
-[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol
-[DatabaseRegion]: #databaseregion
+[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
+[DatabaseRegion]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion
[SQL Interpolation]: Documentation/SQLInterpolation.md
[custom SQLite build]: Documentation/CustomSQLiteBuilds.md
[Combine]: https://developer.apple.com/documentation/combine
@@ -8817,7 +7402,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Demo Applications]: Documentation/DemoApps
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing
[FAQ]: #faq
-[Database Observation]: #database-changes-observation
+[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[SQLRequest]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlrequest
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
diff --git a/Support/Info.plist b/Support/Info.plist
index 430b388d3..1cd426410 100644
--- a/Support/Info.plist
+++ b/Support/Info.plist
@@ -15,7 +15,7 @@
CFBundlePackageType
FMWK
CFBundleShortVersionString
- 6.3.1
+ 6.4.0
CFBundleSignature
????
CFBundleVersion
diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift
index aa4957c01..1f002f238 100644
--- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift
+++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift
@@ -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
diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift
index 8f6338e92..8d4333a26 100644
--- a/Tests/GRDBTests/AssociationAggregateTests.swift
+++ b/Tests/GRDBTests/AssociationAggregateTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift
index a61ae6401..161e8e148 100644
--- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift
index b7569d318..06e63f47a 100644
--- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
index 8b04ac643..b7f826ab0 100644
--- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
index 187de9ae9..49a81fa25 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift
@@ -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")
}
}
diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
index 03aceea2e..c56904732 100644
--- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
+++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift
@@ -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")
diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift
index 987d4047b..ca30569e1 100644
--- a/Tests/GRDBTests/AssociationChainRowScopesTests.swift
+++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift
@@ -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)
diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift
index e944fe86c..602edfa08 100644
--- a/Tests/GRDBTests/AssociationChainSQLTests.swift
+++ b/Tests/GRDBTests/AssociationChainSQLTests.swift
@@ -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")
}
diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift
index 40cada2b6..5feb757c9 100644
--- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift
+++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift
@@ -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()
diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift
index ddd47d74e..ffc3fcaab 100644
--- a/Tests/GRDBTests/AssociationHasManySQLTests.swift
+++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift
@@ -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")
diff --git a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift
index 52522c233..79be3fa5e 100644
--- a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift
+++ b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift
@@ -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
diff --git a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift
index a51364990..215720a6b 100644
--- a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift
+++ b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift
@@ -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)
diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
index 8d24f0a37..9165292b1 100644
--- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift
index 66d704621..f61c05772 100644
--- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift
+++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift
@@ -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")
diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift
index b27807b79..890e25267 100644
--- a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift
+++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift
@@ -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)
diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift
index 17f9c4e57..cc15b34a0 100644
--- a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift
+++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift
@@ -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)
}
diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift
index 9c1b42562..513e9cc27 100644
--- a/Tests/GRDBTests/AssociationParallelSQLTests.swift
+++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift
@@ -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")
}
}
diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift
index ba579efc3..b8e79922b 100644
--- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift
+++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift
@@ -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)")
diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift
index 7dce1d24e..3ecb21d40 100644
--- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift
+++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift
@@ -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")
diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift
index 55d929fff..602e8705c 100644
--- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift
+++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift
@@ -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 {
diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift
index 79a5dcfbf..b0d4d2714 100644
--- a/Tests/GRDBTests/DatabaseConfigurationTests.swift
+++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift
@@ -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
}
}
diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift
index 322310e7e..aa4b996fa 100644
--- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift
+++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift
@@ -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>("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>("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>("t").deleteOne(db, id: testedDates[0])
diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift
index feb1700f9..7a329c38c 100644
--- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift
+++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift
@@ -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)
}
}
diff --git a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift
index 6de662006..35c314a8e 100644
--- a/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift
+++ b/Tests/GRDBTests/DatabaseQueueInMemoryTests.swift
@@ -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") })
}
}
}
diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift
index d2935629b..fec7c02f5 100644
--- a/Tests/GRDBTests/DatabaseReaderTests.swift
+++ b/Tests/GRDBTests/DatabaseReaderTests.swift
@@ -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
}
}
diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift
index 9e6f69fc7..bec4f9cf9 100644
--- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift
+++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift
@@ -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)
// }
// }
diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift
new file mode 100644
index 000000000..eb66ff237
--- /dev/null
+++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift
@@ -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
diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift
index 874c57a6d..6730a8984 100644
--- a/Tests/GRDBTests/DatabaseSnapshotTests.swift
+++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift
@@ -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)")
}
diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift
index 80686cfc5..d898df7e7 100644
--- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift
+++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift
@@ -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")!,
diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift
index 8f2e4b1e3..76a7eb88d 100644
--- a/Tests/GRDBTests/DatabaseWriterTests.swift
+++ b/Tests/GRDBTests/DatabaseWriterTests.swift
@@ -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)")
diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift
index 2717dbc12..ad7287b4d 100644
--- a/Tests/GRDBTests/FTS4TableBuilderTests.swift
+++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift
@@ -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"])
diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift
index 156fa5c57..9bccf6c11 100644
--- a/Tests/GRDBTests/FTS5TableBuilderTests.swift
+++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift
@@ -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"])
diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift
index 4c36f1872..a8430b187 100644
--- a/Tests/GRDBTests/FetchRequestTests.swift
+++ b/Tests/GRDBTests/FetchRequestTests.swift
@@ -8,7 +8,7 @@ class FetchRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "table1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES")
try db.execute(sql: "INSERT INTO table1 DEFAULT VALUES")
@@ -25,7 +25,7 @@ class FetchRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "table1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
let derivedExpression = request > 0
@@ -41,7 +41,7 @@ class FetchRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "table1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
do {
@@ -66,7 +66,7 @@ class FetchRequestTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "table1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
let sqlRequest: SQLRequest = "SELECT * FROM (\(request))"
diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift
index 9de30a497..61f94e027 100644
--- a/Tests/GRDBTests/JoinSupportTests.swift
+++ b/Tests/GRDBTests/JoinSupportTests.swift
@@ -216,26 +216,26 @@ class JoinSupportTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "t1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("name", .text).notNull()
}
try db.create(table: "t2") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("t1id", .integer).notNull().references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
t.uniqueKey(["t1id", "name"])
}
try db.create(table: "t3") { t in
- t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade)
+ t.primaryKey("t1id", .integer).references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
t.column("ignored", .integer)
}
try db.create(table: "t4") { t in
- t.column("t1id", .integer).primaryKey().references("t1", onDelete: .cascade)
+ t.primaryKey("t1id", .integer).references("t1", onDelete: .cascade)
t.column("name", .text).notNull()
}
try db.create(table: "t5") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("t3id", .integer).references("t3", onDelete: .cascade)
t.column("t4id", .integer).references("t4", onDelete: .cascade)
t.column("name", .text).notNull()
diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift
index bc974114b..bfa1bf32a 100644
--- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift
+++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift
@@ -31,7 +31,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "players") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("name", .text)
t.column("score", .integer)
t.column("creationDate", .datetime)
diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift
index 1caa68b1c..5ebae5d26 100644
--- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift
+++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift
@@ -119,7 +119,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -139,7 +139,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -158,7 +158,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -202,7 +202,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
try dbQueue.writeWithoutTransaction { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("email", .text).unique()
}
@@ -254,7 +254,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -274,7 +274,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -294,7 +294,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
@@ -314,7 +314,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
// Insert
diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift
index 13bd726e6..5b708c5c9 100644
--- a/Tests/GRDBTests/MutablePersistableRecordTests.swift
+++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift
@@ -349,6 +349,49 @@ class MutablePersistableRecordTests: GRDBTestCase {
}
}
+ func testUpdateWithoutExplicitPrimaryKeyButWithExplicitRowIDSupport() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.execute(sql: "CREATE TABLE record(name)")
+
+ struct Record: Codable, MutablePersistableRecord {
+ var rowID: Int64?
+ var name: String
+ mutating func didInsert(_ inserted: InsertionSuccess) {
+ rowID = inserted.rowID
+ }
+ }
+
+ var record1 = Record(name: "Arthur")
+ var record2 = Record(name: "Barbara")
+ try record1.insert(db)
+ try record2.insert(db)
+ record1.name = "Craig"
+ try record1.update(db)
+
+ let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid")
+ XCTAssertEqual(names, ["Craig", "Barbara"])
+ }
+ }
+
+ func testUpdateWithoutExplicitPrimaryKeyAndWithoutExplicitRowIDSupport() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.execute(sql: "CREATE TABLE record(name)")
+
+ struct Record: Codable, PersistableRecord {
+ var name: String
+ }
+
+ let record = Record(name: "Arthur")
+ try record.insert(db)
+ do {
+ try record.update(db)
+ XCTFail("Expected PersistenceError")
+ } catch is PersistenceError { }
+ }
+ }
+
func testUpdateMutablePersistableRecordPerson() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -501,6 +544,48 @@ class MutablePersistableRecordTests: GRDBTestCase {
}
}
+ func testDeleteWithoutExplicitPrimaryKeyButWithExplicitRowIDSupport() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.execute(sql: "CREATE TABLE record(name)")
+
+ struct Record: Codable, MutablePersistableRecord {
+ var rowID: Int64?
+ var name: String
+ mutating func didInsert(_ inserted: InsertionSuccess) {
+ rowID = inserted.rowID
+ }
+ }
+
+ var record1 = Record(name: "Arthur")
+ var record2 = Record(name: "Barbara")
+ try record1.insert(db)
+ try record2.insert(db)
+ try record1.delete(db)
+
+ let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid")
+ XCTAssertEqual(names, ["Barbara"])
+ }
+ }
+
+ func testDeleteWithoutExplicitPrimaryKeyAndWithoutExplicitRowIDSupport() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.execute(sql: "CREATE TABLE record(name)")
+
+ struct Record: Codable, PersistableRecord {
+ var name: String
+ }
+
+ let record = Record(name: "Arthur")
+ try record.insert(db)
+ try XCTAssertFalse(record.delete(db))
+
+ let names = try String.fetchAll(db, sql: "SELECT name FROM record ORDER BY rowid")
+ XCTAssertEqual(names, ["Arthur"])
+ }
+ }
+
func testDeleteMutablePersistableRecordPerson() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -1037,7 +1122,7 @@ class MutablePersistableRecordTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .text)
t.column("b", .text)
t.column("c", .integer).notNull().defaults(to: 123)
@@ -1072,7 +1157,7 @@ class MutablePersistableRecordTests: GRDBTestCase {
// Expect database errors when missing columns must have a value
try db.drop(table: "records")
try db.create(table: "records") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .text)
t.column("b", .text).notNull()
}
diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift
index 7cb3b32a6..29c8fcaf7 100644
--- a/Tests/GRDBTests/PoolTests.swift
+++ b/Tests/GRDBTests/PoolTests.swift
@@ -14,7 +14,7 @@ class PoolTests: XCTestCase {
// Get and release element
let first = try pool.get()
XCTAssertEqual(first.element, 1)
- first.release()
+ first.release(.reuse)
// Get recycled element
let second = try pool.get()
@@ -24,17 +24,46 @@ class PoolTests: XCTestCase {
let third = try pool.get()
XCTAssertEqual(third.element, 2)
- // Release elements
- second.release()
- third.release()
+ // Reuse elements
+ second.release(.reuse)
+ third.release(.reuse)
// Get and release recycled elements
let fourth = try pool.get()
XCTAssertEqual(fourth.element, 1)
let fifth = try pool.get()
XCTAssertEqual(fifth.element, 2)
- fourth.release()
- fifth.release()
+ fourth.release(.reuse)
+ fifth.release(.reuse)
+ }
+
+ func testElementsCanBeDiscarded() throws {
+ let pool = makeCounterPool(maximumCount: 2)
+
+ // Get and release element
+ let first = try pool.get()
+ XCTAssertEqual(first.element, 1)
+ first.release(.reuse)
+
+ // Get recycled element
+ let second = try pool.get()
+ XCTAssertEqual(second.element, 1)
+
+ // Get new element
+ let third = try pool.get()
+ XCTAssertEqual(third.element, 2)
+
+ // Reuse second, discard third
+ second.release(.reuse)
+ third.release(.discard)
+
+ // Get and release recycled elements
+ let fourth = try pool.get()
+ XCTAssertEqual(fourth.element, 1)
+ let fifth = try pool.get()
+ XCTAssertEqual(fifth.element, 3)
+ fourth.release(.reuse)
+ fifth.release(.reuse)
}
func testRemoveAll() throws {
@@ -49,17 +78,17 @@ class PoolTests: XCTestCase {
// removeAll is not locked by used elements
pool.removeAll()
- // Release elements
- first.release()
- second.release()
+ // Reuse elements
+ first.release(.reuse)
+ second.release(.reuse)
// Get and release new elements
let third = try pool.get()
XCTAssertEqual(third.element, 3)
let fourth = try pool.get()
XCTAssertEqual(fourth.element, 4)
- third.release()
- fourth.release()
+ third.release(.reuse)
+ fourth.release(.reuse)
}
func testBarrierLocksElements() throws {
@@ -85,7 +114,7 @@ class PoolTests: XCTestCase {
let first = try! pool.get()
element = first.element
- first.release()
+ first.release(.reuse)
expectation.fulfill()
s3.signal()
}
@@ -93,7 +122,7 @@ class PoolTests: XCTestCase {
// Assert that get() is blocked
waitForExpectations(timeout: 1)
- // Release barrier
+ // Reuse barrier
s2.signal()
// Wait for get() to complete
@@ -121,8 +150,8 @@ class PoolTests: XCTestCase {
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
- // Release element
- first.release()
+ // Reuse element
+ first.release(.reuse)
// Wait for barrier to complete
s.wait()
@@ -130,7 +159,7 @@ class PoolTests: XCTestCase {
// Get and release recycled element
let second = try pool.get()
XCTAssertEqual(second.element, 1)
- second.release()
+ second.release(.reuse)
}
func testBarrierIsLockedByOneUsedElementOutOfTwo() throws {
@@ -145,8 +174,8 @@ class PoolTests: XCTestCase {
let second = try pool.get()
XCTAssertEqual(second.element, 2)
- // Release first element
- first.release()
+ // Reuse first element
+ first.release(.reuse)
let s = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
@@ -158,8 +187,8 @@ class PoolTests: XCTestCase {
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
- // Release second element
- second.release()
+ // Reuse second element
+ second.release(.reuse)
// Wait for barrier to complete
s.wait()
@@ -167,7 +196,7 @@ class PoolTests: XCTestCase {
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
- third.release()
+ third.release(.reuse)
}
func testBarrierIsLockedByTwoUsedElementsOutOfTwo() throws {
@@ -192,9 +221,9 @@ class PoolTests: XCTestCase {
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
- // Release elements
- first.release()
- second.release()
+ // Reuse elements
+ first.release(.reuse)
+ second.release(.reuse)
// Wait for barrier to complete
s.wait()
@@ -202,7 +231,7 @@ class PoolTests: XCTestCase {
// Get and release recycled element
let third = try pool.get()
XCTAssertEqual(third.element, 1)
- third.release()
+ third.release(.reuse)
}
func testBarrierRemoveAll() throws {
@@ -226,8 +255,8 @@ class PoolTests: XCTestCase {
// Assert that barrier is blocked
waitForExpectations(timeout: 1)
- // Release element
- first.release()
+ // Reuse element
+ first.release(.reuse)
// Wait for barrier to complete
s.wait()
@@ -235,6 +264,6 @@ class PoolTests: XCTestCase {
// Get and release new element
let second = try pool.get()
XCTAssertEqual(second.element, 2)
- second.release()
+ second.release(.reuse)
}
}
diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift
index f68746e10..959a1d4f4 100644
--- a/Tests/GRDBTests/SelectStatementTests.swift
+++ b/Tests/GRDBTests/SelectStatementTests.swift
@@ -312,25 +312,25 @@ class SelectStatementTests : GRDBTestCase {
}
try db.create(table: "table1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("id3", .integer).references("table3", column: "id", onDelete: .cascade, onUpdate: .cascade)
t.column("id4", .integer).references("table4", column: "id", onDelete: .setNull, onUpdate: .cascade)
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "table2") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .integer)
t.column("b", .integer)
}
try db.create(table: "table3") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
try db.create(table: "table4") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
try db.create(table: "table5") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
try db.execute(sql: "CREATE TRIGGER table5trigger AFTER INSERT ON table5 BEGIN INSERT INTO table1 (id3, id4, a, b) VALUES (NULL, NULL, 0, 0); END")
diff --git a/Tests/GRDBTests/SingletonRecordTest.swift b/Tests/GRDBTests/SingletonRecordTest.swift
index d526a4a2b..13bf62384 100644
--- a/Tests/GRDBTests/SingletonRecordTest.swift
+++ b/Tests/GRDBTests/SingletonRecordTest.swift
@@ -41,7 +41,7 @@ class SingletonRecordTest: GRDBTestCase {
// Table creation
try db.create(table: "appConfiguration") { t in
// 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("text", .text).notNull()
diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift
index e63c134d6..eebe2d597 100644
--- a/Tests/GRDBTests/TableDefinitionTests.swift
+++ b/Tests/GRDBTests/TableDefinitionTests.swift
@@ -8,7 +8,7 @@ class TableDefinitionTests: GRDBTestCase {
try dbQueue.inDatabase { db in
// Simple table creation
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("name", .text)
}
@@ -25,7 +25,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
assertEqualSQL(lastSQLQuery!, """
CREATE TEMPORARY TABLE IF NOT EXISTS "test" (\
@@ -36,7 +36,7 @@ class TableDefinitionTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.create(table: "test2", options: [.temporary, .ifNotExists, .withoutRowID]) { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
}
assertEqualSQL(lastSQLQuery!, """
CREATE TEMPORARY TABLE IF NOT EXISTS "test2" (\
@@ -59,7 +59,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test3", options: [.strict]) { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .integer)
t.column("b", .real)
t.column("c", .text)
@@ -145,7 +145,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey(onConflict: .fail)
+ t.primaryKey("id", .integer, onConflict: .fail)
}
assertEqualSQL(lastSQLQuery!, """
CREATE TABLE "test" (\
@@ -156,6 +156,7 @@ class TableDefinitionTests: GRDBTestCase {
}
try dbQueue.inTransaction { db in
try db.create(table: "test") { t in
+ // legacy api
t.column("id", .integer).primaryKey(autoincrement: true)
}
assertEqualSQL(lastSQLQuery!, """
@@ -332,7 +333,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
- t.column("name", .text).primaryKey()
+ t.primaryKey("name", .text)
t.column("email", .text).unique()
}
try db.create(table: "pkless") { t in
@@ -393,6 +394,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inTransaction { db in
try db.create(table: "test") { t in
+ // Legacy api
t.primaryKey(["a", "b"])
t.column("a", .text)
t.column("b", .text)
@@ -408,6 +410,27 @@ class TableDefinitionTests: GRDBTestCase {
}
try dbQueue.inTransaction { db in
try db.create(table: "test") { t in
+ t.column("regular1")
+ t.primaryKey {
+ t.column("a", .text)
+ t.column("b", .text)
+ }
+ t.column("regular2")
+ }
+ assertEqualSQL(lastSQLQuery!, """
+ CREATE TABLE "test" (\
+ "regular1", \
+ "a" TEXT NOT NULL, \
+ "b" TEXT NOT NULL, \
+ "regular2", \
+ PRIMARY KEY ("a", "b")\
+ )
+ """)
+ return .rollback
+ }
+ try dbQueue.inTransaction { db in
+ try db.create(table: "test") { t in
+ // Legacy api
t.primaryKey(["a", "b"], onConflict: .fail)
t.column("a", .text)
t.column("b", .text)
@@ -421,6 +444,22 @@ class TableDefinitionTests: GRDBTestCase {
""")
return .rollback
}
+ try dbQueue.inTransaction { db in
+ try db.create(table: "test") { t in
+ t.primaryKey(onConflict: .fail) {
+ t.column("a", .text).defaults(to: "O'Reilly")
+ t.column("b", .text)
+ }
+ }
+ assertEqualSQL(lastSQLQuery!, """
+ CREATE TABLE "test" (\
+ "a" TEXT NOT NULL DEFAULT 'O''Reilly', \
+ "b" TEXT NOT NULL, \
+ PRIMARY KEY ("a", "b") ON CONFLICT FAIL\
+ )
+ """)
+ return .rollback
+ }
}
func testTableUniqueKey() throws {
@@ -449,9 +488,10 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
- t.primaryKey(["a", "b"])
- t.column("a", .text)
- t.column("b", .text)
+ t.primaryKey {
+ t.column("a", .text)
+ t.column("b", .text)
+ }
}
try db.create(table: "child") { t in
t.foreignKey(["c", "d"], references: "parent", onDelete: .cascade, onUpdate: .cascade)
@@ -526,7 +566,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test1") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("id2", .integer).references("test1")
}
assertEqualSQL(lastSQLQuery!, """
@@ -536,34 +576,69 @@ class TableDefinitionTests: GRDBTestCase {
)
""")
- try db.create(table: "test2") { t in
+ try db.create(table: "test2_legacy") { t in
+ // Legacy api
t.column("id", .integer)
- t.column("id2", .integer).references("test2")
+ t.column("id2", .integer).references("test2_legacy")
t.primaryKey(["id"])
}
assertEqualSQL(lastSQLQuery!, """
- CREATE TABLE "test2" (\
+ CREATE TABLE "test2_legacy" (\
"id" INTEGER, \
- "id2" INTEGER REFERENCES "test2"("id"), \
+ "id2" INTEGER REFERENCES "test2_legacy"("id"), \
PRIMARY KEY ("id")\
)
""")
- try db.create(table: "test3") { t in
+ try db.create(table: "test2") { t in
+ t.column("id2", .integer).references("test2")
+ t.primaryKey {
+ t.column("id", .integer)
+ }
+ }
+ assertEqualSQL(lastSQLQuery!, """
+ CREATE TABLE "test2" (\
+ "id2" INTEGER REFERENCES "test2"("id"), \
+ "id" INTEGER NOT NULL, \
+ PRIMARY KEY ("id")\
+ )
+ """)
+
+ try db.create(table: "test3Legacy") { t in
t.column("a", .integer)
t.column("b", .integer)
t.column("c", .integer)
t.column("d", .integer)
- t.foreignKey(["c", "d"], references: "test3")
+ t.foreignKey(["c", "d"], references: "test3Legacy")
t.primaryKey(["a", "b"])
}
assertEqualSQL(lastSQLQuery!, """
- CREATE TABLE "test3" (\
+ CREATE TABLE "test3Legacy" (\
"a" INTEGER, \
"b" INTEGER, \
"c" INTEGER, \
"d" INTEGER, \
PRIMARY KEY ("a", "b"), \
+ FOREIGN KEY ("c", "d") REFERENCES "test3Legacy"("a", "b")\
+ )
+ """)
+
+ try db.create(table: "test3") { t in
+ t.column("c", .integer)
+ t.column("d", .integer)
+ t.foreignKey(["c", "d"], references: "test3")
+ t.primaryKey {
+ t.column("a", .integer)
+ t.column("b", .integer)
+ }
+ }
+ assertEqualSQL(lastSQLQuery!, """
+ CREATE TABLE "test3" (\
+ "c" INTEGER, \
+ "d" INTEGER, \
+ "a" INTEGER NOT NULL, \
+ "b" INTEGER NOT NULL, \
+ PRIMARY KEY ("a", "b"), \
FOREIGN KEY ("c", "d") REFERENCES "test3"("a", "b")\
)
""")
@@ -774,7 +849,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("name", .text)
}
XCTAssertTrue(try db.tableExists("test"))
@@ -790,7 +865,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .text)
t.column("b", .text)
}
@@ -813,7 +888,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("a", .text)
t.column("b", .text)
}
@@ -830,7 +905,7 @@ class TableDefinitionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "test") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("name", .text)
}
try db.create(index: "test_on_name", on: "test", columns: ["name"])
diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
index 3553cec4c..19182f7aa 100644
--- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
+++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift
@@ -328,7 +328,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
try dbQueue.inTransaction { db in
struct Player: TableRecord { }
try db.create(table: "player") { t in
- t.column("a", .integer).notNull().primaryKey()
+ t.primaryKey("a", .integer)
}
try XCTAssertFalse(Player.exists(db, key: 1))
@@ -343,7 +343,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
try dbQueue.inTransaction { db in
struct Player: TableRecord { }
try db.create(table: "player") { t in
- t.column("id", .text).notNull().primaryKey()
+ t.primaryKey("id", .text)
}
try XCTAssertFalse(Player.exists(db, key: "foo"))
@@ -397,7 +397,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
var id: String
}
try db.create(table: "player") { t in
- t.column("id", .text).notNull().primaryKey()
+ t.primaryKey("id", .text)
}
try XCTAssertFalse(Player.exists(db, id: "foo"))
diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift
index 375649d4d..6b67e8092 100644
--- a/Tests/GRDBTests/TableTests.swift
+++ b/Tests/GRDBTests/TableTests.swift
@@ -728,7 +728,7 @@ class TableTests: GRDBTestCase {
t.uniqueKey(["b", "c"])
}
try db.create(table: "country") { t in
- t.column("code", .text).notNull().primaryKey()
+ t.primaryKey("code", .text)
}
try db.create(table: "document") { t in
t.column("a")
@@ -883,7 +883,7 @@ class TableTests: GRDBTestCase {
t.uniqueKey(["b", "c"])
}
try db.create(table: "country") { t in
- t.column("code", .text).notNull().primaryKey()
+ t.primaryKey("code", .text)
}
try db.create(table: "document") { t in
t.column("a")
diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift
index 35f6da8cd..d5085dcc9 100644
--- a/Tests/GRDBTests/ValueObservationPrintTests.swift
+++ b/Tests/GRDBTests/ValueObservationPrintTests.swift
@@ -54,6 +54,9 @@ class ValueObservationPrintTests: GRDBTestCase {
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
+ try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool())
+#endif
}
func test_readonly_success_immediateScheduling() throws {
@@ -88,11 +91,17 @@ class ValueObservationPrintTests: GRDBTestCase {
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
+ try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool())
+#endif
}
func test_readonly_failure_asynchronousScheduling() throws {
struct TestError: Error { }
- _ = try makeDatabasePool(filename: "test")
+ let dbPool = try makeDatabasePool(filename: "test")
+ // workaround Xcode 14.1 compiler (???) bug: database is not in the WAL
+ // mode unless the pool is used.
+ try dbPool.write { _ in }
func test(_ dbReader: some DatabaseReader) throws {
let logger = TestStream()
@@ -120,11 +129,17 @@ class ValueObservationPrintTests: GRDBTestCase {
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
+ try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool())
+#endif
}
func test_readonly_failure_immediateScheduling() throws {
struct TestError: Error { }
- _ = try makeDatabasePool(filename: "test")
+ let dbPool = try makeDatabasePool(filename: "test")
+ // workaround Xcode 14.1 compiler (???) bug: database is not in the WAL
+ // mode unless the pool is used.
+ try dbPool.write { _ in }
func test(_ dbReader: some DatabaseReader) throws {
let logger = TestStream()
@@ -152,6 +167,9 @@ class ValueObservationPrintTests: GRDBTestCase {
try test(makeDatabaseQueue(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config))
try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot())
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
+ try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool())
+#endif
}
// MARK: - Writeonly
diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift
index 5b01e8e63..dccf8c445 100644
--- a/Tests/GRDBTests/ValueObservationRowTests.swift
+++ b/Tests/GRDBTests/ValueObservationRowTests.swift
@@ -126,7 +126,7 @@ class ValueObservationRowTests: GRDBTestCase {
[["content":"foo"]]],
setup: { db in
try db.create(table: "documents") { t in
- t.column("id", .integer).primaryKey()
+ t.primaryKey("id", .integer)
t.column("content", .text)
}
try db.create(virtualTable: "ft_documents", using: FTS4()) { t in
diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift
index d540d6839..3a2a7d49a 100644
--- a/Tests/GRDBTests/ValueObservationTests.swift
+++ b/Tests/GRDBTests/ValueObservationTests.swift
@@ -313,7 +313,7 @@ class ValueObservationTests: GRDBTestCase {
}
}
}
-
+
// MARK: - Snapshot Optimization
func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws {
@@ -421,13 +421,13 @@ class ValueObservationTests: GRDBTestCase {
}
let expectedCounts: [Int]
- #if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
- // Optimization not available
- expectedCounts = [0, 0, 1]
- #else
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
// Optimization available
expectedCounts = [0, 1]
- #endif
+#else
+ // Optimization not available
+ expectedCounts = [0, 0, 1]
+#endif
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
@@ -471,13 +471,13 @@ class ValueObservationTests: GRDBTestCase {
}
let expectedCounts: [Int]
- #if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
- // Optimization not available
- expectedCounts = [0, 0, 1]
- #else
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
// Optimization available
expectedCounts = [0, 1]
- #endif
+#else
+ // Optimization not available
+ expectedCounts = [0, 0, 1]
+#endif
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
@@ -496,6 +496,33 @@ class ValueObservationTests: GRDBTestCase {
}
}
+ // MARK: - Snapshot Observation
+
+#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
+ func testDatabaseSnapshotPoolObservation() throws {
+ let dbPool = try makeDatabasePool()
+ try dbPool.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
+
+ let expectation = XCTestExpectation()
+ expectation.assertForOverFulfill = false
+
+ let observation = ValueObservation.trackingConstantRegion { db in
+ try db.registerAccess(to: Table("t"))
+ expectation.fulfill()
+ return try DatabaseSnapshotPool(db)
+ }
+
+ let recorder = observation.record(in: dbPool)
+ wait(for: [expectation], timeout: 5)
+ try dbPool.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") }
+
+ let results = try wait(for: recorder.next(2), timeout: 5)
+ XCTAssertEqual(results.count, 2)
+ try XCTAssertEqual(results[0].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 0)
+ try XCTAssertEqual(results[1].read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, 1)
+ }
+#endif
+
// MARK: - Cancellation
func testCancellableLifetime() throws {