diff --git a/.gitignore b/.gitignore index c04845a86..cd1383aee 100644 --- a/.gitignore +++ b/.gitignore @@ -112,3 +112,6 @@ Tests/SPM/Packages # Ruby .ruby-version + +# Test products +Tests/products diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c9515d2d..bafd7f8a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.13.x` Releases - [5.13.0](#5130) - `5.12.x` Releases - [5.12.0](#5120) - `5.11.x` Releases - [5.11.0](#5110) - `5.10.x` Releases - [5.10.0](#5100) @@ -79,6 +80,24 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 5.13.0 + +Released November 7, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.12.0...v5.13.0) + +- **Breaking Change**: [#1076](https://github.com/groue/GRDB.swift/pull/1076) by [@groue](https://github.com/groue): Require Swift 5.3 and Xcode 12 +- **New**: :star: [#1088](https://github.com/groue/GRDB.swift/pull/1088) by [@groue](https://github.com/groue): Shared ValueObservation +- **New**: :star: [#1095](https://github.com/groue/GRDB.swift/pull/1095) by [@groue](https://github.com/groue): Precise foreign key checks for migrations +- **New**: [#1078](https://github.com/groue/GRDB.swift/pull/1078) by [@groue](https://github.com/groue): Non-mutating persistence methods `saved` and `inserted`, and existence-checking methods `isEmpty` and `exists` +- **New**: `DatabasePool.erase()` prevents concurrent reads until it has completed. +- **New**: The `close()` method allows precise closing of database connections. +- **New**: Filtering records by single-column primary key now properly encodes dates and uuids according to the customized strategies (`filter(id:)`, `deleteAll(_:keys:)`, etc.) +- **New**: `DatabaseUUIDEncodingStrategy.lowercaseString` can encode UUID as a lowercased string. For clarity, the `string` strategy has been deprecated and renamed `uppercaseString`. +- **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) got a major overhaul. +- **Documentation Update**: :star: A new [ValueObservation Sharing](README.md#valueobservation-sharing) chapter describes how to share database observations and spare database resources. +- **Documentation Update**: :star: The [Migrations](Documentation/Migrations.md) guide tells how you can mitigate slow foreign key checks during schema changes. +- **Documentation Update**: The [Date and UUID Coding Strategies](README.md#date-and-uuid-coding-strategies) chapter describes the new support for date and uuid primary key coding in requests by single-column primary key. +- **Documentation Update**: A new [Testing for Record Existence](README.md#testing-for-record-existence) chapter describes the new `request.isEmpty(_:)`, `Record.exists(_:id:)` and `Record.exists(_:key:)` methods. + ## 5.12.0 Released September 25, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.11.0...v5.12.0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b6c01ccb..0a0679b2a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -118,7 +118,7 @@ Starting points: GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places: -- [Concurrency Guide](README.md#concurrency) +- [Concurrency Guide](Documentation/Concurrency.md) - [Why Adopt GRDB?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md#strong-and-clear-multi-threading-guarantees) - [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) - [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time) @@ -313,7 +313,7 @@ Features that blur this focus are non-goals: [Non-Goals]: #non-goals [Report Bugs]: #report-bugs [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB -[Concurrency]: #concurrency +[Concurrency]: Documentation/Concurrency.md [Sponsoring and Professional Support]: #sponsoring-and-professional-support [SQL Console in the Debugger]: #sql-console-in-the-debugger [SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container diff --git a/Documentation/Combine.md b/Documentation/Combine.md index b83f71835..ffa19ca8f 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -191,7 +191,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above). -When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](../README.md#advanced-databasepool) for more information. +When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](Concurrency.md#advanced-databasepool) for more information. When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied. @@ -205,6 +205,7 @@ It completes on the main queue, unless you provide a specific [scheduler] to the Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter. - [`ValueObservation.publisher(in:scheduling:)`] +- [`SharedValueObservation.publisher()`] - [`DatabaseRegionObservation.publisher(in:)`] @@ -250,6 +251,22 @@ This publisher has the same behavior as ValueObservation: See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information. +#### `SharedValueObservation.publisher()` + +[SharedValueObservation] tracks changes in database values. You can turn it into a Combine publisher: + +```swift +let sharedObservation = ValueObservation + .tracking { db in try Player.fetchAll(db) } + .shared(in: dbQueue) + +// A publisher with output [Player] and failure Error +let publisher = sharedObservation.publisher() +``` + +This publisher has the same behavior as SharedValueObservation. + + #### `DatabaseRegionObservation.publisher(in:)` [DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher: @@ -374,8 +391,10 @@ let cancellable = hallOfFamePublisher.sink( [Demo Application]: DemoApps/GRDBCombineDemo/README.md [SQLite]: http://sqlite.org [ValueObservation]: ../README.md#valueobservation +[SharedValueObservation]: ../README.md#valueobservation-sharing [`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin [`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling +[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher [`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue [`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates [`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread @@ -383,5 +402,5 @@ let cancellable = hallOfFamePublisher.sink( [configured]: ../README.md#databasepool-configuration [database pool]: ../README.md#database-pools [database queue]: ../README.md#database-queues -[database snapshot]: ../README.md#database-snapshots +[database snapshot]: Concurrency.md#database-snapshots [scheduler]: https://developer.apple.com/documentation/combine/scheduler diff --git a/Documentation/Concurrency.md b/Documentation/Concurrency.md new file mode 100644 index 000000000..9f27bdf5f --- /dev/null +++ b/Documentation/Concurrency.md @@ -0,0 +1,517 @@ +:twisted_rightwards_arrows: Concurrency +======================================= + +**GRDB helps your app deal with SQLite concurrency.** + +If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated [Sharing a Database] guide after this one. + +**In all cases, and first and foremost, follow the [Concurrency Rules] right from the start.** + +The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code. + +- [Concurrency Rules] +- [Synchronous and Asynchronous Database Accesses] +- [Safe and Unsafe Database Accesses] +- [Differences between Database Queues and Pools] +- [Concurrent Thinking] +- [Advanced DatabasePool] +- [Database Snapshots] +- [Sharing a Database] + + +## Concurrency Rules + +**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side! + +:point_up: **[Rule 1](#rule-1): Connect to any database file only once** + +Open one single [DatabaseQueue] or [DatabasePool] per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file. + +> *Why does this rule exist?* - Since SQLite does not support parallel writes, each [DatabaseQueue] and [DatabasePool] makes sure application threads perform writes one by one, without overlap. +> +> *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database. +> +> *What if you do not follow this rule?* +> +> - You will not be able to use the [Database Observation] features. +> - You will see SQLite errors with code 5 ([SQLITE_BUSY]). + +:point_up: **[Rule 2](#rule-2): Mind your transactions** + +Database operations that are grouped in an SQLite transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions have an interesting property as well: they guarantee a stable and immutable view of the database[^1], and do not see changes performed by eventual concurrent writes. In other words, transactions are the one and single tool that helps you enforce and rely on the important invariants of your database (such as "all credits have a matching debit", or "all books have an author"). + +**You are responsible**, in your Swift code, for delimiting transactions. You do so by grouping database accesses inside a pair of `{ db in ... }` brackets: + +```swift +try dbQueue.write { db in /* Inside a transaction */ } +try dbQueue.read { db in /* Inside a transaction */ } +let observation = ValueObservation.tracking { db in /* 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. +> +> *Practical advice* - See below a correct example, as well as frequent mistakes you should avoid: +> +>
Sample code +> +> In order to insert a money transfer in the database, in a way that enforces the "all credits have a matching debit" invariant, you can write: +> +> ```swift +> // CORRECT: the "all credits have a matching debit" invariant is preserved. +> do { +> try dbQueue.write { db in +> try credit.insert(db) +> try debit.insert(db) +> } +> } catch { +> print("An error occurred: \(error)") +> } +> ``` +> +> A frequent mistake is to forget about grouping inside a pair of `{ db in ... }` brackets: +> +> ```swift +> // INCORRECT. Related database operations are not grouped inside +> // one transaction. The invariant is not enforced. +> do { +> try dbQueue.write { db in try credit.insert(db) } +> try dbQueue.write { db in try debit.insert(db) } +> } catch { +> print("An error occurred: \(error)") +> } +> ``` +> +> Another frequent mistake is to catch database errors at the wrong place: +> +> ```swift +> // INCORRECT. Related database operations are not grouped inside +> // one transaction, and a failed operation does not prevent +> // subsequent operations from being performed. The invariant is +> // not enforced. +> do { +> try dbQueue.write { db in try credit.insert(db) } +> } catch { +> print("An error occurred: \(error)") +> } +> +> do { +> try dbQueue.write { db in try debit.insert(db) } +> } catch { +> print("An error occurred: \(error)") +> } +> ``` +> +>
+> +> *What if you do not follow this rule?* - You will see broken database invariants, at runtime, and when your apps wakes up after a crash. You may have a hard time fixing this mess. + + +## Synchronous and Asynchronous Database Accesses + +**You can access the database from any thread, in a synchronous or asynchronous way.** + +:arrow_right: **A sync access blocks the current thread** until the database operations are completed: + +```swift +let playerCount = try dbQueue.read { db in + try Player.fetchCount(db) +} + +let newPlayerCount = try dbQueue.write { db -> Int in + try Player(id: 12, name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +It is a programmer error to perform a sync access from any other database access (this restriction can be lifted: see [Safe and Unsafe Database Accesses]): + +```swift +try dbQueue.write { db in + // Fatal Error: Database methods are not reentrant. + try dbQueue.write { db in ... } +} +``` + +:twisted_rightwards_arrows: **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are three ways to access the database asynchronously: + +
+ Combine publishers + +```swift +let playerCountPublisher = dbQueue.readPublisher { db in + try Player.fetchCount(db) +} + +let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in + try Player(id: 12, name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +Those publishers do not access the database until they are subscribed. They complete on the main dispatch queue by default. See [GRDB ❤️ Combine]. + +
+ +
+ RxSwift observables + +```swift +let playerCountObservable = dbQueue.rx.read { db in + try Player.fetchCount(db) +} + +let newPlayerCountObservable = dbQueue.rx.write { db -> Int in + try Player(id: 12, name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +Those observables do not access the database until they are subscribed. They complete on the main dispatch queue by default. See the companion library [RxGRDB]. + +
+ +
+ Completion blocks + +```swift +dbQueue.asyncRead { (dbResult: Result) in + do { + // Maybe read access could not be established + let db = try dbResult.get() + let playerCount = try Player.fetchCount(db) + ... // Handle playerCount + } catch { + ... // Handle error + } +} + +dbQueue.asyncWrite({ (db: Database) -> Int in + try Player(id: 12, name: "Arthur").insert(db) + return try Player.fetchCount(db) +}, completion: { (db: Database, result: Result) in + // Handle write transaction result: + switch result { + case let .success(newPlayerCount): + ... // Handle newPlayerCount + case let .failure(error): + ... // Handle error + } +}) +``` + +
+ +During one async access, all individual database operations grouped inside (fetch, insert, etc.) are synchronous: + +```swift +// One asynchronous access... +dbQueue.writePublisher { db in + // ... always performs synchronous database operations: + try Player(...).insert(db) + try Player(...).insert(db) + let players = try Player.fetchAll(db) +} +``` + +This is true for all async techniques. + +This prevents the database operations from various concurrent accesses from being interleaved, with disastrous consequences. For example, one access must not be able to issue a `COMMIT` statement in the middle of an unfinished concurrent write! + + +## Safe and Unsafe Database Accesses + +**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees: + +- **[Serialized Writes]** - All writes performed by one [DatabaseQueue] or [DatabasePool] instance are serialized. *Why is it important?* - this guarantee prevents [SQLITE_BUSY] errors during concurrent writes. +- **[Write Transactions]** - All writes are wrapped in a transaction. *Why is it important?* - concurrent reads can not see partial database updates (even reads performed by other processes). +- **[Isolated Reads]** - All reads are wrapped in a transaction. *Why is it important?* - an isolated read sees a stable and immutable state of the database[^1], and does not see changes performed by eventual concurrent writes (even writes performed by other processes). +- **[Forbidden Writes]** - Inside a read access, all attempts to write raise an error. *Why is it important?* - this enforces the immutability of the database during a read. +- **[Non-Reentrancy]** - Database accesses are not reentrant. *Why is it important?* - this reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of the [second concurrency rule](#rule-2). + +Some applications need to relax this safety net, in order to achieve specific SQLite operations. In this case, replace `read` and `write` with one of the methods below: + +- **Write outside of any transaction** + (Lifted guarantee: [Write Transactions]) + + ```swift + try dbQueue.writeWithoutTransaction { db in ... } + ``` + + You can also use `asyncWriteWithoutTransaction`. + +- **Write outside of any transaction, and prevents concurrent reads** + (Lifted guarantee: [Write Transactions]) + + ```swift + try dbQueue.barrierWriteWithoutTransaction { db in ... } + ``` + + The barrier write guarantees an exclusive access to the database: the method blocks until all concurrent database accesses are completed, reads and writes, and postpones all other accesses until it completes. + + There is a known limitation: database accesses performed by other processes, and reads performed by [DatabaseSnapshot] are out of scope of this barrier, and can run concurrently with the barrier. + + You will use this method, for example, when you [change the password](../README.md#changing-the-passphrase-of-an-encrypted-database) of an encrypted database. + + You can also use `asyncBarrierWriteWithoutTransaction`. + +- **Reentrant write outside of any transaction** + (Lifted guarantees: [Write Transactions], [Non-Reentrancy]) + + ```swift + try dbQueue.unsafeReentrantWrite { db in ... } + ``` + + Reentrant writes can be performed from any other database access: + + ```swift + try dbQueue.write { db in + // No fatal error + try dbQueue.unsafeReentrantWrite { db in ... } + } + ``` + + `unsafeReentrantWrite` has no async version. + +- **Read outside of any transaction** + (Lifted guarantees: [Isolated Reads], [Forbidden Writes]) + + ```swift + try dbQueue.unsafeRead { db in ... } + ``` + + `unsafeRead` has no async version. + +- **Reentrant read, outside of any transaction** + (Lifted guarantees: [Isolated Reads], [Forbidden Writes], [Non-Reentrancy]) + + ```swift + try dbQueue.unsafeReentrantRead { db in ... } + ``` + + Reentrant reads can be performed from any other database access: + + ```swift + try dbQueue.write { db in + // No fatal error + try dbQueue.unsafeReentrantRead { db in ... } + } + ``` + + `unsafeReentrantRead` has no async version. + +:point_up: **By using one of the methods above, you become responsible of the thread-safety of your application.** Please understand the consequences of lifting each concurrency guarantee. Some guarantees can also be restored at your convenience: + +- The [Write Transactions] and [Isolated Reads] guarantees can be restored at any point, by opening an [explicit transaction](../README.md#transactions-and-savepoints). For example: + + ```swift + try dbQueue.writeWithoutTransaction { db in + try db.inTransaction { + ... + return .commit + } + } + ``` + +- The [Forbidden Writes] guarantee can only be lifted with [DatabaseQueue]. It can be restored with [`PRAGMA query_only`](https://www.sqlite.org/pragma.html#pragma_query_only). + + +## Differences between Database Queues and Pools + +Despite the common [guarantees](#safe-and-unsafe-database-accesses) and [rules](#concurrency-rules) shared by database queues and pools, those two database accessors don't have the same behavior. + +[DatabaseQueue] opens a single database connection, and serializes all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes: + +![DatabaseQueueScheduling](https://cdn.rawgit.com/groue/GRDB.swift/development/Documentation/Images/DatabaseQueueScheduling.svg) + +[DatabasePool] manages a pool of several database connections, and allows concurrent reads and writes thanks to the [WAL mode](https://www.sqlite.org/wal.html). A database pool serializes all writes (the [Serialized Writes] guarantee). Reads are isolated so that they don't see changes performed by other threads (the [Isolated Reads] guarantee). This gives a very different picture: + +![DatabasePoolScheduling](https://cdn.rawgit.com/groue/GRDB.swift/development/Documentation/Images/DatabasePoolScheduling.svg) + +See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next [Concurrent Thinking] chapter below for a relief. + + +## Concurrent Thinking + +Despite their [differences](#differences-between-database-queues-and-pools), you can write robust code that works equally well with both database queues and pools. + +This allows your app to switch between queues and pools, at your convenience: + +- The [demo applications] share the same database code for the on-disk pool that feeds the app, and the in-memory queue that feeds tests and SwiftUI previews. This makes sure tests and previews run fast, without any temporary file, with the same behavior as the app. +- Applications that perform slow write transactions (when saving a lot of data from a remote server, for example) may want to replace their queue with a pool so that the reads that feed their user interface can run in parallel. + +All you need is a little "concurrent thinking", based on those two basic facts: + +- You are sure, when you perform a write access, that you deal with the latest database state on disk. This is enforced by SQLite, which simply can't perform parallel writes, and by GRDB database queues and pools, which make sure [only one thread can write](#guarantee-serialized-writes). As for writes performed by other processes, they can only trigger [SQLITE_BUSY] errors [that you can handle](SharingADatabase.md). + +- Whenever you extract some data from a database access, immediately consider it as _stale_. It is stale, whether you use a database queue or a database pool. It is stale because nothing prevents other application threads or processes from overwriting the value you have just fetched: + + + + ```swift + // or dbQueue.write, for that matter + let cookieCount = dbPool.read { db in + try Cookie.fetchCount(db) + } + + // At this point, the number of cookies on disk + // may have already changed. + print("We have \(cookieCount) cookies left") + ``` + + Does this mean you can't rely on anything? Of course not: + + - If you intend to display the database content on screen, use [ValueObservation]: it always eventually notifies the latest state of the database. You won't display stale values for a long time [^2]. + + - As said above, the moment of truth is the next write access! + + +## Advanced DatabasePool + +[DatabasePool] is very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database. + +When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid blocking concurrent writes longer than necessary: + +```swift +try dbPool.write { db in + // Increment the number of players + try Player(...).insert(db) + try Player(...).insert(db) + + // Read the number of players. Concurrent writes are blocked :-( + let newPlayerCount = try Player.fetchCount(db) +} +``` + +:arrow_right: The solution is the `concurrentRead` method. It must be called from within a write access, outside of any transaction. It returns a *future value* which you consume any time later, with the `wait()` method. + +```swift +let future: DatabaseFuture = try dbPool.writeWithoutTransaction { db in + // Increment the number of players + try db.inTransaction { + try Player(...).insert(db) + try Player(...).insert(db) + return .commit + } + + // <- Not in a transaction here + let future = dbPool.concurrentRead { db + try Player.fetchCount(db) + } + return future +} +// <- Concurrent writes can be performed :-) + +// Wait and handle newPlayerCount +let newPlayerCount = try future.wait() +``` + +:twisted_rightwards_arrows: The async version of `concurrentRead` is `asyncConcurrentRead`: + +```swift +try dbPool.writeWithoutTransaction { db in + // Increment the number of players + try db.inTransaction { + try Player(...).insert(db) + try Player(...).insert(db) + return .commit + } + + // <- Not in a transaction here + dbPool.asyncConcurrentRead { dbResult in + do { + // Maybe read access could not be established + let db = try dbResult.get() + let newPlayerCount = try Player.fetchCount(db) + // Handle newPlayerCount + } catch { + // Handle error + } + } +} +``` + +`concurrentRead` and `asyncConcurrentRead` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure. + +In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write: + +![DatabasePoolConcurrentRead](https://cdn.rawgit.com/groue/GRDB.swift/development/Documentation/Images/DatabasePoolConcurrentRead.svg) + +[Transaction Observers](../README.md#transactionobserver-protocol) can also use those methods in their `databaseDidCommit` method, in order to process database changes without blocking other threads that want to write into the database. + + +## Database Snapshots + +**[DatabasePool] can take snapshots.** A database snapshot sees an unchanging database content, as it existed at the moment it was created. + +"Unchanging" means that a snapshot never sees any database modifications 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)). + +```swift +let snapshot = try dbPool.makeSnapshot() +``` + +You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#databasepool-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized. + +**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools: + +```swift +let playerCount = try snapshot.read { db in + try Player.fetchCount(db) +} +``` + +When you want to control the latest committed changes seen by a snapshot, create the snapshot from within a write, outside of any transaction: + +```swift +let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in + try db.inTransaction { + // delete all players + try Player.deleteAll() + return .commit + } + + // <- not in a transaction here + return dbPool.makeSnapshot() +} +// <- Other threads may modify the database here +let snapshot2 = try dbPool.makeSnapshot() + +try snapshot1.read { db in + // Guaranteed to be zero + try Player.fetchCount(db) +} + +try snapshot2.read { db in + // Could be anything + try Player.fetchCount(db) +} +``` + +> :point_up: **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads. + +[^1]: This immutable view of the database is called [snapshot isolation](https://www.sqlite.org/isolation.html). + +[^2]: After the database has been changed on disk, GRDB has to fetch the fresh value, and then hop to the main thread. Only then your screen can be updated. + +[Concurrency Rules]: #concurrency-rules +[Synchronous and Asynchronous Database Accesses]: #synchronous-and-asynchronous-database-accesses +[Safe and Unsafe Database Accesses]: #safe-and-unsafe-database-accesses +[Differences between Database Queues and Pools]: #differences-between-database-queues-and-pools +[Concurrent Thinking]: #concurrent-thinking +[Advanced DatabasePool]: #advanced-databasepool +[Database Snapshots]: #database-snapshots +[DatabaseQueue]: ../README.md#database-queues +[DatabasePool]: ../README.md#database-pools +[DatabaseSnapshot]: #database-snapshots +[demo apps]: DemoApps +[Database Observation]: ../README.md#database-changes-observation +[SQLITE_BUSY]: https://www.sqlite.org/rescode.html#busy +[Sharing a Database]: SharingADatabase.md +[ValueObservation]: ../README.md#valueobservation +[GRDB ❤️ Combine]: Combine.md +[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB +[Serialized Writes]: #guarantee-serialized-writes +[Write Transactions]: #guarantee-write-transactions +[Isolated Reads]: #guarantee-isolated-reads +[Forbidden Writes]: #guarantee-forbidden-writes +[Non-Reentrancy]: #guarantee-non-reentrancy +[demo applications]: DemoApps diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj index 854b7a323..d3ad48f6c 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -379,7 +379,7 @@ }; }; buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */; - compatibilityVersion = "Xcode 9.3"; + compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index c6fb87b72..82690996c 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -462,7 +462,7 @@ }; }; buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */; - compatibilityVersion = "Xcode 3.2"; + compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -687,7 +687,11 @@ GCC_C_LANGUAGE_STANDARD = gnu11; INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 14.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; @@ -710,7 +714,11 @@ GCC_C_LANGUAGE_STANDARD = gnu11; INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 14.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); MTL_FAST_MATH = YES; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -727,7 +735,11 @@ CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension; PRODUCT_NAME = "${TARGET_NAME}"; SDKROOT = watchos; @@ -743,7 +755,11 @@ CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension; PRODUCT_NAME = "${TARGET_NAME}"; SDKROOT = watchos; @@ -896,7 +912,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; WATCHOS_DEPLOYMENT_TARGET = 2.0; @@ -911,7 +928,10 @@ CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = GRDBDemoiOS/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -925,7 +945,10 @@ CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = GRDBDemoiOS/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS; PRODUCT_NAME = "$(TARGET_NAME)"; }; diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 9233f4ed7..45f214571 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index b83fbb465..e06918629 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -24,8 +24,8 @@ Your attention will be needed, though, in the area of database observation. GRDB requirements have been bumped: -- **Swift 5.2+** (was Swift 4.2+) -- **Xcode 11.4+** (was Xcode 10.0+) +- **Swift 5.3+** (was Swift 4.2+) +- **Xcode 12.0+** (was Xcode 10.0+) - **iOS 11.0+** (was iOS 9.0+) - **macOS 10.10+** (was macOS 10.9+) - tvOS 9.0+ (unchanged) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 6725321e0..7977f9665 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -803,8 +803,8 @@ Instead, have a look at [Database Observation]: [migrations]: Migrations.md [migration]: Migrations.md [Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions -[Concurrency Guide]: ../README.md#concurrency -[GRDB concurrency rules]: ../README.md#concurrency +[Concurrency Guide]: Concurrency.md +[GRDB concurrency rules]: Concurrency.md#concurrency-rules [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation [ValueObservation]: ../README.md#valueobservation diff --git a/Documentation/Images/DatabasePoolConcurrentRead.svg b/Documentation/Images/DatabasePoolConcurrentRead.svg new file mode 100644 index 000000000..0f9c94437 --- /dev/null +++ b/Documentation/Images/DatabasePoolConcurrentRead.svg @@ -0,0 +1,337 @@ + + + DatabasePoolConcurrentRead + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Documentation/Images/DatabasePoolScheduling.svg b/Documentation/Images/DatabasePoolScheduling.svg index a39e6ab27..030414466 100644 --- a/Documentation/Images/DatabasePoolScheduling.svg +++ b/Documentation/Images/DatabasePoolScheduling.svg @@ -1,173 +1,248 @@ - - + DatabasePoolScheduling - Created with Sketch. - - + + + + + + + + + + + - - - - + + - - + + + + + - - - - + + + + + + - - + + + + + - - - - + + + + + + - - + + + + + - - - - + + + + + + - - + + + + + - - - - + + - - - - - - - - - - + + + + + - - - - - - - - Thread 1 - - - Thread 2 - - - Thread 3 - - - - - - - - - - - - - Read State A - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Read State A - + + + + + + + + + + + + + + - - - - - - - - - - - - Write State B - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Read State B - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Write State C - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Read State C - + + + + + + + + + + + + + + + + + + - - - Time - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file diff --git a/Documentation/Images/DatabaseQueueScheduling.svg b/Documentation/Images/DatabaseQueueScheduling.svg index 01cdf4cf6..559a2947d 100644 --- a/Documentation/Images/DatabaseQueueScheduling.svg +++ b/Documentation/Images/DatabaseQueueScheduling.svg @@ -1,150 +1,207 @@ - - + DatabaseQueueScheduling - Created with Sketch. - - + + + + + + + + + + + - - - - + + - - + + + + + - - - - + + - - + + + + + - - - - + + - - + + + + + - - - - + + - - - - - - - - - - + + + + + - - - - - - - - Thread 1 - - - Thread 2 - - - Thread 3 - - - - Time - - - - - - - - - - - - - - - Read State A - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Write State B - + + + + + + + + + + + + + + - - - - - - - - - - - - Read State B - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Read State C - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - Write State C - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file diff --git a/Documentation/Images/Makefile b/Documentation/Images/Makefile deleted file mode 100644 index 7c42c98f5..000000000 --- a/Documentation/Images/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -fixfonts: - sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg - sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg diff --git a/Documentation/Images/TwoCookiesLeft.jpg b/Documentation/Images/TwoCookiesLeft.jpg new file mode 100644 index 000000000..6c6929e39 Binary files /dev/null and b/Documentation/Images/TwoCookiesLeft.jpg differ diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index aca5bf756..abee19b36 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -2,6 +2,15 @@ **Migrations** are a convenient way to alter your database schema over time in a consistent and easy way. +- [Migrations Overview] +- [The `eraseDatabaseOnSchemaChange` Option] +- [Advanced Database Schema Changes] +- [Foreign Key Checks] +- [Asynchronous Migrations] + + +## Migrations Overview + Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run. Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs: @@ -31,7 +40,7 @@ migrator.registerMigration("v2") { db in **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. -**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). +**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See [Foreign Key Checks] below for more information. **The memory of applied migrations is stored in the database itself** (in a reserved table). @@ -68,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.12/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.13/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option @@ -102,13 +111,10 @@ The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database i ## Advanced Database Schema Changes -SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example. - -Yet any kind of schema change is still possible, by recreating tables: +If SQLite does not directly support all kinds of schema alterations, you can make arbitrary changes to the schema design of any table using a sequence of operations, as in the example below: ```swift -migrator.registerMigration("AddNotNullCheckOnName") { db in - // Add a NOT NULL constraint on player.name: +migrator.registerMigration("Add NOT NULL check on player.name") { db in try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() @@ -119,6 +125,144 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in } ``` +This technique is described in SQLite documentation: [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). + +The detailed sequence of operations is described below, some of them are performed by GRDB, and others by your code: + +1. GRDB: If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF. + +2. GRDB: Start a transaction. + +3. **Your code**: Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`. + +4. **Your code**: Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course. + +5. **Your code**: Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`. + +6. **Your code**: Drop the old table X: `DROP TABLE X`. + +7. **Your code**: Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`. + +8. **Your code**: Use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration. + +9. **Your code**: If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`. + +10. GRDB: If foreign key constraints were originally enabled then run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints. + +11. GRDB: Commit the transaction started in step 2. + +12. GRDB: If foreign keys constraints were originally enabled, reenable them now. + +> :point_up: **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary. +> +> :point_up: **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll. + + +## Foreign Key Checks + +SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perform some schema changes, and this creates very undesired churn w.r.t. foreign keys. GRDB makes its best to hide those problems to you, but you might have to deal with them one day, especially if your database becomes *very big*: + +You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeys` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks. + +**Your first mitigation technique is immediate foreign key checks.** + +If you register a migration with `.immediate` foreign key checks, the migration will not temporarily disable foreign keys, and won't need to perform a deferred full check of all foreign keys in your database: + +```swift +migrator.registerMigration("make it faster please", foreignKeyChecks: .immediate) { db in + try db.create(table: ...) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ... +} +``` + +Such a migration is much faster, and it still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). In this case, you'll need to use the second mitigation technique: + +**Your second mitigation technique is to disable deferred foreign key checks.** + +You can ask the migrator to stop performing foreign key checks for all newly registered migrations. + +:warning: If you use this technique, your app becomes responsible for preventing foreign key violations from being committed to disk! + +```swift +migrator = migrator.disablingDeferredForeignKeyChecks() + +// From now on, migrations are unchecked! +migrator.registerMigration("fast but unchecked") { db in ... } +``` + +In order to prevent foreign key violations from being committed to disk, you can: + +- Run migrations with immediate foreign key check, as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes): + + ```swift + migrator = migrator.disablingDeferredForeignKeyChecks() + migrator.registerMigration("unchecked") { db in ... } + migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... } + ``` + +- Perform foreign key checks on some tables only: + + ```swift + migrator = migrator.disablingDeferredForeignKeyChecks() + migrator.registerMigration("partially checked") { db in + ... + + // Throws an error and stops migrations if there exists a + // foreign key violation in the 'player' table. + try db.checkForeignKeys(in: "player") + } + ``` + +- Perform a full check of foreign keys, eventually: + + ```swift + try migrator.migrate(dbQueue) + + // Throws an error if there exists any foreign key violation. + try dbQueue.read { db in + try db.checkForeignKeys() + } + ``` + +In order to check for foreign key violations, the `checkForeignKeys()` and `checkForeignKeys(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information: + +```swift +// SQLite error 19: FOREIGN KEY constraint violation - from player(teamId) to team(id), +// in [id:1 teamId:2 name:"O'Brien" score:1000] +try db.checkForeignKeys() +``` + +You can also iterate a lazy [cursor](../README.md#cursors) of all individual foreign key violations found in the database: + +```swift +let violations = try db.foreignKeyViolations() +while let violation = try violations.next() { + // The name of the table that contains the `REFERENCES` clause + violation.originTable + + // The rowid of the row that contains the invalid `REFERENCES` clause, or + // nil if the origin table is a `WITHOUT ROWID` table. + violation.originRowID + + // The name of the table that is referred to. + violation.destinationTable + + // The id of the specific foreign key constraint that failed. This id + // matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more + // information. + violation.foreignKeyId + + // Plain description: + // "FOREIGN KEY constraint violation - from player to team, in rowid 1" + String(describing: violation) + + // Rich description: + // "FOREIGN KEY constraint violation - from player(teamId) to team(id), + // in [id:1 teamId:2 name:"O'Brien" score:1000]" + try violation.failureDescription(db) +} +``` + ## Asynchronous Migrations `DatabaseMigrator` provides two ways to migrate a database in an asynchronous way. @@ -142,3 +286,11 @@ let publisher = migrator.migratePublisher(dbQueue) ``` This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument. + + + +[Migrations Overview]: #migrations-overview +[The `eraseDatabaseOnSchemaChange` Option]: #the-erasedatabaseonschemachange-option +[Advanced Database Schema Changes]: #advanced-database-schema-changes +[Foreign Key Checks]: #foreign-key-checks +[Asynchronous Migrations]: #asynchronous-migrations diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 2aec8083b..ea7e1d6da 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -19,7 +19,7 @@ try dbQueue.write { db in } ``` -SQL Interpolation is an answer to these troubles. It is available in Swift 5. +SQL Interpolation is an answer to these troubles. - [Introduction] - [SQL Literal] diff --git a/Documentation/SharingADatabase.md b/Documentation/SharingADatabase.md index 429ead152..b0f59761f 100644 --- a/Documentation/SharingADatabase.md +++ b/Documentation/SharingADatabase.md @@ -1,7 +1,7 @@ Sharing a Database ================== -This chapter describes a recommended setup that applies as soon as several processes want to access a same SQLite database. +**This guide describes a recommended setup that applies as soon as several processes want to access the same SQLite database.** It complements the [Concurrency](Concurrency.md) guide, that you should read first. On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS as well, several processes may want to open the same database, according to their particular sandboxing contexts. @@ -152,7 +152,6 @@ If several processes want to write in the database, configure the database pool ```swift var configuration = Configuration() configuration.busyMode = .timeout(/* a TimeInterval */) -configuration.defaultTransactionKind = .immediate let dbPool = try DatabasePool(path: ..., configuration: configuration) ``` @@ -161,7 +160,7 @@ With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") err ```swift do { try dbPool.write { db in ... } -} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY { +} catch DatabaseError.SQLITE_BUSY { // Another process won't let you write. Deal with it. } ``` @@ -251,7 +250,7 @@ See https://developer.apple.com/documentation/xcode/understanding-the-exception- ```swift do { try dbPool.write { db in ... } - } catch let error as DatabaseError where error.isInterruptionError { + } catch DatabaseError.SQLITE_INTERRUPT, DatabaseError.SQLITE_ABORT { // Oops, the database is suspended. // Maybe try again after database is resumed? } diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 977631eda..e36e48de6 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -240,7 +240,7 @@ let maximumScore: Int? = try Int.fetchOne(db, sql: """ """) ``` -With Swift 5, you can profit from **SQL interpolation**. It lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/): +[SQL interpolation] lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/): ```swift try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)") @@ -285,7 +285,7 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB] Happy GRDB! :gift: -[Concurrency Guide]: ../README.md#concurrency +[Concurrency Guide]: Concurrency.md [Core Data]: https://developer.apple.com/documentation/coredata [DatabasePool]: ../README.md#database-pools [Diesel]: http://diesel.rs @@ -306,3 +306,4 @@ Happy GRDB! :gift: [associations]: AssociationsBasics.md [Codable records]: ../README.md#codable-records [records]: ../README.md#records +[SQL interpolation]: SQLInterpolation.md diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index a80cc66c8..9a551333e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.12.0' + s.version = '5.13.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' @@ -9,7 +9,7 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } s.module_name = 'GRDB' - s.swift_versions = ['5.2'] + s.swift_versions = ['5.3', '5.4', '5.5'] s.ios.deployment_target = '11.0' s.osx.deployment_target = '10.10' s.watchos.deployment_target = '2.0' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d95347493..5a1a122d4 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 47; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -14,6 +14,13 @@ 56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; }; 56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; }; 56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; }; + 560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; + 560233C52724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; + 560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; + 560233C72724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; }; + 560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; }; + 560233CA2724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; }; + 560233CB2724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; }; 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; @@ -573,6 +580,9 @@ 56915783231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; }; 56915784231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; }; 569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */; }; + 5691D96A27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; }; + 5691D96B27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; }; + 5691D96C27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; }; 569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */; }; 5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */; }; 5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */; }; @@ -1258,6 +1268,8 @@ /* Begin PBXFileReference section */ 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; + 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; + 560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -1361,6 +1373,7 @@ 56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = ""; }; 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = ""; }; 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = ""; }; + 5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; @@ -1478,6 +1491,7 @@ 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; 56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; + 5691D96927256C3A0021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = ""; }; 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = ""; }; 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = ""; }; @@ -1791,6 +1805,7 @@ isa = PBXGroup; children = ( 563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */, + 560233C32724234F00529DF3 /* SharedValueObservation.swift */, 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, @@ -1933,6 +1948,7 @@ 563B06BF2185CD1700B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 560233C82724338800529DF3 /* SharedValueObservationTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, @@ -1964,6 +1980,7 @@ 56419A6024A51601004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D96927256C3A0021D540 /* AvailableElements.swift */, 56419A6124A51601004967E1 /* Finished.swift */, 56419A6224A51601004967E1 /* NextOne.swift */, 56419A6324A51601004967E1 /* Next.swift */, @@ -2443,6 +2460,7 @@ DC10500F19C904DD00D8CA30 /* Tests */, DC3773F419C8CBB3004FCF85 /* Products */, 564390D42414FC2C00BA61E6 /* Frameworks */, + 5643676D272EDF2400C718C7 /* Scripts */, ); indentWidth = 4; sourceTree = ""; @@ -2737,7 +2755,7 @@ }; }; buildConfigurationList = DC3773ED19C8CBB3004FCF85 /* Build configuration list for PBXProject "GRDB" */; - compatibilityVersion = "Xcode 6.3"; + compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -2843,7 +2861,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; }; 56EB54FA22C9115E00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2861,7 +2879,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; }; AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2879,7 +2897,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; }; /* End PBXShellScriptBuildPhase section */ @@ -2943,6 +2961,7 @@ 567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, + 560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */, 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, @@ -3130,6 +3149,7 @@ 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */, + 560233C52724234F00529DF3 /* SharedValueObservation.swift in Sources */, 5611620925757583007AAF99 /* JoinAssociation.swift in Sources */, 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */, 566BE71F2342542F00A8254B /* LockedBox.swift in Sources */, @@ -3211,6 +3231,7 @@ 562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, 563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, + 5691D96B27256C3B0021D540 /* AvailableElements.swift in Sources */, 56DF001C228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */, 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, @@ -3368,6 +3389,7 @@ 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 560233CA2724338800529DF3 /* SharedValueObservationTests.swift in Sources */, 56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, @@ -3443,6 +3465,7 @@ 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, 56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */, 563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, + 5691D96A27256C3B0021D540 /* AvailableElements.swift in Sources */, 56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, @@ -3600,6 +3623,7 @@ 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, + 560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */, 56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, 569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, @@ -3727,6 +3751,7 @@ AAA4DCCB230F1E0600C74B15 /* DatabaseRegion.swift in Sources */, AAA4DCCC230F1E0600C74B15 /* DatabaseQueue.swift in Sources */, AAA4DCCD230F1E0600C74B15 /* ValueObservation.swift in Sources */, + 560233C72724234F00529DF3 /* SharedValueObservation.swift in Sources */, 5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */, AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */, 566BE7212342542F00A8254B /* LockedBox.swift in Sources */, @@ -3808,6 +3833,7 @@ AAA4DD26230F262000C74B15 /* DatabaseWriterTests.swift in Sources */, AAA4DD27230F262000C74B15 /* DatabasePoolFunctionTests.swift in Sources */, AAA4DD28230F262000C74B15 /* ValueObservationCountTests.swift in Sources */, + 5691D96C27256C3B0021D540 /* AvailableElements.swift in Sources */, AAA4DD29230F262000C74B15 /* AssociationPrefetchingRowTests.swift in Sources */, AAA4DD2A230F262000C74B15 /* RowCopiedFromStatementTests.swift in Sources */, AAA4DD2B230F262000C74B15 /* DerivableRequestTests.swift in Sources */, @@ -3965,6 +3991,7 @@ AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */, 56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, AAA4DDAE230F262000C74B15 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 560233CB2724338800529DF3 /* SharedValueObservationTests.swift in Sources */, 56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, AAA4DDAF230F262000C74B15 /* CursorTests.swift in Sources */, AAA4DDB1230F262000C74B15 /* FoundationNSStringTests.swift in Sources */, @@ -4092,6 +4119,7 @@ 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5611620825757583007AAF99 /* JoinAssociation.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */, 569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, @@ -4177,7 +4205,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = watchos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -4204,7 +4236,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = watchos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = 4; @@ -4220,7 +4256,11 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -4237,11 +4277,16 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -4262,7 +4307,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -4288,10 +4337,15 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; @@ -4307,7 +4361,11 @@ DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -4329,14 +4387,19 @@ DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; "PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = ""; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -4349,7 +4412,11 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -4367,12 +4434,17 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -4395,7 +4467,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; SKIP_INSTALL = YES; @@ -4423,11 +4499,16 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -4443,7 +4524,11 @@ DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBtvOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -4465,13 +4550,18 @@ DEVELOPMENT_TEAM = ""; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); OTHER_SWIFT_FLAGS = "$(inherited) -D SQLITE_MODULE"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBtvOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -4574,7 +4664,8 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -4597,7 +4688,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; @@ -4618,9 +4713,14 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = Support/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 97dbaa94a..27d0364b8 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -175,7 +175,7 @@ extension Database { .contains { $0.lowercased() == name } } - /// The primary key for table named `tableName`, in the main or temp schema. + /// The primary key for table named `tableName`. /// /// All tables have a primary key, even when it is not explicit. When a /// table has no explicit primary key, the result is the hidden @@ -304,7 +304,7 @@ extension Database { } } - /// The indexes on table named `tableName`, in the main or temp schema. + /// The indexes on table named `tableName`. /// /// Only indexes on columns are returned. Indexes on expressions are /// not returned. @@ -385,7 +385,7 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } - /// The foreign keys defined on table named `tableName`, in the main or temp schema. + /// The foreign keys defined on table named `tableName`. /// /// - throws: A DatabaseError if table does not exist. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { @@ -404,6 +404,7 @@ extension Database { } var rawForeignKeys: [( + id: Int, destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil @@ -424,7 +425,7 @@ extension Database { .append((origin: origin, destination: destination, seq: seq)) } else { let mapping = [(origin: origin, destination: destination, seq: seq)] - rawForeignKeys.append((destinationTable: table, mapping: mapping)) + rawForeignKeys.append((id: id, destinationTable: table, mapping: mapping)) previousId = id } } @@ -438,7 +439,7 @@ extension Database { } } - let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in + let foreignKeys = try rawForeignKeys.map { (id, destinationTable, columnMapping) -> ForeignKeyInfo in let orderedMapping = columnMapping .sorted { $0.seq < $1.seq } .map { (origin: $0.origin, destination: $0 .destination) } @@ -454,13 +455,59 @@ extension Database { (origin: origin, destination: destination!) } } - return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping) + return ForeignKeyInfo(id: id, destinationTable: destinationTable, mapping: completeMapping) } schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name) return foreignKeys } + /// Returns a cursor over foreign key violations in the database. + public func foreignKeyViolations() throws -> RecordCursor { + try ForeignKeyViolation.fetchCursor(self, sql: "PRAGMA foreign_key_check") + } + + /// Returns a cursor over foreign key violations in the table. + public func foreignKeyViolations(in tableName: String) throws -> RecordCursor { + for schemaIdentifier in try schemaIdentifiers() { + if try exists(type: .table, name: tableName, in: schemaIdentifier) { + return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) + } + } + throw DatabaseError.noSuchTable(tableName) + } + + /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + /// if there exists a foreign key violation in the database. + public func checkForeignKeys() throws { + try checkForeignKeys(from: foreignKeyViolations()) + } + + /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + /// if there exists a foreign key violation in the table. + public func checkForeignKeys(in tableName: String) throws { + try checkForeignKeys(from: foreignKeyViolations(in: tableName)) + } + + private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { + try ForeignKeyViolation.fetchCursor(self, sql: """ + PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) + """) + } + + private func checkForeignKeys(from violations: RecordCursor) throws { + guard let violation = try violations.next() else { + return + } + + // Grab detailed information, if possible, for better error message. + // If detailed information is not available, fallback to plain description. + let message = (try? violation.failureDescription(self)) ?? String(describing: violation) + throw DatabaseError( + resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, + message: message) + } + /// Returns the actual name of the database table, in the main or temp /// schema, or nil if the table does not exist. /// @@ -486,7 +533,7 @@ extension Database { extension Database { - /// The columns in the table named `tableName`, in the main or temp schema. + /// The columns in the table named `tableName`. /// /// - throws: A DatabaseError if table does not exist. public func columns(in tableName: String) throws -> [ColumnInfo] { @@ -725,6 +772,79 @@ public struct IndexInfo { } } +/// A foreign key violation produced by PRAGMA foreign_key_check +/// +/// See +public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { + /// The name of the table that contains the `REFERENCES` clause + var originTable: String + + /// The rowid of the row that contains the invalid `REFERENCES` clause, or + /// nil if the origin table is a `WITHOUT ROWID` table. + var originRowID: Int64? + + /// The name of the table that is referred to. + var destinationTable: String + + /// The id of the specific foreign key constraint that failed. This id + /// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more + /// information. + var foreignKeyId: Int + + public init(row: Row) { + originTable = row[0] + originRowID = row[1] + destinationTable = row[2] + foreignKeyId = row[3] + } + + public var description: String { + if let originRowID = originRowID { + return """ + FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \ + in rowid \(originRowID) + """ + } else { + return """ + FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable) + """ + } + } + + /// Returns a precise description of the foreign key violation. + /// + /// For example: 'FOREIGN KEY constraint violation - from player(teamId) to team(id), + /// in [id:1 teamId:2 name:"O'Brien" score: 1000]' + public func failureDescription(_ db: Database) throws -> String { + // Grab detailed information, if possible, for better error message + let originRow = try originRowID.flatMap { rowid in + try Row.fetchOne(db, sql: "SELECT * FROM \(originTable) WHERE rowid = \(rowid)") + } + let foreignKey = try db.foreignKeys(on: originTable).first(where: { foreignKey in + foreignKey.id == foreignKeyId + }) + + var description: String + if let foreignKey = foreignKey { + description = """ + FOREIGN KEY constraint violation - \ + from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \ + to \(destinationTable)(\(foreignKey.destinationColumns.joined(separator: ", "))) + """ + } else { + description = "FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)" + } + + if let originRow = originRow { + description += ", in \(String(describing: originRow))" + } else if let originRowID = originRowID { + description += ", in rowid \(originRowID)" + } + + return description + } +} + /// Primary keys are returned from the Database.primaryKey(_:) method. /// /// When the table's primary key is the rowid: @@ -861,6 +981,9 @@ public struct PrimaryKeyInfo { /// You get foreign keys from table names, with the /// `foreignKeys(on:)` method. public struct ForeignKeyInfo { + /// The first column in the output of the `foreign_key_list` pragma + public var id: Int + /// The name of the destination table public let destinationTable: String diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b1c16a1ff..f8f6bc47f 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -26,7 +26,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - SQLite C API /// The raw SQLite connection, suitable for the SQLite C API. - public let sqliteConnection: SQLiteConnection + /// It is constant, until close() sets it to nil. + public var sqliteConnection: SQLiteConnection? // MARK: - Configuration @@ -112,7 +113,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // > connection while this routine is running, then the return value // > is undefined. SchedulingWatchdog.preconditionValidQueue(self) - if isClosed { return false } // Support for SerializedDatabase.deinit + if sqliteConnection == nil { return false } // Support for SerializedDatabase.deinit return sqlite3_get_autocommit(sqliteConnection) == 0 } @@ -182,7 +183,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private var functions = Set() private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly - private var isClosed = false // MARK: - Initializer @@ -197,7 +197,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } deinit { - assert(isClosed) + assert(sqliteConnection == nil) } // MARK: - Database Opening @@ -216,7 +216,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // https://www.sqlite.org/c3ref/close.html // > Calling sqlite3_close() or sqlite3_close_v2() with a NULL // > pointer argument is a harmless no-op. - sqlite3_close(sqliteConnection) + _ = sqlite3_close(sqliteConnection) // ignore result code throw DatabaseError(resultCode: code) } if let sqliteConnection = sqliteConnection { @@ -368,36 +368,80 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Database Closing - /// This method must be called before database deallocation - func close() { + /// Closes a connection with `sqlite3_close`. This method is intended for + /// the public `close()` function. It may fail. + func close() throws { SchedulingWatchdog.preconditionValidQueue(self) - if isClosed { + guard let sqliteConnection = sqliteConnection else { + // Already closed return } configuration.SQLiteConnectionWillClose?(sqliteConnection) internalStatementCache.clear() publicStatementCache.clear() - Database.closeConnection(sqliteConnection) - isClosed = true + + // https://www.sqlite.org/c3ref/close.html + // > If the database connection is associated with unfinalized prepared + // > statements or unfinished sqlite3_backup objects then + // > sqlite3_close() will leave the database connection open and + // > return SQLITE_BUSY. + let code = sqlite3_close(sqliteConnection) + guard code == SQLITE_OK else { + if let log = Self.logError { + if code == SQLITE_BUSY { + // Let the user know about unfinalized statements that did + // prevent the connection from closing properly. + var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil) + while stmt != nil { + log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))") + stmt = sqlite3_next_stmt(sqliteConnection, stmt) + } + } + } + + throw DatabaseError(resultCode: code, message: lastErrorMessage) + } + + self.sqliteConnection = nil configuration.SQLiteConnectionDidClose?() } - private static func closeConnection(_ sqliteConnection: SQLiteConnection) { + /// Closes a connection with `sqlite3_close_v2`. This method is intended for + /// deallocated connections. + func close_v2() { + SchedulingWatchdog.preconditionValidQueue(self) + + guard let sqliteConnection = sqliteConnection else { + // Already closed + return + } + + configuration.SQLiteConnectionWillClose?(sqliteConnection) + internalStatementCache.clear() + publicStatementCache.clear() + // https://www.sqlite.org/c3ref/close.html // > If sqlite3_close_v2() is called with unfinalized prepared // > statements and/or unfinished sqlite3_backups, then the database // > connection becomes an unusable "zombie" which will automatically // > be deallocated when the last prepared statement is finalized or the // > last sqlite3_backup is finished. + // > + // > The sqlite3_close_v2() interface is intended for use with host + // > languages that are garbage collected, and where the order in which + // > destructors are called is arbitrary. let code = sqlite3_close_v2(sqliteConnection) - if code != SQLITE_OK, let log = logError { + if code != SQLITE_OK, let log = Self.logError { // A rare situation where GRDB doesn't fatalError on // unprocessed errors. let message = String(cString: sqlite3_errmsg(sqliteConnection)) log(ResultCode(rawValue: code), "could not close database: \(message)") } + + self.sqliteConnection = nil + configuration.SQLiteConnectionDidClose?() } // MARK: - Limits diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 9fda1eb42..9449381db 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -258,6 +258,12 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { } } +extension DatabaseError { + static func connectionIsClosed() -> Self { + DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed") + } +} + // Support for `catch DatabaseError.SQLITE_XXX` extension DatabaseError { public static let SQLITE_OK = ResultCode.SQLITE_OK diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 40f5d32a9..acc7c09de 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -7,7 +7,10 @@ import UIKit /// A DatabasePool grants concurrent accesses to an SQLite database. public final class DatabasePool: DatabaseWriter { private let writer: SerializedDatabase - private var readerPool: Pool! + + /// The pool of reader connections. + /// It is constant, until close() sets it to nil. + private var readerPool: Pool? @LockedBox var databaseSnapshotCount = 0 @@ -153,7 +156,7 @@ public final class DatabasePool: DatabaseWriter { /// executed the *body* block. fileprivate func forEachConnection(_ body: (Database) -> Void) { writer.sync(body) - readerPool.forEach { $0.sync(body) } + readerPool?.forEach { $0.sync(body) } } } @@ -169,8 +172,8 @@ extension DatabasePool { // Release writer memory writer.sync { $0.releaseMemory() } // Release readers memory by closing all connections - readerPool.barrier { - readerPool.removeAll() + readerPool?.barrier { + readerPool?.removeAll() } } @@ -222,11 +225,34 @@ extension DatabasePool { extension DatabasePool: DatabaseReader { + public func close() throws { + try readerPool?.barrier { + // Close writer connection first. If we can't close it, + // don't close readers. + // + // This allows us to exit this method as fully closed (read and + // writes fail), or not closed at all (reads and writes succeed). + // + // Unfortunately, this introduces a regression for + // https://github.com/groue/GRDB.swift/issues/739. + // TODO: fix this regression. + try writer.sync { try $0.close() } + + // OK writer is closed. Now close readers and + // eventually prevent any future read access + defer { readerPool = nil } + + try readerPool?.forEach { reader in + try reader.sync { try $0.close() } + } + } + } + // MARK: - Interrupting Database Operations public func interrupt() { writer.interrupt() - readerPool.forEach { $0.interrupt() } + readerPool?.forEach { $0.interrupt() } } // MARK: - Database Suspension @@ -277,35 +303,11 @@ extension DatabasePool: DatabaseReader { // MARK: - Reading from Database - /// Synchronously executes a read-only block in a protected dispatch queue, - /// and returns its result. The block is wrapped in a deferred transaction. - /// - /// let players = try dbPool.read { db in - /// try Player.fetchAll(...) - /// } - /// - /// The block is completely isolated. Eventual concurrent database updates - /// are *not visible* inside the block: - /// - /// try dbPool.read { db in - /// // Those two values are guaranteed to be equal, even if the - /// // `wine` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// } - /// - /// try dbPool.read { db in - /// // Now this value may be different: - /// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would - /// happen while establishing the read access to the database. - public func read(_ block: (Database) throws -> T) throws -> T { + public func read(_ value: (Database) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool = readerPool else { + throw DatabaseError.connectionIsClosed() + } return try readerPool.get { reader in try reader.sync { db in var result: T? = nil @@ -313,7 +315,7 @@ extension DatabasePool: DatabaseReader { // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { try db.clearSchemaCacheIfNeeded() - result = try block(db) + result = try value(db) return .commit } return result! @@ -321,22 +323,7 @@ extension DatabasePool: DatabaseReader { } } - /// Asynchronously executes a read-only block in a protected dispatch queue. - /// - /// let players = try dbQueue.asyncRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } - /// } - /// - /// Attempts to write in the database from this method throw a DatabaseError - /// of resultCode `SQLITE_READONLY`. - /// - /// - parameter block: A block that accesses the database. - public func asyncRead(_ block: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping (Result) -> Void) { // First async jump in order to grab a reader connection. // Honor configuration dispatching (qos/targetQueue). let label = configuration.identifier( @@ -346,7 +333,10 @@ extension DatabasePool: DatabaseReader { .makeDispatchQueue(label: label) .async { do { - let (reader, releaseReader) = try self.readerPool.get() + guard let readerPool = self.readerPool else { + throw DatabaseError.connectionIsClosed() + } + let (reader, releaseReader) = try readerPool.get() // Second async jump because sync could deadlock if // configuration has a serial targetQueue. @@ -359,19 +349,19 @@ extension DatabasePool: DatabaseReader { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) try db.clearSchemaCacheIfNeeded() - block(.success(db)) + value(.success(db)) } catch { - block(.failure(error)) + value(.failure(error)) } } } catch { - block(.failure(error)) + value(.failure(error)) } } } /// :nodoc: - public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + public func _weakAsyncRead(_ value: @escaping (Result?) -> Void) { // First async jump in order to grab a reader connection. // Honor configuration dispatching (qos/targetQueue). let label = configuration.identifier( @@ -381,18 +371,21 @@ extension DatabasePool: DatabaseReader { .makeDispatchQueue(label: label) .async { [weak self] in guard let self = self else { - block(nil) + value(nil) return } do { - let (reader, releaseReader) = try self.readerPool.get() + guard let readerPool = self.readerPool else { + throw DatabaseError.connectionIsClosed() + } + let (reader, releaseReader) = try readerPool.get() // Second async jump because sync could deadlock if // configuration has a serial targetQueue. reader.weakAsync { db in guard let db = db else { - block(nil) + value(nil) return } @@ -404,101 +397,54 @@ extension DatabasePool: DatabaseReader { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) try db.clearSchemaCacheIfNeeded() - block(.success(db)) + value(.success(db)) } catch { - block(.failure(error)) + value(.failure(error)) } } } catch { - block(.failure(error)) + value(.failure(error)) } } } - /// Synchronously executes a read-only block in a protected dispatch queue, - /// and returns its result. - /// - /// The block argument is not isolated: eventual concurrent database updates - /// are visible inside the block: - /// - /// try dbPool.unsafeRead { db in - /// // Those two values may be different because some other thread - /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// } - /// - /// Cursor iteration is safe, though: - /// - /// try dbPool.unsafeRead { db in - /// // No concurrent update can mess with this iteration: - /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") - /// while let row = try rows.next() { ... } - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would - /// happen while establishing the read access to the database. - public func unsafeRead(_ block: (Database) throws -> T) throws -> T { + public func unsafeRead(_ value: (Database) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool = readerPool else { + throw DatabaseError.connectionIsClosed() + } return try readerPool.get { reader in try reader.sync { db in try db.clearSchemaCacheIfNeeded() - return try block(db) + return try value(db) } } } - /// Synchronously executes a read-only block in a protected dispatch queue, - /// and returns its result. - /// - /// The block argument is not isolated: eventual concurrent database updates - /// are visible inside the block: - /// - /// try dbPool.unsafeReentrantRead { db in - /// // Those two values may be different because some other thread - /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// } - /// - /// Cursor iteration is safe, though: - /// - /// try dbPool.unsafeReentrantRead { db in - /// // No concurrent update can mess with this iteration: - /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") - /// while let row = try rows.next() { ... } - /// } - /// - /// This method is reentrant. It is unsafe because it fosters dangerous - /// concurrency practices. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would - /// happen while establishing the read access to the database. - public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { - return try reader.reentrantSync(block) + return try reader.reentrantSync(value) } else { + guard let readerPool = readerPool else { + throw DatabaseError.connectionIsClosed() + } return try readerPool.get { reader in try reader.sync { db in try db.clearSchemaCacheIfNeeded() - return try block(db) + return try value(db) } } } } - public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { // The semaphore that blocks until futureResult is defined: let futureSemaphore = DispatchSemaphore(value: 0) var futureResult: Result? = nil asyncConcurrentRead { dbResult in // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try block(db) } } + futureResult = dbResult.flatMap { db in Result { try value(db) } } futureSemaphore.signal() } @@ -512,18 +458,19 @@ extension DatabasePool: DatabaseReader { /// Performs the same job as asyncConcurrentRead. /// /// :nodoc: - public func spawnConcurrentRead(_ block: @escaping (Result) -> Void) { - asyncConcurrentRead(block) + public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + asyncConcurrentRead(value) } - /// Asynchronously executes a read-only block in a protected dispatch queue. + /// Asynchronously executes a read-only function in a protected + /// dispatch queue. /// /// This method must be called from a writing dispatch queue, outside of any /// transaction. You'll get a fatal error otherwise. /// - /// The *block* argument is guaranteed to see the database in the last - /// committed state at the moment this method is called. Eventual concurrent - /// database updates are *not visible* inside the block. + /// The `value` function is guaranteed to see the database in the last + /// committed state at the moment this method is called. Eventual + /// concurrent database updates are not visible from the function. /// /// This method returns as soon as the isolation guarantees described above /// are established. @@ -550,8 +497,8 @@ extension DatabasePool: DatabaseReader { /// try Player(...).insert(db) /// } /// - /// - parameter block: A block that accesses the database. - public func asyncConcurrentRead(_ block: @escaping (Result) -> Void) { + /// - parameter value: A function that accesses the database. + public func asyncConcurrentRead(_ value: @escaping (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -568,6 +515,9 @@ extension DatabasePool: DatabaseReader { let isolationSemaphore = DispatchSemaphore(value: 0) do { + guard let readerPool = readerPool else { + throw DatabaseError.connectionIsClosed() + } let (reader, releaseReader) = try readerPool.get() reader.async { db in defer { @@ -625,7 +575,7 @@ extension DatabasePool: DatabaseReader { try db.clearSchemaCacheIfNeeded() } catch { isolationSemaphore.signal() - block(.failure(error)) + value(.failure(error)) return } @@ -633,11 +583,11 @@ extension DatabasePool: DatabaseReader { // can release the writer queue. isolationSemaphore.signal() - block(.success(db)) + value(.success(db)) } } catch { isolationSemaphore.signal() - block(.failure(error)) + value(.failure(error)) } // Block the writer queue until snapshot isolation success or error @@ -652,12 +602,16 @@ extension DatabasePool: DatabaseReader { /// Eventual concurrent read-only accesses are not invalidated: they will /// proceed until completion. public func invalidateReadOnlyConnections() { - readerPool.removeAll() + readerPool?.removeAll() } /// Returns a reader that can be used from the current dispatch queue, /// if any. private var currentReader: SerializedDatabase? { + guard let readerPool = readerPool else { + return nil + } + var readers: [SerializedDatabase] = [] readerPool.forEach { reader in // We can't check for reader.onValidQueue here because @@ -679,54 +633,20 @@ extension DatabasePool: DatabaseReader { // MARK: - Writing in Database - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database updates are postponed until the updates - /// are completed. - /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. - /// - /// This method is *not* reentrant. - /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) } - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Updates are guaranteed an exclusive access to the database. They wait - /// until all pending writes and reads are completed. They postpone all - /// other writes and reads until they are completed. - /// - /// This method is *not* reentrant. - /// - /// - important: Reads executed by concurrent *database snapshots* are not - /// considered: they can run concurrently with the barrier updates. - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - try readerPool.barrier { + // TODO: throw instead of crashing when the database is closed + try readerPool!.barrier { try writer.sync(updates) } } - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Updates are guaranteed an exclusive access to the database. They wait - /// until all pending writes and reads are completed. They postpone all - /// other writes and reads until they are completed. - /// - /// - important: Reads executed by concurrent *database snapshots* are not - /// considered: they can run concurrently with the barrier updates. - /// - parameter updates: The updates to the database. public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - readerPool.asyncBarrier { + // TODO: throw instead of crashing when the database is closed + readerPool!.asyncBarrier { self.writer.sync(updates) } } @@ -771,17 +691,6 @@ extension DatabasePool: DatabaseReader { } } - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database updates are postponed until the updates - /// are completed. - /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. - /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { try writer.reentrantSync(updates) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 7264c583e..a763b67cf 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -69,6 +69,10 @@ public final class DatabaseQueue: DatabaseWriter { // Explicit unregistration is required before OS X 10.11. NotificationCenter.default.removeObserver(self) } + + public func close() throws { + try writer.sync { try $0.close() } + } } extension DatabaseQueue { @@ -174,49 +178,20 @@ extension DatabaseQueue { // MARK: - Reading from Database - /// Synchronously executes a read-only block in a protected dispatch queue, - /// and returns its result. - /// - /// let players = try dbQueue.read { db in - /// try Player.fetchAll(db) - /// } - /// - /// This method is *not* reentrant. - /// - /// Attempts to write in the database from this method throw a DatabaseError - /// of resultCode `SQLITE_READONLY`. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - public func read(_ block: (Database) throws -> T) throws -> T { + public func read(_ value: (Database) throws -> T) throws -> T { try writer.sync { db in // The transaction guarantees snapshot isolation against eventual // external connection. var result: T? try db.inTransaction(.deferred) { - result = try db.readOnly { try block(db) } + result = try db.readOnly { try value(db) } return .commit } return result! } } - /// Asynchronously executes a read-only block in a protected dispatch queue. - /// - /// let players = try dbQueue.asyncRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } - /// } - /// - /// Attempts to write in the database from this method throw a DatabaseError - /// of resultCode `SQLITE_READONLY`. - /// - /// - parameter block: A block that accesses the database. - public func asyncRead(_ block: @escaping (Result) -> Void) { + public func asyncRead(_ value: @escaping (Result) -> Void) { writer.async { db in do { // The transaction guarantees snapshot isolation against eventual @@ -224,11 +199,11 @@ extension DatabaseQueue { try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { - block(.failure(error)) + value(.failure(error)) return } - block(.success(db)) + value(.success(db)) // Ignore error because we can not notify it. try? db.endReadOnly() @@ -237,10 +212,10 @@ extension DatabaseQueue { } /// :nodoc: - public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { + public func _weakAsyncRead(_ value: @escaping (Result?) -> Void) { writer.weakAsync { db in guard let db = db else { - block(nil) + value(nil) return } @@ -250,11 +225,11 @@ extension DatabaseQueue { try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { - block(.failure(error)) + value(.failure(error)) return } - block(.success(db)) + value(.success(db)) // Ignore error because we can not notify it. try? db.endReadOnly() @@ -262,39 +237,15 @@ extension DatabaseQueue { } } - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// let players = try dbQueue.unsafeRead { db in - /// try Player.fetchAll(db) - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - /// - /// :nodoc: - public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - try writer.sync(block) + public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { + try writer.sync(value) } - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// let players = try dbQueue.unsafeReentrantRead { db in - /// try Player.fetchAll(db) - /// } - /// - /// This method is reentrant. It is unsafe because it fosters dangerous - /// concurrency practices. - /// - /// :nodoc: - public func unsafeReentrantRead(_ block: (Database) throws -> T) rethrows -> T { - try writer.reentrantSync(block) + public func unsafeReentrantRead(_ value: (Database) throws -> T) rethrows -> T { + try writer.reentrantSync(value) } - public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { + public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { // DatabaseQueue can't perform parallel reads. // Perform a blocking read instead. return DatabaseFuture(Result { @@ -306,7 +257,7 @@ extension DatabaseQueue { // external connection. var result: T? try db.inTransaction(.deferred) { - result = try db.readOnly { try block(db) } + result = try db.readOnly { try value(db) } return .commit } return result! @@ -317,7 +268,7 @@ extension DatabaseQueue { /// Performs the same job as asyncConcurrentRead. /// /// :nodoc: - public func spawnConcurrentRead(_ block: @escaping (Result) -> Void) { + public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -327,11 +278,11 @@ extension DatabaseQueue { try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { - block(.failure(error)) + value(.failure(error)) return } - block(.success(db)) + value(.success(db)) // Ignore error because we can not notify it. try? db.endReadOnly() @@ -378,41 +329,14 @@ extension DatabaseQueue { } } - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database accesses are postponed until the updates - /// are completed. - /// - /// This method is *not* reentrant. - /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) } - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database accesses are postponed until the updates - /// are completed. - /// - /// This method is *not* reentrant. - /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) } - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database accesses are postponed until the updates - /// are completed. - /// - /// - parameter updates: The updates to the database. public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { writer.async(updates) } @@ -420,35 +344,24 @@ extension DatabaseQueue { /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// - /// // INSERT INTO player ... - /// let players = try dbQueue.inDatabase { db in - /// try Player(...).insert(db) - /// } + /// Eventual concurrent database updates are postponed until the updates + /// are completed. + /// + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. /// /// This method is *not* reentrant. /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) } - /// Synchronously executes database updates in a protected dispatch queue, and - /// returns the result. - /// - /// // INSERT INTO player ... - /// try dbQueue.unsafeReentrantWrite { db in - /// try Player(...).insert(db) - /// } - /// - /// This method is reentrant. It is unsafe because it fosters dangerous - /// concurrency practices. public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { try writer.reentrantSync(updates) } - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction. public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { writer.async(updates) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 74c5ab21f..be083967c 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -24,6 +24,28 @@ public protocol DatabaseReader: AnyObject { /// The database configuration var configuration: Configuration { get } + /// Closes the database connection with the `sqlite3_close()` function. + /// + /// **Note**: You DO NOT HAVE to call this method, and you SHOULD NOT call + /// it unless the correct execution of your program depends on precise + /// database closing. Database connections are automatically closed when + /// they are deinitialized, and this is sufficient for most applications. + /// + /// If this method does not throw, then the database is properly closed, and + /// every future database access will throw a `DatabaseError` of + /// code `SQLITE_MISUSE`. + /// + /// Otherwise, there exists concurrent database accesses or living prepared + /// statements that prevent the database from closing, and this method + /// throws a `DatabaseError` of code `SQLITE_BUSY`. + /// See for more information. + /// + /// After an error has been thrown, the database may still be opened, and + /// you can keep on accessing it. It may also remain in a "zombie" state, + /// in which case it will throw `SQLITE_MISUSE` for all future + /// database accesses. + func close() throws + // MARK: - Interrupting Database Operations /// This method causes any pending database operation to abort and return at @@ -87,15 +109,22 @@ public protocol DatabaseReader: AnyObject { // MARK: - Read From Database - /// Synchronously executes a read-only block that takes a database + /// Synchronously executes a read-only function that accepts a database /// connection, and returns its result. /// - /// Guarantee 1: the block argument is isolated. Eventual concurrent - /// database updates are not visible inside the block: + /// For example: + /// + /// let count = try reader.read { db in + /// try Player.fetchCount(db) + /// } + /// + /// The `value` function runs in an isolated fashion: eventual concurrent + /// database updates are not visible from the function: /// /// try reader.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `player` table is modified between the two requests: + /// // `player` table is modified, between the two requests, by + /// // some other database connection or some other thread. /// let count1 = try Player.fetchCount(db) /// let count2 = try Player.fetchCount(db) /// } @@ -105,25 +134,34 @@ public protocol DatabaseReader: AnyObject { /// let count = try Player.fetchCount(db) /// } /// - /// Guarantee 2: attempts to write in the database throw a DatabaseError - /// whose resultCode is `SQLITE_READONLY`. + /// Attempts to write in the database throw a DatabaseError with + /// resultCode `SQLITE_READONLY`. /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would + /// It is a programmer error to call this method from another database + /// access method: + /// + /// try reader.read { db in + /// // Raises a fatal error + /// try reader.read { ... ) + /// } + /// + /// - parameter value: A function that accesses the database. + /// - throws: The error thrown by `value`, or any `DatabaseError` that would /// happen while establishing the read access to the database. - func read(_ block: (Database) throws -> T) throws -> T + func read(_ value: (Database) throws -> T) throws -> T - /// Asynchronously executes a read-only block that takes a + /// Asynchronously executes a read-only function that accepts a /// database connection. /// - /// Guarantee 1: the block argument is isolated. Eventual concurrent - /// database updates are not visible inside the block: + /// The `value` function runs in an isolated fashion: eventual concurrent + /// database updates are not visible from the function: /// - /// try reader.asyncRead { dbResult in + /// reader.asyncRead { dbResult in /// do { /// let db = try dbResult.get() /// // Those two values are guaranteed to be equal, even if the - /// // `player` table is modified between the two requests: + /// // `player` table is modified, between the two requests, by + /// // some other database connection or some other thread. /// let count1 = try Player.fetchCount(db) /// let count2 = try Player.fetchCount(db) /// } catch { @@ -131,81 +169,83 @@ public protocol DatabaseReader: AnyObject { /// } /// } /// - /// Guarantee 2: attempts to write in the database throw a DatabaseError - /// whose resultCode is `SQLITE_READONLY`. + /// Attempts to write in the database throw a DatabaseError with + /// resultCode `SQLITE_READONLY`. /// - /// - parameter block: A block that accesses the database. - func asyncRead(_ block: @escaping (Result) -> Void) + /// - parameter value: A function that accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the read access to the database. + func asyncRead(_ value: @escaping (Result) -> Void) /// Same as asyncRead, but without retaining self /// /// :nodoc: - func _weakAsyncRead(_ block: @escaping (Result?) -> Void) + func _weakAsyncRead(_ value: @escaping (Result?) -> Void) - /// Synchronously executes a read-only block that takes a database + /// Synchronously executes a function that accepts a database /// connection, and returns its result. /// - /// The two guarantees of the safe `read` method are lifted: + /// For example: /// - /// The block argument is not isolated: eventual concurrent database updates - /// are visible inside the block: + /// let count = try reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// + /// The guarantees of the `read` method are lifted: + /// + /// the `value` function is not isolated: eventual concurrent database + /// updates are visible from the function: /// /// try reader.unsafeRead { db in - /// // Those two values may be different because some other thread - /// // may have inserted or deleted a player between the two requests: + /// // Those two values can be different, because some other + /// // database connection or some other thread may modify the + /// // database between the two requests. /// let count1 = try Player.fetchCount(db) /// let count2 = try Player.fetchCount(db) /// } /// - /// Cursor iterations are isolated, though: - /// - /// try reader.unsafeRead { db in - /// // No concurrent update can mess with this iteration: - /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") - /// while let row = try rows.next() { ... } - /// } - /// - /// The block argument is not prevented from writing (DatabaseQueue, in + /// The `value` function is not prevented from writing (DatabaseQueue, in /// particular, will accept database modifications in `unsafeRead`). /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would + /// It is a programmer error to call this method from another database + /// access method: + /// + /// try reader.read { db in + /// // Raises a fatal error + /// try reader.unsafeRead { ... ) + /// } + /// + /// - parameter value: A function that accesses the database. + /// - throws: The error thrown by `value`, or any `DatabaseError` that would /// happen while establishing the read access to the database. - func unsafeRead(_ block: (Database) throws -> T) throws -> T + func unsafeRead(_ value: (Database) throws -> T) throws -> T - /// Synchronously executes a block that takes a database connection, and - /// returns its result. + /// Synchronously executes a function that accepts a database + /// connection, and returns its result. /// - /// The two guarantees of the safe `read` method are lifted: + /// The guarantees of the safe `read` method are lifted: /// - /// The block argument is not isolated: eventual concurrent database updates - /// are visible inside the block: + /// the `value` function is not isolated: eventual concurrent database + /// updates are visible from the function: /// /// try reader.unsafeReentrantRead { db in - /// // Those two values may be different because some other thread - /// // may have inserted or deleted a player between the two requests: + /// // Those two values can be different, because some other + /// // database connection or some other thread may modify the + /// // database between the two requests. /// let count1 = try Player.fetchCount(db) /// let count2 = try Player.fetchCount(db) /// } /// - /// Cursor iterations are isolated, though: - /// - /// try reader.unsafeReentrantRead { db in - /// // No concurrent update can mess with this iteration: - /// let rows = try Row.fetchCursor(db, sql: "SELECT ...") - /// while let row = try rows.next() { ... } - /// } - /// - /// The block argument is not prevented from writing (DatabaseQueue, in - /// particular, will accept database modifications in `unsafeReentrantRead`). - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block, or any DatabaseError that would - /// happen while establishing the read access to the database. + /// The `value` function is not prevented from writing (DatabaseQueue, in + /// particular, will accept database modifications in `unsafeRead`). /// /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. - func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T + /// + /// - parameter value: A function that accesses the database. + /// - throws: The error thrown by `value`, or any `DatabaseError` that would + /// happen while establishing the read access to the database. + func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T // MARK: - Value Observation @@ -400,6 +440,10 @@ public final class AnyDatabaseReader: DatabaseReader { base.configuration } + public func close() throws { + try base.close() + } + // MARK: - Interrupting Database Operations public func interrupt() { @@ -408,25 +452,25 @@ public final class AnyDatabaseReader: DatabaseReader { // MARK: - Reading from Database - public func read(_ block: (Database) throws -> T) throws -> T { - try base.read(block) + public func read(_ value: (Database) throws -> T) throws -> T { + try base.read(value) } - public func asyncRead(_ block: @escaping (Result) -> Void) { - base.asyncRead(block) + public func asyncRead(_ value: @escaping (Result) -> Void) { + base.asyncRead(value) } /// :nodoc: - public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { - base._weakAsyncRead(block) + public func _weakAsyncRead(_ value: @escaping (Result?) -> Void) { + base._weakAsyncRead(value) } - public func unsafeRead(_ block: (Database) throws -> T) throws -> T { - try base.unsafeRead(block) + public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + try base.unsafeRead(value) } - public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - try base.unsafeReentrantRead(block) + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + try base.unsafeReentrantRead(value) } // MARK: - Value Observation diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 18349a9dc..e05f14409 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -348,6 +348,14 @@ public protocol DatabaseRegionConvertible { func databaseRegion(_ db: Database) throws -> DatabaseRegion } +#if compiler(>=5.5) +extension DatabaseRegionConvertible where Self == DatabaseRegion { + /// The region that covers the full database: all columns and all rows + /// from all tables. + public static var fullDatabase: Self { DatabaseRegion.fullDatabase } +} +#endif + extension DatabaseRegion: DatabaseRegionConvertible { /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 768ce697e..356169c75 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -61,6 +61,10 @@ public class DatabaseSnapshot: DatabaseReader { try? db.commit() } } + + public func close() throws { + try serializedDatabase.sync { try $0.close() } + } } // DatabaseReader @@ -74,48 +78,25 @@ extension DatabaseSnapshot { // MARK: - Reading from Database - /// Synchronously executes a read-only block that takes a database - /// connection, and returns its result. - /// - /// let players = try snapshot.read { db in - /// try Player.fetchAll(...) - /// } - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { try serializedDatabase.sync(block) } - /// Asynchronously executes a read-only block in a protected dispatch queue. - /// - /// let players = try snapshot.asyncRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } - /// } - /// - /// - parameter block: A block that accesses the database. - public func asyncRead(_ block: @escaping (Result) -> Void) { - serializedDatabase.async { block(.success($0)) } + public func asyncRead(_ value: @escaping (Result) -> Void) { + serializedDatabase.async { value(.success($0)) } } /// :nodoc: - public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { - serializedDatabase.weakAsync { block($0.map { .success($0) }) } + public func _weakAsyncRead(_ value: @escaping (Result?) -> Void) { + serializedDatabase.weakAsync { value($0.map { .success($0) }) } } - /// :nodoc: - public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - try serializedDatabase.sync(block) + public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { + try serializedDatabase.sync(value) } - /// :nodoc: - public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - try serializedDatabase.reentrantSync(block) + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + try serializedDatabase.reentrantSync(value) } // MARK: - Database Observation diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 1f5fd8d46..ee8558f09 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -35,7 +35,13 @@ public protocol DatabaseWriter: DatabaseReader { /// Eventual concurrent reads are guaranteed to not see any partial updates /// of the database until the transaction has completed. /// - /// This method is *not* reentrant. + /// It is a programmer error to call this method from another database + /// access method: + /// + /// try writer.write { db in + /// // Raises a fatal error + /// try writer.write { ... ) + /// } /// /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates, or by the @@ -51,7 +57,13 @@ public protocol DatabaseWriter: DatabaseReader { /// Eventual concurrent reads may see partial updates unless you wrap them /// in a transaction. /// - /// This method is *not* reentrant. + /// It is a programmer error to call this method from another database + /// access method: + /// + /// try writer.write { db in + /// // Raises a fatal error + /// try writer.writeWithoutTransaction { ... ) + /// } /// /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. @@ -64,7 +76,13 @@ public protocol DatabaseWriter: DatabaseReader { /// until all pending writes and reads are completed. They postpone all /// other writes and reads until they are completed. /// - /// This method is *not* reentrant. + /// It is a programmer error to call this method from another database + /// access method: + /// + /// try writer.write { db in + /// // Raises a fatal error + /// try writer.barrierWriteWithoutTransaction { ... ) + /// } /// /// - parameter updates: The updates to the database. /// - throws: The error thrown by the updates. @@ -164,7 +182,7 @@ public protocol DatabaseWriter: DatabaseReader { /// // Guaranteed to be zero /// let count = try future.wait() /// } - func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture + func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -202,28 +220,11 @@ public protocol DatabaseWriter: DatabaseReader { /// /// - parameter block: A block that accesses the database. /// :nodoc: - func spawnConcurrentRead(_ block: @escaping (Result) -> Void) + func spawnConcurrentRead(_ value: @escaping (Result) -> Void) } extension DatabaseWriter { - /// Synchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result. - /// - /// If the updates throw an error, the transaction is rollbacked and the - /// error is rethrown. - /// - /// Eventual concurrent database updates are postponed until the transaction - /// has completed. - /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. - /// - /// This method is *not* reentrant. - /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates, or by the - /// wrapping transaction. public func write(_ updates: (Database) throws -> T) throws -> T { try writeWithoutTransaction { db in var result: T? @@ -303,11 +304,8 @@ extension DatabaseWriter { // MARK: - Erasing the content of the database /// Erases the content of the database. - /// - /// - precondition: database is not accessed concurrently during the - /// execution of this method. public func erase() throws { - try writeWithoutTransaction { try $0.erase() } + try barrierWriteWithoutTransaction { try $0.erase() } } // MARK: - Claiming Disk Space @@ -617,6 +615,10 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.configuration } + public func close() throws { + try base.close() + } + // MARK: - Interrupting Database Operations public func interrupt() { @@ -625,34 +627,34 @@ public final class AnyDatabaseWriter: DatabaseWriter { // MARK: - Reading from Database - public func read(_ block: (Database) throws -> T) throws -> T { - try base.read(block) + public func read(_ value: (Database) throws -> T) throws -> T { + try base.read(value) } - public func asyncRead(_ block: @escaping (Result) -> Void) { - base.asyncRead(block) + public func asyncRead(_ value: @escaping (Result) -> Void) { + base.asyncRead(value) } /// :nodoc: - public func _weakAsyncRead(_ block: @escaping (Result?) -> Void) { - base._weakAsyncRead(block) + public func _weakAsyncRead(_ value: @escaping (Result?) -> Void) { + base._weakAsyncRead(value) } - public func unsafeRead(_ block: (Database) throws -> T) throws -> T { - try base.unsafeRead(block) + public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + try base.unsafeRead(value) } - public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - try base.unsafeReentrantRead(block) + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + try base.unsafeReentrantRead(value) } - public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { - base.concurrentRead(block) + public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + base.concurrentRead(value) } /// :nodoc: - public func spawnConcurrentRead(_ block: @escaping (Result) -> Void) { - base.spawnConcurrentRead(block) + public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + base.spawnConcurrentRead(value) } // MARK: - Writing in Database diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 0e3d8f43f..038375728 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -59,7 +59,7 @@ final class SerializedDatabase { // // So let's close the database now. The deinitializer // will only close the database if needed. - db.close() + db.close_v2() throw error } } @@ -68,7 +68,7 @@ final class SerializedDatabase { deinit { // Database may be deallocated in its own queue: allow reentrancy reentrantSync { db in - db.close() + db.close_v2() } } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 3778d1075..52f55892d 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -47,6 +47,27 @@ import Foundation /// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { + /// Controls how migrations handle foreign keys constraints. + public enum ForeignKeyChecks { + /// The migration runs with disabled foreign keys, until foreign keys + /// are checked right before changes are committed on disk. + /// + /// These deferred checks are not executed if the migrator comes + /// from `disablingDeferredForeignKeyChecks()`. + /// + /// Deferred foreign key checks are necessary for migrations that + /// perform schema changes as described in + /// + case deferred + + /// The migration runs for foreign keys on. + /// + /// Immediate foreign key checks are not compatible with migrations that + /// perform schema changes as described in + /// + case immediate + } + /// When the `eraseDatabaseOnSchemaChange` flag is true, the migrator will /// automatically wipe out the full database content, and recreate the whole /// database from scratch, if it detects that a migration has changed its @@ -72,12 +93,50 @@ public struct DatabaseMigrator { /// 2. When the database content can easily be recreated, such as a cache /// for some downloaded data. public var eraseDatabaseOnSchemaChange = false + private var defersForeignKeyChecks = true private var _migrations: [Migration] = [] /// A new migrator. public init() { } + // MARK: - Disabling Foreign Key Checks + + /// Returns a migrator that will not perform deferred foreign key checks in + /// all newly registered migrations. + /// + /// The returned migrator is _unsafe_, because it no longer guarantees the + /// integrity of the database. It is your responsibility to register + /// migrations that do not break foreign key constraints. + /// + /// Running migrations without foreign key checks can improve migration + /// performance on huge databases. + /// + /// Example: + /// + /// var migrator = DatabaseMigrator() + /// migrator.registerMigration("A") { db in + /// // Runs with deferred foreign key checks + /// } + /// migrator.registerMigration("B", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } + /// + /// migrator = migrator.disablingDeferredForeignKeyChecks() + /// migrator.registerMigration("C") { db in + /// // Runs with disabled foreign key checks + /// } + /// migrator.registerMigration("D", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } + /// + /// - warning: Before using this unsafe method, try to run your migrations with + /// `.immediate` foreign key checks, if possible. This may enhance migration + /// performances, while preserving the database integrity guarantee. + public func disablingDeferredForeignKeyChecks() -> DatabaseMigrator { + with { $0.defersForeignKeyChecks = false } + } + // MARK: - Registering Migrations /// Registers a migration. @@ -92,10 +151,40 @@ public struct DatabaseMigrator { /// /// - parameters: /// - identifier: The migration identifier. + /// - foreignKeyChecks: This parameter is ignored if the database has + /// not enabled foreign keys. + /// + /// The default `.deferred` checks have the migration run with + /// disabled foreign keys, until foreign keys are checked right before + /// changes are committed on disk. These deferred checks are not + /// executed if the migrator comes + /// from `disablingDeferredForeignKeyChecks()`. + /// + /// The `.immediate` checks have the migration run with foreign + /// keys enabled. + /// + /// Only use `.immediate` if you are sure that the migration does not + /// perform schema changes described in + /// /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, migrate: migrate)) + public mutating func registerMigration( + _ identifier: String, + foreignKeyChecks: ForeignKeyChecks = .deferred, + migrate: @escaping (Database) throws -> Void) + { + let migrationChecks: Migration.ForeignKeyChecks + switch foreignKeyChecks { + case .deferred: + if defersForeignKeyChecks { + migrationChecks = .deferred + } else { + migrationChecks = .disabled + } + case .immediate: + migrationChecks = .immediate + } + registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate)) } // MARK: - Applying Migrations @@ -252,6 +341,7 @@ public struct DatabaseMigrator { } private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { + try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") let appliedIdentifiers = try self.appliedMigrations(db) // Subsequent migration must not be applied @@ -271,7 +361,6 @@ public struct DatabaseMigrator { return } - try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") for migration in unappliedMigrations { try migration.run(db) } @@ -347,6 +436,8 @@ public struct DatabaseMigrator { } } +extension DatabaseMigrator: Refinable { } + #if canImport(Combine) extension DatabaseMigrator { // MARK: - Publishing Migrations diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 7550cf407..36676d017 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,17 +1,31 @@ /// An internal struct that defines a migration. struct Migration { + enum ForeignKeyChecks { + case deferred + case immediate + case disabled + } + let identifier: String + var foreignKeyChecks: ForeignKeyChecks let migrate: (Database) throws -> Void func run(_ db: Database) throws { if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { - try runWithDeferredForeignKeysChecks(db) + switch foreignKeyChecks { + case .deferred: + try runWithDeferredForeignKeysChecks(db) + case .immediate: + try runWithImmediateForeignKeysChecks(db) + case .disabled: + try runWithDisabledForeignKeysChecks(db) + } } else { - try runWithoutDisabledForeignKeys(db) + try runWithImmediateForeignKeysChecks(db) } } - private func runWithoutDisabledForeignKeys(_ db: Database) throws { + private func runWithImmediateForeignKeysChecks(_ db: Database) throws { try db.inTransaction(.immediate) { try migrate(db) try insertAppliedIdentifier(db) @@ -19,6 +33,21 @@ struct Migration { } } + private func runWithDisabledForeignKeysChecks(_ db: Database) throws { + try db.execute(sql: "PRAGMA foreign_keys = OFF") + try throwingFirstError( + execute: { + try db.inTransaction(.immediate) { + try migrate(db) + try insertAppliedIdentifier(db) + return .commit + } + }, + finally: { + try db.execute(sql: "PRAGMA foreign_keys = ON") + }) + } + private func runWithDeferredForeignKeysChecks(_ db: Database) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter @@ -38,23 +67,7 @@ struct Migration { // > then run PRAGMA foreign_key_check to verify that the // > schema change did not break any foreign // > key constraints. - if try db - .makeStatement(sql: "PRAGMA foreign_key_check") - .makeCursor() - .isEmpty() == false - { - // https://www.sqlite.org/pragma.html#pragma_foreign_key_check - // - // PRAGMA foreign_key_check does not return an error, - // but the list of violated foreign key constraints. - // - // Let's turn any violation into an - // SQLITE_CONSTRAINT_FOREIGNKEY error, and rollback - // the transaction. - throw DatabaseError( - resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, - message: "FOREIGN KEY constraint failed") - } + try db.checkForeignKeys() // > 11. Commit the transaction started in step 2. return .commit diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 490ff67d9..ae557f96b 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -410,6 +410,20 @@ extension QueryInterfaceRequest { } } +// MARK: - Check Existence + +extension QueryInterfaceRequest { + /// Returns true if the request matches no row in the database. + /// + /// try Player.filter(Column("name") == "Arthur").isEmpty(db) + /// + /// - parameter db: A database connection. + /// - returns: Whether the request matches no row in the database. + public func isEmpty(_ db: Database) throws -> Bool { + try !SQLRequest("SELECT \(exists())").fetchOne(db)! + } +} + // MARK: - Batch Delete extension QueryInterfaceRequest { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 39bafad3e..72a9ccccc 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -1,3 +1,18 @@ +import Foundation + +// MARK: - TypedRequest + +/// The protocol for all requests that know how database rows should +/// be interpreted. +public protocol TypedRequest { + /// The type that can decode database rows. + /// + /// In the request below, it is Book: + /// + /// let request = Book.all() + associatedtype RowDecoder +} + // MARK: - SelectionRequest /// The protocol for all requests that can refine their selection. @@ -221,7 +236,7 @@ public protocol TableRequest { func aliased(_ alias: TableAlias) -> Self } -extension TableRequest where Self: FilteredRequest { +extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// Creates a request filtered by primary key. /// @@ -246,7 +261,38 @@ extension TableRequest where Self: FilteredRequest { -> Self where Sequence.Element: DatabaseValueConvertible { - let keys = Array(keys) + // In order to encode keys in the database, we perform a runtime check + // for EncodableRecord, and look for a customized encoding strategy. + // Such dynamic dispatch is unusual in GRDB, but static dispatch + // (customizing TableRequest where RowDecoder: EncodableRecord) would + // make it impractical to define `filter(id:)`, `fetchOne(_:key:)`, + // `deleteAll(_:ids:)` etc. + if let recordType = RowDecoder.self as? EncodableRecord.Type { + if Sequence.Element.self == Date.self { + let strategy = recordType.databaseDateEncodingStrategy + let keys = keys.compactMap { strategy.encode($0 as! Date)?.databaseValue } + return filter(rawKeys: keys) + } else if Sequence.Element.self == UUID.self { + let strategy = recordType.databaseUUIDEncodingStrategy + let keys = keys.map { strategy.encode($0 as! UUID).databaseValue } + return filter(rawKeys: keys) + } + } + + return filter(rawKeys: keys) + } + + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) + /// let request = try Player...filter(encodedKeys: [1, 2, 3]) + /// + /// - parameter keys: A collection of primary keys + func filter(rawKeys: Sequence) + -> Self + where Sequence.Element: DatabaseValueConvertible + { + let keys = Array(rawKeys) if keys.isEmpty { return none() } @@ -309,8 +355,16 @@ extension TableRequest where Self: FilteredRequest { return key // Preserve ordering of columns in the unique index .sorted { (kv1, kv2) in - let index1 = lowercaseColumns.firstIndex(of: kv1.key.lowercased())! - let index2 = lowercaseColumns.firstIndex(of: kv2.key.lowercased())! + guard let index1 = lowercaseColumns.firstIndex(of: kv1.key.lowercased()) else { + // We allow extra columns which are not in the unique key + // Put them last in the query + return false + } + guard let index2 = lowercaseColumns.firstIndex(of: kv2.key.lowercased()) else { + // We allow extra columns which are not in the unique key + // Put them last in the query + return true + } return index1 < index2 } .map { (column, value) in Column(column) == value } @@ -324,7 +378,7 @@ extension TableRequest where Self: FilteredRequest { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension TableRequest where Self: FilteredRequest, - Self: JoinableRequest, // for RowDecoder + Self: TypedRequest, RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { @@ -355,7 +409,7 @@ where Self: FilteredRequest, @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension TableRequest where Self: FilteredRequest, - Self: JoinableRequest, // for RowDecoder + Self: TypedRequest, RowDecoder: Identifiable, RowDecoder.ID: _OptionalProtocol, RowDecoder.ID.Wrapped: DatabaseValueConvertible @@ -612,21 +666,7 @@ public protocol _JoinableRequest { } /// The protocol for all requests that can be associated. -public protocol JoinableRequest: _JoinableRequest { - /// The record type that can be associated to. - /// - /// In the request below, it is Book: - /// - /// let request = Book.all() - /// - /// In the `belongsTo` association below, it is Author: - /// - /// struct Book: TableRecord { - /// // BelongsToAssociation - /// static let author = belongsTo(Author.self) - /// } - associatedtype RowDecoder -} +public protocol JoinableRequest: TypedRequest, _JoinableRequest { } extension JoinableRequest { /// Creates a request that prefetches an association. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 2a6481328..adce66876 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1236,6 +1236,97 @@ extension Table { } } +// MARK: - Check Existence by Single-Column Primary Key + +extension Table { + /// Returns whether a row exists for this primary key. + /// + /// try Table("player").exists(db, key: 123) + /// try Table("country").exists(db, key: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Table("document").exists(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a row exists for this primary key. + public func exists(_ db: Database, key: PrimaryKeyType) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + try !filter(key: key).isEmpty(db) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: DatabaseValueConvertible +{ + /// Returns whether a row exists for this primary key. + /// + /// try Table("player").exists(db, id: 123) + /// try Table("player").exists(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Table("document").exists(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a row exists for this primary key. + public func exists(_ db: Database, id: RowDecoder.ID) throws -> Bool { + try !filter(id: id).isEmpty(db) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Returns whether a row exists for this primary key. + /// + /// try Table("player").exists(db, id: 123) + /// try Table("country").exists(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Table("document").exists(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a row exists for this primary key. + public func exists(_ db: Database, id: RowDecoder.ID.Wrapped) throws -> Bool { + try !filter(id: id).isEmpty(db) + } +} + +// MARK: - Check Existence by Key + +extension Table { + /// Returns whether a row exists for this unique key (primary key or any key + /// with a unique index on it). + /// + /// Table("player").exists(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a row exists for this key. + public func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try !filter(key: key).isEmpty(db) + } +} + // MARK: - Deleting by Single-Column Primary Key extension Table { @@ -1343,16 +1434,16 @@ where RowDecoder: Identifiable, /// database row was deleted. /// /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, id: 123) + /// try Table("player").deleteOne(db, id: 123) /// /// // DELETE FROM country WHERE code = 'FR' - /// try Country.deleteOne(db, id: "FR") + /// try Table("country").deleteOne(db, id: "FR") /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, id: 1) + /// try Table("document").deleteOne(db, id: 1) /// /// - parameters: /// - db: A database connection. diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index e7b296a41..06c1e133c 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -226,48 +226,3 @@ extension ColumnEncoder: SingleValueEncodingContainer { try recordEncoder.encode(value, forKey: key) } } - -@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) -private var iso8601Formatter: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = .withInternetDateTime - return formatter -}() - -extension DatabaseDateEncodingStrategy { - fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? { - switch self { - case .deferredToDate: - return date.databaseValue - case .timeIntervalSinceReferenceDate: - return date.timeIntervalSinceReferenceDate - case .timeIntervalSince1970: - return date.timeIntervalSince1970 - case .millisecondsSince1970: - return Int64(floor(1000.0 * date.timeIntervalSince1970)) - case .secondsSince1970: - return Int64(floor(date.timeIntervalSince1970)) - case .iso8601: - if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { - return iso8601Formatter.string(from: date) - } else { - fatalError("ISO8601DateFormatter is unavailable on this platform.") - } - case .formatted(let formatter): - return formatter.string(from: date) - case .custom(let format): - return format(date) - } - } -} - -extension DatabaseUUIDEncodingStrategy { - fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? { - switch self { - case .deferredToUUID: - return uuid.databaseValue - case .string: - return uuid.uuidString - } - } -} diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 3e8d2c903..47c0c466f 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -111,7 +111,7 @@ public protocol EncodableRecord { /// For example: /// /// struct Player: PersistableProtocol, Encodable { - /// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string + /// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .uppercaseString /// /// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" /// var uuid: UUID @@ -126,7 +126,7 @@ public protocol EncodableRecord { /// For example: /// /// struct Player: PersistableProtocol, Encodable { - /// static let databaseColumnEncodingStrategy: DatabaseUUIDEncodingStrategy = .convertToSnakeCase + /// static let databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy = .convertToSnakeCase /// /// // encoded as player_id /// var playerID: String @@ -374,6 +374,38 @@ public enum DatabaseDateEncodingStrategy { /// Encodes the result of the user-provided function case custom((Date) -> DatabaseValueConvertible?) + + @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) + private static let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }() + + func encode(_ date: Date) -> DatabaseValueConvertible? { + switch self { + case .deferredToDate: + return date.databaseValue + case .timeIntervalSinceReferenceDate: + return date.timeIntervalSinceReferenceDate + case .timeIntervalSince1970: + return date.timeIntervalSince1970 + case .millisecondsSince1970: + return Int64(floor(1000.0 * date.timeIntervalSince1970)) + case .secondsSince1970: + return Int64(floor(date.timeIntervalSince1970)) + case .iso8601: + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { + return Self.iso8601Formatter.string(from: date) + } else { + fatalError("ISO8601DateFormatter is unavailable on this platform.") + } + case .formatted(let formatter): + return formatter.string(from: date) + case .custom(let format): + return format(date) + } + } } // MARK: - DatabaseUUIDEncodingStrategy @@ -384,7 +416,7 @@ public enum DatabaseDateEncodingStrategy { /// For example: /// /// struct Player: EncodableProtocol, Encodable { -/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.string +/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString /// /// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" /// var uuid: UUID @@ -395,8 +427,26 @@ public enum DatabaseUUIDEncodingStrategy { /// It encodes UUIDs as 16-bytes data blobs. case deferredToUUID - /// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" - case string + /// Encodes UUIDs as uppercased strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + case uppercaseString + + /// Encodes UUIDs as lowercased strings such as "e621e1f8-c36c-495a-93fc-0c247a3e6e5f" + case lowercaseString + + /// Encodes UUIDs as uppercased strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + @available(*, deprecated, renamed: "uppercaseString") + public static var string: Self { .uppercaseString } + + func encode(_ uuid: UUID) -> DatabaseValueConvertible { + switch self { + case .deferredToUUID: + return uuid.databaseValue + case .uppercaseString: + return uuid.uuidString + case .lowercaseString: + return uuid.uuidString.lowercased() + } + } } // MARK: - DatabaseColumnEncodingStrategy diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 91303a4bf..de21f85e8 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -223,6 +223,12 @@ private struct _RowDecoder: Decoder { return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key]) } + // Prefetched Rows? + if let prefetchedRows = row.prefetchedRows[key.stringValue] { + let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) + return try T(from: decoder) + } + // Key is not a column, and not a scope. return nil } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index be1f325dc..8751f8ed6 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -201,6 +201,23 @@ extension MutablePersistableRecord { try performInsert(db) } + /// Executes an INSERT statement so that `self` is saved in the database, + /// and return the inserted record. + /// + /// Usage: + /// + /// let player = Player(id: nil, name: "Arthur") + /// let insertedPlayer = try dbQueue.write { db in + /// try player.inserted(db) + /// } + /// print(player.id) // nil + /// print(insertedPlayer.id) // some id + public func inserted(_ db: Database) throws -> Self { + var result = self + try result.insert(db) + return result + } + /// Executes an UPDATE statement. /// /// - parameter db: A database connection. @@ -318,6 +335,23 @@ extension MutablePersistableRecord { try performSave(db) } + /// Executes an INSERT or an UPDATE statement so that `self` is saved in + /// the database, and return the saved record. + /// + /// Usage: + /// + /// let player = Player(id: nil, name: "Arthur") + /// let savedPlayer = try dbQueue.write { db in + /// try player.saved(db) + /// } + /// print(player.id) // nil + /// print(savedPlayer.id) // some id + public func saved(_ db: Database) throws -> Self { + var result = self + try result.save(db) + return result + } + /// Executes a DELETE statement. /// /// The default implementation for delete() invokes performDelete(). diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 9f3f8e623..1e14454ff 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -155,6 +155,94 @@ extension TableRecord { } } +// MARK: - Check Existence by Single-Column Primary Key + +extension TableRecord { + /// Returns whether a row exists for this primary key. + /// + /// try Player.exists(db, key: 123) + /// try Country.exists(db, key: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Document.exists(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a row exists for this primary key. + public static func exists(_ db: Database, key: PrimaryKeyType) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + try !filter(key: key).isEmpty(db) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { + /// Returns whether a row exists for this primary key. + /// + /// try Player.deleteOne(db, id: 123) + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a row exists for this primary key. + public static func exists(_ db: Database, id: ID) throws -> Bool { + try !filter(id: id).isEmpty(db) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord +where Self: Identifiable, + ID: _OptionalProtocol, + ID.Wrapped: DatabaseValueConvertible +{ + /// Returns whether a row exists for this primary key. + /// + /// try Player.deleteOne(db, id: 123) + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a row exists for this primary key. + public static func exists(_ db: Database, id: ID.Wrapped) throws -> Bool { + try !filter(id: id).isEmpty(db) + } +} + +// MARK: - Check Existence by Key + +extension TableRecord { + /// Returns whether a row exists for this unique key (primary key or any key + /// with a unique index on it). + /// + /// try Player.exists(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a row exists for this key. + public static func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try !filter(key: key).isEmpty(db) + } +} + // MARK: - Deleting by Single-Column Primary Key extension TableRecord { diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift new file mode 100644 index 000000000..bb5259b94 --- /dev/null +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -0,0 +1,300 @@ +import Foundation + +/// Controls the extent of the shared database observation +/// of `SharedValueObservation`. +public enum SharedValueObservationExtent { + /// The `SharedValueObservation` starts a single database observation, which + /// ends when the `SharedValueObservation` is deallocated and all + /// subscriptions terminated. + /// + /// This extent prevents the shared observation from recovering from + /// database errors. To recover from database errors, create a new shared + /// `SharedValueObservation` instance. + case observationLifetime + + /// The `SharedValueObservation` ends database observation when the number + /// of subscriptions drops down to zero. The database observation restarts + /// on the next subscription. + /// + /// Database errors can be recovered by resubscribing to the + /// shared observation. + case whileObserved +} + +extension ValueObservation { + /// Returns a shared value observation that shares a single underlying + /// database observation for all subscriptions, and thus spares + /// database resources. + /// + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// For example: + /// + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue) + /// + /// The sharing only applies if you start observing the database from the + /// same `SharedValueObservation` instance: + /// + /// // 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 by providing a scheduler. + /// For example, `.immediate` notifies all values on the main queue as well, + /// and the first one is immediately notified when the start() method + /// is called: + /// + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared( + /// in: dbQueue, + /// scheduling: .immediate) // <- + /// + /// let cancellable = try sharedObservation.start( + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// // <- 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. + /// + /// 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. See `SharedValueObservationExtent` for available options. + /// + /// - parameter reader: A DatabaseReader. + /// - parameter scheduler: A Scheduler. By default, fresh values are + /// dispatched asynchronously on the main queue. + /// - parameter extent: The extent of the shared database observation. + /// - returns: A `SharedValueObservation` + public func shared( + in reader: DatabaseReader, + scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), + extent: SharedValueObservationExtent = .whileObserved) + -> SharedValueObservation + { + SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in + self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange) + } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A shared value observation that shares a single underlying database +/// observation for all subscriptions, and thus spares database resources. +/// +/// For example: +/// +/// 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("Players have changed.") +/// }) +/// +/// The sharing only applies if you start observing the database from the +/// same `SharedValueObservation` instance: +/// +/// // 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(...) +public final class SharedValueObservation { + private let scheduler: ValueObservationScheduler + private let extent: SharedValueObservationExtent + private let startObservation: ValueObservationStart + private let lock = NSRecursiveLock() // support synchronous observation events + + // protected by lock + private var clients: [Client] + private var isObserving = false + private var cancellable: AnyDatabaseCancellable? + private var lastResult: Result? + + private final class Client { + var onError: (Error) -> Void + var onChange: (Element) -> Void + + init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) { + self.onError = onError + self.onChange = onChange + } + } + + fileprivate init( + scheduling scheduler: ValueObservationScheduler, + extent: SharedValueObservationExtent, + startObservation: @escaping ValueObservationStart) + { + self.scheduler = scheduler + self.extent = extent + self.startObservation = startObservation + self.clients = [] + } + + /// Starts observing the database. + /// + /// The observation lasts until the returned cancellable is cancelled + /// or deallocated. + /// + /// For example: + /// + /// 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)") + /// }) + /// + /// - parameter onError: A closure that is provided eventual errors that + /// happen during observation + /// - parameter onChange: A closure that is provided fresh values + /// - returns: a DatabaseCancellable + public func start( + onError: @escaping (Error) -> Void, + onChange: @escaping (Element) -> Void) + -> DatabaseCancellable + { + synchronized { + // Support for reentrancy: a shared immediate observation is + // started from the first value notification of that same shared + // immediate observation. Yeah, users are nasty. + // In this case, self.cancellable is still nil, because we are + // still waiting for the upstream ValueObservation to start. + // But we must not start another one. + let needsStart = !isObserving + + // State change + let client = Client(onError: onError, onChange: onChange) + clients.append(client) + isObserving = true + + // Side effect + if needsStart { + // Self retains the cancellable, so don't have the cancellable retain self. + cancellable = AnyDatabaseCancellable(startObservation( + // onError + { [weak self] error in + self?.handleError(error) + }, + // onChange + { [weak self] element in + self?.handleChange(element) + })) + } else if let result = lastResult { + // Notify last result as an initial value + scheduler.scheduleInitial { + switch result { + case let .failure(error): + onError(error) + case let .success(value): + onChange(value) + } + } + } + + return AnyDatabaseCancellable { + // Retain shared observation (self) until client cancels + self.handleCancel(client) + } + } + } + +#if canImport(Combine) + /// Creates a publisher which tracks changes in database values. + /// + /// For example: + /// + /// let publisher = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue) + /// .publisher() + /// + /// let cancellable = publisher.sink( + /// receiveCompletion: { completion in ... }, + /// receiveValue: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// + /// - returns: A Combine publisher + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func publisher() -> DatabasePublishers.Value { + DatabasePublishers.Value { onError, onChange in + self.start(onError: onError, onChange: onChange) + } + } +#endif + + private func handleError(_ error: Error) { + synchronized { + let notifiedClients = clients + + // State change + clients = [] + if extent == .whileObserved { + isObserving = false + cancellable = nil + lastResult = nil + } else { + lastResult = .failure(error) + } + + // Side effect + for client in notifiedClients { + client.onError(error) + } + } + } + + private func handleChange(_ value: Element) { + synchronized { + // State change + lastResult = .success(value) + + // Side effect + for client in clients { + client.onChange(value) + } + } + } + + private func handleCancel(_ client: Client) { + synchronized { + // State change + clients.removeFirst(where: { $0 === client }) + if clients.isEmpty && extent == .whileObserved { + isObserving = false + cancellable = nil + lastResult = nil + } + } + } + + private func synchronized(_ execute: () throws -> T) rethrows -> T { + lock.lock() + defer { lock.unlock() } + return try execute() + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 86e6f89e5..fe2e5339f 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -52,6 +52,11 @@ struct ValueObservationEvents: Refinable { var didCancel: (() -> Void)? } +typealias ValueObservationStart = ( + _ onError: @escaping (Error) -> Void, + _ onChange: @escaping (T) -> Void) +-> DatabaseCancellable + extension ValueObservation: Refinable { // MARK: - Starting Observation @@ -90,6 +95,9 @@ extension ValueObservation: Refinable { /// }) /// // <- 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 Scheduler. By default, fresh values are /// dispatched asynchronously on the main queue. @@ -261,39 +269,30 @@ extension ValueObservation { scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value { - return DatabasePublishers.Value(self, in: reader, scheduling: scheduler) + DatabasePublishers.Value { [weak reader] (onError, onChange) in + guard let reader = reader else { + return AnyDatabaseCancellable(cancel: { }) + } + return self.start( + in: reader, + scheduling: scheduler, + onError: onError, + onChange: onChange) + } } } @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - fileprivate typealias Start = ( - _ onError: @escaping (Error) -> Void, - _ onChange: @escaping (T) -> Void) -> DatabaseCancellable - /// A publisher that tracks changes in the database. /// /// See `ValueObservation.publisher(in:scheduling:)`. public struct Value: Publisher { public typealias Failure = Error - private let start: Start + private let start: ValueObservationStart - init( - _ observation: ValueObservation, - in reader: DatabaseReader, - scheduling scheduler: ValueObservationScheduler) - where Reducer.Value == Output - { - start = { [weak reader] (onError, onChange) in - guard let reader = reader else { - return AnyDatabaseCancellable(cancel: { }) - } - return observation.start( - in: reader, - scheduling: scheduler, - onError: onError, - onChange: onChange) - } + init(start: @escaping ValueObservationStart) { + self.start = start } public func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { @@ -309,7 +308,7 @@ extension DatabasePublishers { { private struct WaitingForDemand { let downstream: Downstream - let start: Start + let start: ValueObservationStart } private struct Observing { @@ -336,7 +335,7 @@ extension DatabasePublishers { private var lock = NSRecursiveLock() // Allow re-entrancy init( - start: @escaping Start, + start: @escaping ValueObservationStart, downstream: Downstream) { state = .waitingForDemand(WaitingForDemand( diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index cc8036f46..61cce1d97 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -59,6 +59,14 @@ public class ValueObservationScheduler { /// - important: this scheduler requires that the observation is started /// from the main queue. A fatal error is raised otherwise. public static let immediate = ValueObservationScheduler(impl: ImmediateImpl()) + + func scheduleInitial(_ action: @escaping () -> Void) { + if immediateInitialValue() { + action() + } else { + schedule(action) + } + } } private protocol ValueObservationSchedulerImpl { diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d224c905a..921bf2c8e 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 47; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -11,6 +11,10 @@ 56012B6B2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; 56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; }; 56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; }; + 560233CE2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; }; + 560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; }; + 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; }; + 560233D227243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; }; 56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 56043297228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; @@ -380,6 +384,8 @@ 5690C3451D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; }; 5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; }; 5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; }; + 5691D96F27256C490021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96D27256C490021D540 /* AvailableElements.swift */; }; + 5691D97027256C490021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96D27256C490021D540 /* AvailableElements.swift */; }; 56959620222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; }; 56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; }; 56959636222D058B002CB7C9 /* AssociationHasManySQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */; }; @@ -768,6 +774,8 @@ /* Begin PBXFileReference section */ 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; + 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; + 560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -867,6 +875,7 @@ 56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = ""; }; 56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = ""; }; + 5643676E272EDF3700C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 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 = ""; }; @@ -992,6 +1001,7 @@ 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; 5691578B231BF2BE00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; + 5691D96D27256C490021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = ""; }; 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = ""; }; 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = ""; }; @@ -1265,6 +1275,7 @@ isa = PBXGroup; children = ( 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */, + 560233D027243A9100529DF3 /* SharedValueObservation.swift */, 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, @@ -1404,6 +1415,7 @@ 563B06DB2185E04E00B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, @@ -1447,6 +1459,7 @@ 56419A7924A51614004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D96D27256C490021D540 /* AvailableElements.swift */, 56419A7A24A51614004967E1 /* Finished.swift */, 56419A7B24A51614004967E1 /* NextOne.swift */, 56419A7C24A51614004967E1 /* Next.swift */, @@ -1900,6 +1913,7 @@ DC37742D19C8CC90004FCF85 /* GRDB */, F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */, DC10500F19C904DD00D8CA30 /* Tests */, + 5643676E272EDF3700C718C7 /* Scripts */, DC3773F419C8CBB3004FCF85 /* Products */, ); indentWidth = 4; @@ -2125,7 +2139,7 @@ }; }; buildConfigurationList = DC3773ED19C8CBB3004FCF85 /* Build configuration list for PBXProject "GRDBCustom" */; - compatibilityVersion = "Xcode 6.3"; + compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -2213,7 +2227,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; }; 56EB54FD22C9119B00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2231,7 +2245,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; @@ -2362,6 +2376,7 @@ 5656A8842295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, + 560233D227243A9200529DF3 /* SharedValueObservation.swift in Sources */, 5656A85A2295BD56001FF3FF /* SQLGenerationContext.swift in Sources */, 5690C3451D23E82A00E59934 /* Data.swift in Sources */, 5611626C2576BF9D007AAF99 /* JoinAssociation.swift in Sources */, @@ -2493,6 +2508,7 @@ 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, F3BA804C1CFB2B24003DC1BA /* GRDBTestCase.swift in Sources */, 56959620222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */, + 560233CE2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */, 5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, @@ -2514,6 +2530,7 @@ 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 5657AB551D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */, + 5691D97027256C490021D540 /* AvailableElements.swift in Sources */, F3BA81291CFB3063003DC1BA /* RecordInitializersTests.swift in Sources */, 56419C8424A51D6F004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, @@ -2726,6 +2743,7 @@ 5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, + 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */, 5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */, 5690C3421D23E82A00E59934 /* Data.swift in Sources */, 5611626B2576BF9D007AAF99 /* JoinAssociation.swift in Sources */, @@ -2857,6 +2875,7 @@ F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */, 56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */, 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, + 560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */, 56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 563B071221862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */, @@ -2878,6 +2897,7 @@ 5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, + 5691D96F27256C490021D540 /* AvailableElements.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, @@ -3123,7 +3143,8 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -3149,7 +3170,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -3176,10 +3201,15 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; @@ -3194,7 +3224,11 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; @@ -3212,11 +3246,16 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -3238,7 +3277,11 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; @@ -3262,9 +3305,14 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; GCC_NO_COMMON_BLOCKS = YES; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); SKIP_INSTALL = YES; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; @@ -3279,7 +3327,11 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -3298,11 +3350,16 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; diff --git a/Makefile b/Makefile index 2aecaa3ac..9b2bf4a4f 100644 --- a/Makefile +++ b/Makefile @@ -50,71 +50,57 @@ TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with # `xcrun xctrace list devices` (or the deprecated `instruments -s devices`). -ifeq ($(XCODEVERSION),13.0) +ifeq ($(XCODEVERSION),13.1) MAX_SWIFT_VERSION = 5.5 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = 5.3 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.0" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.0" + #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore +else ifeq ($(XCODEVERSION),13.0) + MAX_SWIFT_VERSION = 5.5 + MIN_SWIFT_VERSION = 5.3 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.0" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.0" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" else ifeq ($(XCODEVERSION),12.5) MAX_SWIFT_VERSION = 5.4 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = 5.3 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.5" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=14.5" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" else ifeq ($(XCODEVERSION),12.4) MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.4" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.3" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" else ifeq ($(XCODEVERSION),12.3) MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.3" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.3" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" else ifeq ($(XCODEVERSION),12.2) MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.2" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.2" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" else ifeq ($(XCODEVERSION),12.0) MAX_SWIFT_VERSION = 5.3 - MIN_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=14.0" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.0" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" -else ifeq ($(XCODEVERSION),11.6) - MAX_SWIFT_VERSION = 5.2 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.6" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" -else ifeq ($(XCODEVERSION),11.5) - MAX_SWIFT_VERSION = 5.2 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.5" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" -else ifeq ($(XCODEVERSION),11.4) - MAX_SWIFT_VERSION = 5.2 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4.1" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4" - MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" else - # Swift 5.2 required: Xcode < 11.4 is not supported + # Swift 5.3 required: Xcode < 12.0 is not supported endif # If xcpretty is available, use it for xcodebuild output @@ -147,15 +133,17 @@ else endif # We test framework test suites, and if GRBD can be installed in an application: -test: test_framework test_install +test: test_framework test_archive test_install test_demo_apps test_framework: test_framework_darwin test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framework_SQLCipher test_SPM test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBWatchOS test_framework_GRDBiOS test_framework_GRDBtvOS test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher4 +test_archive: test_archive_GRDBOSX_xcframework test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint test_CocoaPodsLint: test_CocoaPodsLint_GRDB +test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_framework_GRDBOSX: test_framework_GRDBOSX_maxSwift test_framework_GRDBOSX_minSwift @@ -254,6 +242,7 @@ ifdef MIN_SWIFT_VERSION endif test_framework_GRDBtvOS_minTarget: +ifdef MIN_TVOS_DESTINATION $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDBtvOS \ @@ -261,6 +250,7 @@ test_framework_GRDBtvOS_minTarget: SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ $(TEST_ACTIONS) \ $(XCPRETTY) +endif test_framework_GRDBCustomSQLiteOSX: SQLiteCustom $(XCODEBUILD) \ @@ -339,6 +329,24 @@ test_SPM: $(SWIFT) build -c release set -o pipefail && $(SWIFT) test $(XCPRETTY) +test_archive_GRDBOSX_xcframework: + rm -rf Tests/products + mkdir Tests/products + $(XCODEBUILD) archive \ + -project GRDB.xcodeproj \ + -scheme GRDBOSX \ + -configuration Release \ + -destination "generic/platform=macOS" \ + SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ + 'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \ + 'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \ + -archivePath "$(PWD)/Tests/products/GRDB.xcarchive" \ + SKIP_INSTALL=NO \ + BUILD_LIBRARY_FOR_DISTRIBUTION=YES + $(XCODEBUILD) -create-xcframework \ + -framework '$(PWD)/Tests/products/GRDB.xcarchive/Products/Library/Frameworks/GRDB.framework' \ + -output '$(PWD)/Tests/products/GRDB.xcframework' + test_install_manual: $(XCODEBUILD) \ -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ @@ -430,6 +438,24 @@ else @exit 1 endif +test_GRDBDemoiOS: + $(XCODEBUILD) \ + -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ + -scheme GRDBDemoiOS \ + -destination $(MAX_IOS_DESTINATION) \ + SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ + $(TEST_ACTIONS) \ + $(XCPRETTY) + +test_GRDBCombineDemo: + $(XCODEBUILD) \ + -project Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj \ + -scheme GRDBCombineDemo \ + -destination $(MAX_IOS_DESTINATION) \ + SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ + $(TEST_ACTIONS) \ + $(XCPRETTY) + test_performance: $(XCODEBUILD) \ -project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj \ @@ -462,10 +488,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.12.0 \ - --module-version 5.12.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.13.0 \ + --module-version 5.13.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.12/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.13/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 5af35dacf..7a183b65d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

A toolkit for SQLite databases, with a focus on application development

- Swift 5.2 + Swift 5.3 Platforms License CI Status @@ -11,13 +11,14 @@ --- -**Latest release**: September 25, 2021 • version 5.12.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: November 7, 2021 • version 5.13.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) -**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+ +**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.2+** | **v5.12.0** | +| **Swift 5.3+** | **v5.13.0** | +| 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) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -316,7 +317,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.12/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.13/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -350,7 +351,7 @@ Documentation - [Unicode](#unicode) - [Memory Management](#memory-management) - [Data Protection](#data-protection) -- [Concurrency](#concurrency) +- [Concurrency] #### General Guides & Good Practices @@ -492,7 +493,7 @@ let newPlaceCount = try dbQueue.write { db -> Int in When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). -**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. +**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide. > :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS. @@ -510,7 +511,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.12/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html) for more details. ## Database Pools @@ -569,9 +570,9 @@ let newPlaceCount = try dbPool.write { db -> Int in When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). -- Database pools can take [snapshots](#database-snapshots) of the database. +- Database pools can take [snapshots](Documentation/Concurrency.md#database-snapshots) of the database. -**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency](#concurrency) chapter for more details about database pools, how they differ from database queues, and advanced use cases. +**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency] guide for more details about database pools, how they differ from database queues, and advanced use cases. > :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool. @@ -590,7 +591,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.12/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -650,7 +651,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -908,7 +909,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.12/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.13/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -987,7 +988,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1272,7 +1273,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1605,7 +1606,7 @@ In order to customize the JSON format, provide a custom implementation of the `D **A transaction** is a fundamental tool of SQLite that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. -GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic: +GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](Documentation/Concurrency.md#safe-and-unsafe-database-accesses), and provide maximal security for both your application data and application logic: ```swift // BEGIN TRANSACTION @@ -1719,7 +1720,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.12/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1831,7 +1832,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1914,7 +1915,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.12/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.13/Classes/Statement.html). ### Prepared Statements Cache @@ -2657,7 +2658,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2717,7 +2718,7 @@ When a type adopts both TableRecord and [FetchableRecord](#fetchablerecord-proto let paris = try Place.filter(nameColumn == "Paris").fetchOne(db) ``` -TableRecord can also fetch records by primary key and unique keys: see [Fetching by Key](#fetching-by-key). +TableRecord can also fetch deal with primary and unique keys: see [Fetching by Key](#fetching-by-key) and [Testing for Record Existence](#testing-for-record-existence). ## PersistableRecord Protocol @@ -2825,45 +2826,51 @@ struct Player: Encodable, MutablePersistableRecord { [Record](#record-class) subclasses and types that adopt [PersistableRecord] are given default implementations for methods that insert, update, and delete: ```swift -// Instance methods -try place.save(db) // INSERT or UPDATE -try place.insert(db) // INSERT -try place.update(db) // UPDATE -try place.update(db, columns: ...) // UPDATE -try place.updateChanges(db, from: ...) // Maybe UPDATE -try place.updateChanges(db) { ... } // Maybe UPDATE -try place.updateChanges(db) // Maybe UPDATE (Record class only) -try place.delete(db) // DELETE -try place.exists(db) +// INSERT +try place.insert(db) +let insertedPlace = try place.inserted(db) // non-mutating + +// UPDATE +try place.update(db) +try place.update(db, columns: ["title"]) + +// Maybe UPDATE +try place.updateChanges(db, from: otherPlace) +try place.updateChanges(db) { $0.isFavorite = true } +try place.updateChanges(db) // Record class only + +// INSERT or UPDATE +try place.save(db) +let savedPlace = place.saved(db) // non-mutating + +// DELETE +try place.delete(db) + +// EXISTENCE CHECK +let exists = try place.exists(db) ``` The [TableRecord] protocol comes with batch operations: ```swift -// Type methods -try Place.updateAll(db, ...) // UPDATE -try Place.deleteAll(db) // DELETE -try Place.deleteAll(db, ids:...) // DELETE -try Place.deleteAll(db, keys:...) // DELETE -try Place.deleteOne(db, id:...) // DELETE -try Place.deleteOne(db, key:...) // DELETE +// UPDATE +try Place.updateAll(db, ...) + +// DELETE +try Place.deleteAll(db) +try Place.deleteAll(db, ids:...) +try Place.deleteAll(db, keys:...) +try Place.deleteOne(db, id:...) +try Place.deleteOne(db, key:...) ``` -- `insert`, `update`, `save` and `delete` can throw a [DatabaseError](#error-handling). +- All those methods can throw a [DatabaseError](#error-handling). -- `update` and `updateChanges` can also throw a [PersistenceError](#persistenceerror), should the update fail because there is no matching row in the database. - - When saving an object that may or may not already exist in the database, prefer the `save` method: +- `update` and `updateChanges` throw [PersistenceError](#persistenceerror) if the database does not contain any row for the primary key of the record. -- `updateAll` performs a batch update. See [Update Requests](#update-requests). +- `save` makes sure your values are stored in the database. It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly performs an INSERT if the record has no primary key, or a null primary key. -- `save` makes sure your values are stored in the database. - - It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly performs an INSERT if the record has no primary key, or a null primary key. - - Despite the fact that it may execute two SQL statements, `save` behaves as an atomic operation: GRDB won't allow any concurrent thread to sneak in (see [concurrency](#concurrency)). - -- `delete` returns whether a database row was deleted or not. +- `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). @@ -3091,7 +3098,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseColumnDecodingStrategy.html), [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseColumnEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3113,57 +3120,42 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.12/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.13/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. -> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). +There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). -> :point_up: **Note**: Customized date and uuid handling only apply during the encoding and decoding of database rows to and from records. *They do not apply* when you define requests based on date or uuid values. +Customized date and uuid handling apply: + +- When encoding and decoding database rows to and from records (fetching and persistence methods). +- In requests by single-column primary key: `fetchOne(_:id:)`, `filter(id:)`, `deleteAll(_:keys:)`, etc. + +*They do not apply* in other requests based on date or uuid values. So make sure that dates and uuids are properly encoded in your requests. For example: ```swift -struct Player: Codable, FetchableRecord, PersistableRecord { +struct Player: Codable, FetchableRecord, PersistableRecord, Identifiable { // UUIDs are stored as strings - static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.string - var uuid: UUID + static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString + var id: UUID ... } try dbQueue.write { db in let uuid = UUID() - let player = Player(uuid: uuid, ...) + let player = Player(id: uuid, ...) - // Inserts a player in the database, with a string uuid + // OK: inserts a player in the database, with a string uuid try player.insert(db) - // BAD: performs a blob-based query, fails to find the inserted player - _ = try Player.filter(Column("uuid") == uuid).fetchOne(db) + // OK: performs a string-based query, finds the inserted player _ = try Player.filter(id: uuid).fetchOne(db) - - // GOOD: performs a string-based query, finds the inserted player - _ = try Player.filter(Column("uuid") == uuid.uuidString).fetchOne(db) - _ = try Player.filter(id: uuid.uuidString).fetchOne(db) -} -``` -The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) suggest to define a specific method in such situation: - -```swift -extension DerivableRequest where RowDecoder == Player { - func filter(uuid: UUID) -> Self { - filter(Column("uuid") == uuid.uuidString) - } -} - -try dbQueue.write { db in - let uuid = UUID() - let player = Player(uuid: uuid, ...) + // NOT OK: performs a blob-based query, fails to find the inserted player + _ = try Player.filter(Column("id") == uuid).fetchOne(db) - // Inserts a player in the database, with a string uuid - try player.insert(db) - - // GOOD: performs a string-based query, finds the inserted player - _ = try Player.all().filter(uuid: uuid).fetchOne(db) + // OK: performs a string-based query, finds the inserted player + _ = try Player.filter(Column("id") == uuid.uuidString).fetchOne(db) } ``` @@ -3939,7 +3931,9 @@ This is the list of record methods, along with their required protocols. The [Re | `record.didInsert(with:for:)` | [PersistableRecord] | | | **Insert and Update Records** | | | | `record.insert(db)` | [PersistableRecord] | | +| `record.inserted(db)` | [PersistableRecord] | | | `record.save(db)` | [PersistableRecord] | | +| `record.saved(db)` | [PersistableRecord] | | | `record.update(db)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | @@ -3957,6 +3951,9 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | | **Check Record Existence** | | | | `record.exists(db)` | [PersistableRecord] | | +| `Type.exists(db, key: ...)` | [TableRecord] | ¹ | +| `Type.exists(db, id: ...)` | [TableRecord] & [Identifiable] | ¹ | +| `Type.filter(...).isEmpty(db)` | [TableRecord] | ² | | **Convert Record to Dictionary** | | | | `record.databaseDictionary` | [EncodableRecord] | | | **Count Records** | | | @@ -4138,6 +4135,7 @@ So don't miss the [SQL API](#sqlite-api). - [SQL Functions](#sql-functions) - [Fetching from Requests] - [Fetching by Key](#fetching-by-key) +- [Testing for Record Existence](#testing-for-record-existence) - [Fetching Aggregated Values](#fetching-aggregated-values) - [Delete Requests](#delete-requests) - [Update Requests](#update-requests) @@ -4644,7 +4642,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.12/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.13/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5129,7 +5127,7 @@ When the table has no explicit primary key, GRDB uses the [hidden "rowid" column ```swift // SELECT * FROM document WHERE rowid = 1 -try Document.fetchOne(db, id: 1) // Document? +try Document.fetchOne(db, key: 1) // Document? ``` **When you want to build a request and plan to fetch from it later**, use a `filter` method: @@ -5142,6 +5140,55 @@ let request = Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"]) ``` +## Testing for Record Existence + +**You can check if a request has matching rows in the database.** + +```swift +// Some request based on `Player` +let request = Player.filter(...)... + +// Check for player existence: +let noSuchPlayer = try request.isEmpty(db) // Bool +``` + +You should check for emptiness instead of counting: + +```swift +// Correct +let noSuchPlayer = try request.fetchCount(db) == 0 +// Even better +let noSuchPlayer = try request.isEmpty(db) +``` + +**You can also check if a given primary or unique key exists in the database.** + +[Identifiable Records] can use the type-safe method `exists(_:id:)`: + +```swift +try Player.exists(db, id: 1) +try Country.exists(db, id: "FR") +``` + +All record types can use `exists(_:key:)` that can check primary and unique keys: + +```swift +try Player.exists(db, key: 1) +try Country.exists(db, key: "FR") +try Player.exists(db, key: ["email": "arthur@example.com"]) +try Citizenship.exists(db, key: ["citizenId": 1, "countryCode": "FR"]) +``` + +You should check for key existence instead of fetching a record and checking for nil: + +```swift +// Correct +let playerExists = try Player.fetchOne(db, id: 1) != nil +// Even better +let playerExists = try Player.exists(db, id: 1) +``` + + ## Fetching Aggregated Values **Requests can count.** The `fetchCount()` method returns the number of rows that would be returned by a fetch request: @@ -5363,7 +5410,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.12/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.13/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -5752,13 +5799,14 @@ try dbQueue.write { db in 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). -> :point_up: **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. +> :point_up: **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) - [ValueObservation Performance](#valueobservation-performance) - :blue_book: [Combine Publisher](Documentation/Combine.md#database-observation) @@ -5858,10 +5906,12 @@ let cancellable = observation.publisher(in: dbQueue).sink( }) ``` +See [Combine Support] for more information. +

- RxGRDB example + RxSwift example ```swift import GRDB @@ -5877,6 +5927,8 @@ let disposable = observation.rx.observe(in: dbQueue).subscribe( onError: { error in ... }) ``` +See the companion library [RxGRDB] for more information. +
**Generally speaking**: @@ -6088,6 +6140,91 @@ let observation = ValueObservation 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) +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``` + +> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there are a few differences you should be aware of: +> +> - `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may 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(...) +> ``` +> +> - Unlike `ValueObservation`, `SharedValueObservation` retains the database connection. As long as there exists a `SharedValueObservation` instance, or an active suscription to a shared observation, the database connection won't be deinitialized. + + ### ValueObservation Performance This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. @@ -6110,20 +6247,7 @@ When needed, you can help GRDB optimize observations and reduce database content 2. :bulb: **Tip**: Share observations when possible. - Each call to the `start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing a single active observation. - - For example, with RxSwift and RxGRDB, you can use the `share(replay:scope:)` operator: - - ```swift - import GRDB - import RxGRDB - import RxSwift - - let observation = ValueObservation.tracking(Player.fetchAll) - let observable = observation.rx - .observe(in: dbQueue) - .share(replay: 1, scope: .whileConnected) - ``` + 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. @@ -6416,7 +6540,7 @@ do { > :point_up: **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], [ValueObservation], [Combine Support], and [RxGRDB] are all based on the TransactionObserver protocol. +[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. @@ -6541,7 +6665,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.12/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.13/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -6551,7 +6675,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati 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](http://groue.github.io/GRDB.swift/docs/5.12/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.13/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -6713,7 +6837,7 @@ try dbPool.barrierWriteWithoutTransaction { db in > } > ``` -> :point_up: **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed. +> :point_up: **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](Documentation/Concurrency.md#database-snapshots) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed. > :point_up: **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database). @@ -6908,12 +7032,12 @@ try dbQueue.write { db in } // throws SQLITE_ABORT ``` -You can catch both `SQLITE_INTERRUPT` and `SQLITE_ABORT` errors with the `DatabaseError.isInterruptionError` property: +You can catch both `SQLITE_INTERRUPT` and `SQLITE_ABORT` errors: ```swift do { try dbPool.write { db in ... } -} catch let error as DatabaseError where error.isInterruptionError { +} catch DatabaseError.SQLITE_INTERRUPT, DatabaseError.SQLITE_ABORT { // Oops, the database was interrupted. } ``` @@ -7358,552 +7482,6 @@ When a database is protected, an application that runs in the background on a lo You can catch those errors and wait for [UIApplicationDelegate.applicationProtectedDataDidBecomeAvailable(_:)](https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623044-applicationprotecteddatadidbecom) or [UIApplicationProtectedDataDidBecomeAvailable](https://developer.apple.com/reference/uikit/uiapplicationprotecteddatadidbecomeavailable) notification in order to retry the failed database operation. -## Concurrency - -- [Guarantees and Rules](#guarantees-and-rules) -- [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools) -- [Advanced DatabasePool](#advanced-databasepool) -- [Database Snapshots](#database-snapshots) -- [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols) -- [Asynchronous APIs](#asynchronous-apis) -- [Unsafe Concurrency APIs](#unsafe-concurrency-apis) -- :blue_book: [Sharing a Database] - - -### Guarantees and Rules - -GRDB ships with three concurrency modes: - -- [DatabaseQueue](#database-queues) opens a single database connection, and serializes all database accesses. -- [DatabasePool](#database-pools) manages a pool of several database connections, and allows concurrent reads and writes. -- [DatabaseSnapshot](#database-snapshots) opens a single read-only database connection on an unchanging database content, and (currently) serializes all database accesses - -**All foster application safety**: regardless of the concurrency mode you choose, GRDB provides you with the same guarantees, as long as you follow three rules. - -- :bowtie: **Guarantee 1: writes are always serialized**. At every moment, there is no more than a single thread that is writing into the database. - - > Database writes always happen in a unique serial dispatch queue, named the *writer protected dispatch queue*. - -- :bowtie: **Guarantee 2: reads are always isolated**. This means that they are guaranteed an immutable view of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic: - - ```swift - try dbPool.read { db in // or dbQueue.read - // Guaranteed to be equal - let count1 = try Player.fetchCount(db) - let count2 = try Player.fetchCount(db) - } - ``` - - > In [database queues](#database-queues), reads happen in the same protected dispatch queue as writes: isolation is just a consequence of the serialization of database accesses - > - > [Database pools](#database-pools) and [snapshots](#database-snapshots) both use the "snapshot isolation" made possible by SQLite's WAL mode (see [Isolation In SQLite](https://sqlite.org/isolation.html)). - -- :bowtie: **Guarantee 3: requests don't fail**, unless a database constraint violation, a [programmer mistake](#error-handling), or a very low-level issue such as a disk error or an unreadable database file. GRDB grants *correct* use of SQLite, and particularly avoids locking errors and other SQLite misuses. - -Those guarantees hold as long as you follow three rules: - -- :point_up: **Rule 1**: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file. - - This means that opening a new connection each time you access the database is a bad idea. Do share a single connection instead. - - See the [Demo Applications] for sample code that sets up a single database queue that is available throughout the application. - - See [Sharing a Database] for the specific setup required by applications that share their database files. - - ```swift - // SAFE CONCURRENCY - func fetchCurrentUser(_ db: Database) throws -> User? { - try User.fetchOne(db) - } - // dbQueue is a singleton defined somewhere in your app - let user = try dbQueue.read { db in // or dbPool.read - try fetchCurrentUser(db) - } - - // UNSAFE CONCURRENCY - // This method fails when some other thread is currently writing into - // the database. - func currentUser() throws -> User? { - let dbQueue = try DatabaseQueue(...) - return try dbQueue.read { db in - try User.fetchOne(db) - } - } - let user = try currentUser() - ``` - -- :point_up: **Rule 2**: Group related statements within a single call to a DatabaseQueue or DatabasePool database access method (or use [snapshots](#database-snapshots)). - - Database access methods isolate your groups of related statements against eventual database updates performed by other threads, and guarantee a consistent view of the database. This isolation is only guaranteed *inside* the closure argument of those methods. Two consecutive calls *do not* guarantee isolation: - - ```swift - // SAFE CONCURRENCY - try dbPool.read { db in // or dbQueue.read - // Guaranteed to be equal: - let count1 = try Place.fetchCount(db) - let count2 = try Place.fetchCount(db) - } - - // UNSAFE CONCURRENCY - // Those two values may be different because some other thread may have - // modified the database between the two blocks: - let count1 = try dbPool.read { db in try Place.fetchCount(db) } - let count2 = try dbPool.read { db in try Place.fetchCount(db) } - ``` - - In the same vein, when you fetch values that depends on some database updates, group them: - - ```swift - // SAFE CONCURRENCY - try dbPool.write { db in - // The count is guaranteed to be non-zero - try Place(...).insert(db) - let count = try Place.fetchCount(db) - } - - // UNSAFE CONCURRENCY - // The count may be zero because some other thread may have performed - // a deletion between the two blocks: - try dbPool.write { db in try Place(...).insert(db) } - let count = try dbPool.read { db in try Place.fetchCount(db) } - ``` - - On that last example, see [Advanced DatabasePool](#advanced-databasepool) if you look after extra performance. - -- :point_up: **Rule 3**: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a [transaction](#transactions-and-savepoints). - - ```swift - // SAFE CONCURRENCY - try dbPool.write { db in // or dbQueue.write - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - } - - // SAFE CONCURRENCY - try dbPool.writeInTransaction { db in // or dbQueue.inTransaction - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit - } - - // UNSAFE CONCURRENCY - try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccount, amount).insert(db) - // <- Concurrent dbPool.read sees a partial db update here - try Debit(sourceAccount, amount).insert(db) - } - ``` - - Without transaction, `DatabasePool.read { ... }` may see the first statement, but not the second, and access a database where the balance of accounts is not zero. A highly bug-prone situation. - - So do use [transactions](#transactions-and-savepoints) in order to guarantee database consistency across your application threads: that's what they are made for. - - -### Differences between Database Queues and Pools - -Despite the common [guarantees and rules](#guarantees-and-rules) shared by [database queues](#database-queues) and [pools](#database-pools), those two database accessors don't have the same behavior. - -**Database queues** serialize all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes: - -![DatabaseQueueScheduling](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/DatabaseQueueScheduling.svg) - -**Database pools** also serialize all writes. But they allow concurrent reads and writes, and isolate reads so that they don't see changes performed by other threads. This gives a very different picture: - -![DatabasePoolScheduling](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/DatabasePoolScheduling.svg) - -See how, with database pools, two reads can see different database states at the same time. - -For more information about database pools, grab information about SQLite [WAL mode](https://www.sqlite.org/wal.html) and [snapshot isolation](https://sqlite.org/isolation.html). See [Database Observation] when you look after automatic notifications of database changes. - - -### Advanced DatabasePool - -- [The `concurrentRead` Method](#the-concurrentread-method) -- [The `barrierWriteWithoutTransaction` Method](#the-barrierwritewithouttransaction-method) - - -#### The `concurrentRead` Method - -[Database pools](#database-pools) are very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database. - -When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid locking the writer queue longer than necessary: - -```swift -try dbPool.write { db in - // Increment the number of players - try Player(...).insert(db) - - // Read the number of players. The writer queue is still locked :-( - let count = try Player.fetchCount(db) -} -``` - -A wrong solution is to chain a write then a read, as below. Don't do that, because another thread may modify the database in between, and make the read unreliable: - -```swift -// WRONG -try dbPool.write { db in - // Increment the number of players - try Player(...).insert(db) -} -// <- other threads can write in the database here -try dbPool.read { db in - // Read some random value :-( - let count = try Player.fetchCount(db) -} -``` - -The correct solution is the `concurrentRead` method, which must be called from within a write block, outside of any transaction. - -`concurrentRead` returns a **future value** which you consume on any dispatch queue, with the `wait()` method: - -```swift -// CORRECT -let futureCount: DatabaseFuture = try dbPool.writeWithoutTransaction { db in - // increment the number of players - try Player(...).insert(db) - - // <- not in a transaction here - let futureCount = dbPool.concurrentRead { db - try Player.fetchCount(db) - } - return futureCount -} -// <- The writer queue has been unlocked :-) - -// Wait for the player count -let count: Int = try futureCount.wait() -``` - -`concurrentRead` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. - -The closure can run concurrently with eventual updates performed after `concurrentRead`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion: - -```swift -try dbPool.writeWithoutTransaction { db in - // Increment the number of players - try Player(...).insert(db) - - let futureCount = dbPool.concurrentRead { db - // Guaranteed to be non-zero - try Player.fetchCount(db) - } - - try Player.deleteAll(db) -} -``` - -[Transaction Observers](#transactionobserver-protocol) can also use `concurrentRead` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database. - - -#### The `barrierWriteWithoutTransaction` Method - -```swift -try dbPool.barrierWriteWithoutTransaction { db in - // Exclusive database access -} -``` - -The barrier write guarantees exclusive access to the database: the method blocks until all concurrent database accesses are completed, reads and writes, and postpones all other accesses until it completes. - -There is a known limitation: reads performed by [database snapshots](#database-snapshots) are out of scope, and may run concurrently with the barrier. - - - -### Database Snapshots - -**[Database pool](#database-pools) can take snapshots.** A database snapshot sees an unchanging database content, as it existed at the moment it was created. - -"Unchanging" means that a snapshot never sees any database modifications 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)). - -You create snapshots from a [database pool](#database-pools): - -```swift -let snapshot = try dbPool.makeSnapshot() -``` - -You can create as many snapshots as you need, regardless of the [maximum number of readers](#databasepool-configuration) in the pool. A snapshot database connection is closed when the snapshot gets deinitialized. - -**A snapshot can be used from any thread.** Its `read` methods is synchronous, and blocks the current thread until your database statements are executed: - -```swift -// Read values: -try snapshot.read { db in - let players = try Player.fetchAll(db) - let playerCount = try Player.fetchCount(db) -} - -// Extract a value from the database: -let playerCount = try snapshot.read { db in - try Player.fetchCount(db) -} -``` - -When you want to control the latest committed changes seen by a snapshot, create the snapshot from the pool's writer protected dispatch queue, outside of any transaction: - -```swift -let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in - try db.inTransaction { - // delete all players - try Player.deleteAll() - return .commit - } - - // <- not in a transaction here - return dbPool.makeSnapshot() -} -// <- Other threads may modify the database here -let snapshot2 = try dbPool.makeSnapshot() - -try snapshot1.read { db in - // Guaranteed to be zero - try Player.fetchCount(db) -} - -try snapshot2.read { db in - // Could be anything - try Player.fetchCount(db) -} -``` - -> :point_up: **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads. - - -### DatabaseWriter and DatabaseReader Protocols - -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.12/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.12/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. - -These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: - -- [Migrations] -- [DatabaseRegionObservation] -- [ValueObservation] -- [Combine Support] -- [RxGRDB] - -Only five types adopt those protocols: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. Expanding this set is not supported: any future GRDB release may break your custom writers and readers, without notice. - -DatabaseReader and DatabaseWriter provide the *smallest* common guarantees: they don't erase the differences between queues, pools, and snapshots. See for example [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools). - -However, you can prevent some parts of your application from writing in the database by giving them a DatabaseReader: - -```swift -// This class can read in the database, but can't write into it. -class MyReadOnlyComponent { - let reader: DatabaseReader - - init(reader: DatabaseReader) { - self.reader = reader - } -} - -let dbQueue: DatabaseQueue = ... -let component = MyReadOnlyComponent(reader: dbQueue) -``` - -> :point_up: **Note**: DatabaseReader is not a **secure** way to prevent an application component from writing in the database, because write access is just a cast away: -> -> ```swift -> if let dbQueue = reader as? DatabaseQueue { -> try dbQueue.write { ... } -> } -> ``` - - -### Asynchronous APIs - -**Database queues, pools, snapshots, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide asynchronous database access methods.** - -- [`asyncRead`](#asyncread) -- [`asyncWrite`](#asyncwrite) -- [`asyncWriteWithoutTransaction`](#asyncwritewithouttransaction) -- [`asyncConcurrentRead`](#asyncconcurrentread) - - -#### `asyncRead` - -The `asyncRead` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue: - -```swift -reader.asyncRead { (dbResult: Result) in - do { - let db = try dbResult.get() - let players = try Player.fetchAll(db) - } catch { - // handle error - } -} -``` - -The argument function accepts a standard `Result` which may contain a failure if it was impossible to start a reading access to the database. - -Any attempt at modifying the database throws an error. - -When you use a [database queue](#database-queues) or a [database snapshot](#database-snapshots), the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete. - -When you use a [database pool](#database-pools), reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). - - -#### `asyncWrite` - -The `asyncWrite` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, wrapped inside a [database transaction](#transactions-and-savepoints): - -```swift -writer.asyncWrite({ (db: Database) in - try Player(...).insert(db) -}, completion: { (db: Database, result: Result) in - switch result { - case let .success: - // handle transaction success - case let .failure(error): - // handle transaction error - } -}) -``` - -`asyncWrite` accepts two function arguments. The first one executes your database updates. The second one is a completion function which accepts a database connection and the result of the asynchronous transaction. - -On the first unhandled error during database updates, all changes are reverted, the whole transaction is rollbacked, and the error is passed to the completion function. - -When the transaction completes successfully, the result of the first function is contained in the standard `Result` passed to the completion function: - -```swift -writer.asyncWrite({ (db: Database) -> Int in - try Player(...).insert(db) - return try Player.fetchCount(db) -}, completion: { (db: Database, result: Result) in - switch result { - case let .success(newPlayerCount): - print("new player count: \(newPlayerCount)") - case let .failure(error): - // handle transaction error - } -}) -``` - -The scheduled asynchronous transaction has to wait for any eventual concurrent database write to complete before it can start. - - -#### `asyncWriteWithoutTransaction` - -The `asyncWriteWithoutTransaction` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, outside of any transaction: - -```swift -writer.asyncWriteWithoutTransaction { (db: Database) in - do { - try Player(...).insert(db) - } catch { - // handle error - } -} -``` - -**Writing outside of any transaction is dangerous.** You should almost always prefer the `asyncWrite` method described above. Please see [Transactions and Savepoints](#transactions-and-savepoints) for more information. - -The scheduled asynchronous updates have to wait for any eventual concurrent database write to complete before they can start. - - -#### `asyncConcurrentRead` - -The `asyncConcurrentRead` method is available on database pools only. It is the asynchronous equivalent of the `concurrentRead` described in the [Advanced DatabasePool](#advanced-databasepool) chapter. - -It must be called from a writing dispatch queue, outside of any transaction. You'll get a fatal error otherwise. - -The closure argument is guaranteed to see the database in the last committed state at the moment this method is called. Eventual concurrent database updates are *not visible* inside the block. - -`asyncConcurrentRead` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. - -In the example below, the number of players is fetched concurrently with the player insertion. Yet the future is guaranteed to return zero: - -```swift -try writer.asyncWriteWithoutTransaction { db in - do { - // Delete all players - try Player.deleteAll() - - // <- not in a transaction here - // Count players concurrently - writer.asyncConcurrentRead { (dbResult: Result) in - do { - let db = try dbResult.get() - // Guaranteed to be zero - let count = try Player.fetchCount(db) - } catch { - // handle error - } - } - - // Insert a player - try Player(...).insert(db) - } catch { - // handle error - } -} -``` - - -### Unsafe Concurrency APIs - -**Database queues, pools, snapshots, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide *unsafe* database access methods.** Unsafe APIs lift [concurrency guarantees](#guarantees-and-rules), and allow advanced yet unsafe patterns. - -- **`unsafeRead`** - - The `unsafeRead` method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. GRDB does just the bare minimum to provide a database connection that can read. - - When used on a database pool, reads are no longer isolated: - - ```swift - dbPool.unsafeRead { db in - // Those two values may be different because some other thread - // may have inserted or deleted a player between the two requests: - let count1 = try Player.fetchCount(db) - let count2 = try Player.fetchCount(db) - } - ``` - - When used on a database queue, the closure argument is allowed to write in the database. - -- **`unsafeReentrantRead`** - - The `unsafeReentrantRead` behaves just as `unsafeRead` (see above), and allows reentrant calls: - - ```swift - dbPool.read { db1 in - // No "Database methods are not reentrant" fatal error: - dbPool.unsafeReentrantRead { db2 in - dbPool.unsafeReentrantRead { db3 in - ... - } - } - } - ``` - - Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - - There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. - -- **`unsafeReentrantWrite`** - - The `unsafeReentrantWrite` method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. Writes are serialized: eventual concurrent database updates are postponed until the block has executed. - - Reentrant calls are allowed: - - ```swift - dbQueue.write { db1 in - // No "Database methods are not reentrant" fatal error: - dbQueue.unsafeReentrantWrite { db2 in - dbQueue.unsafeReentrantWrite { db3 in - ... - } - } - } - ``` - - Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - - There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. - - FAQ === @@ -7921,7 +7499,7 @@ FAQ - [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) - [What Are Experimental Features?](#what-are-experimental-features) -- [Does GRDB support library evolution and ABI stability?](does-grdb-support-library-evolution-and-abi-stability) +- [Does GRDB support library evolution and ABI stability?](#does-grdb-support-library-evolution-and-abi-stability) **[FAQ: Associations](#faq-associations)** @@ -7991,10 +7569,15 @@ let dbQueue = try DatabaseQueue(path: dbPath) ### How do I close a database connection? -Database connections are managed by [database queues](#database-queues) and [pools](#database-pools). A connection is closed when its database queue or pool is deinitialized, and all usages of this connection are completed. +Database connections are automatically closed when they are deinitialized. -Database accesses that run in background threads postpone the closing of connections. +When the correct execution of your program depends on precise database closing, use the `close()` method: +```swift +try dbQueue.close() +``` + +This explicit `close()` may fail with an error. See the inline documentation of this method for more information. Generally speaking, you should not call this method: rely on automatic closing instead. ## FAQ: SQL @@ -8050,7 +7633,7 @@ db.trace { event in - :arrow_up: [FAQ] - [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) - [What Are Experimental Features?](#what-are-experimental-features) -- [Does GRDB support library evolution and ABI stability?](does-grdb-support-library-evolution-and-abi-stability) +- [Does GRDB support library evolution and ABI stability?](#does-grdb-support-library-evolution-and-abi-stability) ### How do I monitor the duration of database statements execution? @@ -8077,6 +7660,14 @@ try dbQueue.read { db in } ``` +### What Are Experimental Features? + +Since GRDB 1.0, all backwards compatibility guarantees of [semantic versioning](http://semver.org) apply: no breaking change will happen until the next major version of the library. + +There is an exception, though: *experimental features*, marked with the "**:fire: EXPERIMENTAL**" badge. Those are advanced features that are too young, or lack user feedback. They are not stabilized yet. + +Those experimental features are not protected by semantic versioning, and may break between two minor releases of the library. To help them becoming stable, [your feedback](https://github.com/groue/GRDB.swift/issues) is greatly appreciated. + ### Does GRDB support library evolution and ABI stability? No, GRDB does not support library evolution and ABI stability. The only promise is API stability according to [semantic versioning](http://semver.org), with an exception for [experimental features](#what-are-experimental-features). @@ -8352,7 +7943,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](http://groue.github.io/GRDB.swift/docs/5.12/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.13/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8365,10 +7956,7 @@ When your application should be able to run in the background on a locked device ```swift do { try ... -} catch let error as DatabaseError where - error.resultCode == .SQLITE_IOERR || - error.resultCode == .SQLITE_AUTH -{ +} catch DatabaseError.SQLITE_IOERR, DatabaseError.SQLITE_AUTH { // Handle possible data protection error } ``` @@ -8402,15 +7990,6 @@ let players: [Player] = try dbQueue.read { db in ``` -### What Are Experimental Features? - -Since GRDB 1.0, all backwards compatibility guarantees of [semantic versioning](http://semver.org) apply: no breaking change will happen until the next major version of the library. - -There is an exception, though: *experimental features*, marked with the "**:fire: EXPERIMENTAL**" badge. Those are advanced features that are too young, or lack user feedback. They are not stabilized yet. - -Those experimental features are not protected by semantic versioning, and may break between two minor releases of the library. To help them becoming stable, [your feedback](https://github.com/groue/GRDB.swift/issues) is greatly appreciated. - - Sample Code =========== @@ -8483,6 +8062,38 @@ This protocol has been renamed [TableRecord] in GRDB 3.0. This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation]. +#### Concurrency + +This chapter has [moved](Documentation/Concurrency.md). + +#### Guarantees and Rules + +This chapter is now split into [Concurrency Rules](Documentation/Concurrency.md#concurrency-rules) and [Safe and Unsafe Database Accesses](Documentation/Concurrency.md#safe-and-unsafe-database-accesses). + +#### Differences between Database Queues and Pools + +This chapter has [moved](Documentation/Concurrency.md#differences-between-database-queues-and-pools). + +#### Advanced DatabasePool + +This chapter has [moved](Documentation/Concurrency.md#advanced-databasepool). + +#### Database Snapshots + +This chapter has [moved](Documentation/Concurrency.md#database-snapshots). + +#### DatabaseWriter and DatabaseReader Protocols + +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.13/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.13/Protocols/DatabaseWriter.html). + +#### Asynchronous APIs + +This chapter has [moved](Documentation/Concurrency.md#synchronous-and-asynchronous-database-accesses). + +#### Unsafe Concurrency APIs + +This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-accesses). + [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord @@ -8516,11 +8127,12 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [custom SQLite build]: Documentation/CustomSQLiteBuilds.md [Combine]: https://developer.apple.com/documentation/combine [Combine Support]: Documentation/Combine.md +[Concurrency]: Documentation/Concurrency.md [Demo Applications]: Documentation/DemoApps/README.md [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.12/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.13/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/Scripts/swiftlint.sh b/Scripts/swiftlint.sh new file mode 100755 index 000000000..7781c40d8 --- /dev/null +++ b/Scripts/swiftlint.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -e + +# Support for SwiftLint installed via Homebrew on Apple Silicon +# https://github.com/realm/SwiftLint/issues/2992 +if test -d "/opt/homebrew/bin/"; then + PATH="/opt/homebrew/bin/:${PATH}" +fi + +if which swiftlint >/dev/null; then + swiftlint --config ${SRCROOT}/Scripts/swiftlint.yml +else + echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint" +fi diff --git a/.swiftlint.yml b/Scripts/swiftlint.yml similarity index 95% rename from .swiftlint.yml rename to Scripts/swiftlint.yml index 089f47747..c1d25a25c 100644 --- a/.swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -1,5 +1,5 @@ included: - - GRDB + - ../GRDB disabled_rules: - comment_spacing @@ -26,6 +26,7 @@ disabled_rules: opt_in_rules: - anyobject_protocol - array_init + - capture_variable - closure_spacing - collection_alignment - contains_over_filter_count @@ -33,6 +34,7 @@ opt_in_rules: - contains_over_first_not_nil - contains_over_range_nil_comparison - convenience_type + - discouraged_assert - empty_collection_literal - empty_count - empty_string diff --git a/Support/Info.plist b/Support/Info.plist index 6aa6195ad..927c076bd 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.12.0 + 5.13.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 45a096adb..7adce2aec 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -443,6 +443,8 @@ 5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5641A19F24A540D6004967E1 /* PublisherExpectation.swift */; }; 564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; + 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; + 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; @@ -672,6 +674,7 @@ 564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83BFB5733A86DAA3D0BEE684 /* Pods-GRDBTestsEncrypted.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.debug.xcconfig"; sourceTree = ""; }; @@ -727,6 +730,7 @@ 5641A19724A540D6004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D97427257CE40021D540 /* AvailableElements.swift */, 5641A19824A540D6004967E1 /* Finished.swift */, 5641A19924A540D6004967E1 /* NextOne.swift */, 5641A19A24A540D6004967E1 /* Next.swift */, @@ -1228,6 +1232,7 @@ 56419E3124A54062004967E1 /* SQLLiteralTests.swift in Sources */, 56419E5924A54062004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 56419DC524A54062004967E1 /* AssociationHasManyOrderingTests.swift in Sources */, + 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */, 56419E1B24A54062004967E1 /* RowFetchTests.swift in Sources */, 56419ED924A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */, 56419EAB24A54063004967E1 /* DatabaseValueTests.swift in Sources */, @@ -1451,6 +1456,7 @@ 56419E3224A54062004967E1 /* SQLLiteralTests.swift in Sources */, 56419E5A24A54062004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 56419DC624A54062004967E1 /* AssociationHasManyOrderingTests.swift in Sources */, + 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */, 56419E1C24A54062004967E1 /* RowFetchTests.swift in Sources */, 56419EDA24A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */, 56419EAC24A54063004967E1 /* DatabaseValueTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index e62fc8a7f..61f62b11b 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -445,6 +445,8 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; + 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; + 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; @@ -675,6 +677,7 @@ 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; + 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -717,6 +720,7 @@ 5641A16124A540C7004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D97127257C930021D540 /* AvailableElements.swift */, 5641A16224A540C7004967E1 /* Finished.swift */, 5641A16324A540C7004967E1 /* NextOne.swift */, 5641A16424A540C7004967E1 /* Next.swift */, @@ -1234,6 +1238,7 @@ 56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */, 5641A04A24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */, 5641A17824A540C7004967E1 /* Next.swift in Sources */, + 5691D97227257C930021D540 /* AvailableElements.swift in Sources */, 5641A09624A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5641A0EC24A540A1004967E1 /* AssociationPrefetchingObservationTests.swift in Sources */, 5641A01824A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */, @@ -1457,6 +1462,7 @@ 56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */, 5641A04B24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */, 5641A17924A540C7004967E1 /* Next.swift in Sources */, + 5691D97327257C930021D540 /* AvailableElements.swift in Sources */, 5641A09724A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5641A0ED24A540A1004967E1 /* AssociationPrefetchingObservationTests.swift in Sources */, 5641A01924A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */, diff --git a/Tests/CombineExpectations/PublisherExpectation.swift b/Tests/CombineExpectations/PublisherExpectation.swift index 774511c7e..b8fca0b5a 100644 --- a/Tests/CombineExpectations/PublisherExpectation.swift +++ b/Tests/CombineExpectations/PublisherExpectation.swift @@ -6,10 +6,21 @@ public enum PublisherExpectations { } /// The base protocol for PublisherExpectation. It is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. +/// +/// :nodoc: public protocol _PublisherExpectationBase { /// Sets up an XCTestExpectation. This method is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. func _setup(_ expectation: XCTestExpectation) + + /// Returns an object that waits for the expectation. If nil, expectation + /// is waited by the XCTestCase. + func _makeWaiter() -> XCTWaiter? +} + +extension _PublisherExpectationBase { + /// :nodoc: + public func _makeWaiter() -> XCTWaiter? { nil } } /// The protocol for publisher expectations. @@ -94,7 +105,11 @@ extension XCTestCase { { let expectation = self.expectation(description: description) publisherExpectation._setup(expectation) - wait(for: [expectation], timeout: timeout) + if let waiter = publisherExpectation._makeWaiter() { + waiter.wait(for: [expectation], timeout: timeout) + } else { + wait(for: [expectation], timeout: timeout) + } return try publisherExpectation.get() } } diff --git a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift new file mode 100644 index 000000000..82947bcca --- /dev/null +++ b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift @@ -0,0 +1,62 @@ +#if canImport(Combine) +import XCTest + +@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension PublisherExpectations { + /// A publisher expectation which waits for the timeout to expire, or + /// the recorded publisher to complete. + /// + /// When waiting for this expectation, the publisher error is thrown if + /// the publisher fails before the expectation has expired. + /// + /// Otherwise, an array of all elements published before the expectation + /// has expired is returned. + /// + /// Unlike other expectations, `AvailableElements` does not make a test fail + /// on timeout expiration. It just returns the elements published so far. + /// + /// For example: + /// + /// // SUCCESS: no timeout, no error + /// func testTimerPublishesIncreasingDates() throws { + /// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect() + /// let recorder = publisher.record() + /// let dates = try wait(for: recorder.availableElements, timeout: ...) + /// XCTAssertEqual(dates.sorted(), dates) + /// } + public struct AvailableElements: PublisherExpectation { + let recorder: Recorder + + public func _makeWaiter() -> XCTWaiter? { Waiter() } + + public func _setup(_ expectation: XCTestExpectation) { + recorder.fulfillOnCompletion(expectation) + } + + /// Returns all elements published so far, or throws an error if the + /// publisher has failed. + public func get() throws -> [Input] { + try recorder.value { (elements, completion, remainingElements, consume) in + if case let .failure(error) = completion { + throw error + } + consume(remainingElements.count) + return elements + } + } + + /// A waiter that waits but never fails + private class Waiter: XCTWaiter, XCTWaiterDelegate { + init() { + super.init(delegate: nil) + delegate = self + } + + func waiter(_ waiter: XCTWaiter, didTimeoutWithUnfulfilledExpectations unfulfilledExpectations: [XCTestExpectation]) { } + func waiter(_ waiter: XCTWaiter, fulfillmentDidViolateOrderingConstraintsFor expectation: XCTestExpectation, requiredExpectation: XCTestExpectation) { } + func waiter(_ waiter: XCTWaiter, didFulfillInvertedExpectation expectation: XCTestExpectation) { } + func nestedWaiter(_ waiter: XCTWaiter, wasInterruptedByTimedOutWaiter outerWaiter: XCTWaiter) { } + } + } +} +#endif diff --git a/Tests/CombineExpectations/Recorder.swift b/Tests/CombineExpectations/Recorder.swift index 6120d2415..6b91f405c 100644 --- a/Tests/CombineExpectations/Recorder.swift +++ b/Tests/CombineExpectations/Recorder.swift @@ -277,21 +277,46 @@ public class Recorder: Subscriber { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension PublisherExpectations { - /// The type of the publisher expectation returned by Recorder.completion + /// The type of the publisher expectation returned by `Recorder.completion`. public typealias Completion = Map, Subscribers.Completion> - /// The type of the publisher expectation returned by Recorder.elements + /// The type of the publisher expectation returned by `Recorder.elements`. public typealias Elements = Map, [Input]> - /// The type of the publisher expectation returned by Recorder.last + /// The type of the publisher expectation returned by `Recorder.last`. public typealias Last = Map, Input?> - /// The type of the publisher expectation returned by Recorder.single + /// The type of the publisher expectation returned by `Recorder.single`. public typealias Single = Map, Input> } @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Recorder { + /// Returns a publisher expectation which waits for the timeout to expire, + /// or the recorded publisher to complete. + /// + /// When waiting for this expectation, the publisher error is thrown if + /// the publisher fails before the expectation has expired. + /// + /// Otherwise, an array of all elements published before the expectation + /// has expired is returned. + /// + /// Unlike other expectations, `availableElements` does not make a test fail + /// on timeout expiration. It just returns the elements published so far. + /// + /// For example: + /// + /// // SUCCESS: no timeout, no error + /// func testTimerPublishesIncreasingDates() throws { + /// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect() + /// let recorder = publisher.record() + /// let dates = try wait(for: recorder.availableElements, timeout: ...) + /// XCTAssertEqual(dates.sorted(), dates) + /// } + public var availableElements: PublisherExpectations.AvailableElements { + PublisherExpectations.AvailableElements(recorder: self) + } + /// Returns a publisher expectation which waits for the recorded publisher /// to complete. /// diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift index a55263bb1..a66fb3061 100644 --- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift @@ -20,6 +20,11 @@ private struct TeamInfo: Decodable, FetchableRecord, Equatable { var players: [Player] } +private struct TeamWithOptionalPlayers: Decodable, FetchableRecord, Equatable { + var team: Team + var players: [Player]? +} + /// A usage test for ordered hasMany association class AssociationHasManyOrderingTests: GRDBTestCase { @@ -111,6 +116,58 @@ class AssociationHasManyOrderingTests: GRDBTestCase { } } + func testIncludingAllDecodedAsOptional() throws { + try makeDatabaseQueue().read { db in + do { + let teamInfos = try Team + .orderByPrimaryKey() + .including(all: Team.players) + .asRequest(of: TeamWithOptionalPlayers.self) + .fetchAll(db) + XCTAssertTrue(sqlQueries.contains(""" + SELECT * FROM "team" ORDER BY "id" + """)) + XCTAssertTrue(sqlQueries.contains(""" + SELECT *, "teamId" AS "grdb_teamId" \ + FROM "player" \ + WHERE "teamId" IN (1, 2) \ + ORDER BY "position" + """)) + XCTAssertEqual(teamInfos, [ + TeamWithOptionalPlayers( + team: Team(id: 1, name: "Red"), + players: [ + Player(id: 1, teamId: 1, name: "Arthur", position: 1), + Player(id: 2, teamId: 1, name: "Barbara", position: 2), + Player(id: 3, teamId: 1, name: "Craig", position: 3), + ]), + TeamWithOptionalPlayers( + team: Team(id: 2, name: "Blue"), + players: [ + Player(id: 6, teamId: 2, name: "Fiona", position: 1), + Player(id: 5, teamId: 2, name: "Eugene", position: 2), + Player(id: 4, teamId: 2, name: "Diane", position: 3), + ])]) + } + do { + let teamInfos = try Team + .orderByPrimaryKey() + .asRequest(of: TeamWithOptionalPlayers.self) + .fetchAll(db) + XCTAssertTrue(sqlQueries.contains(""" + SELECT * FROM "team" ORDER BY "id" + """)) + XCTAssertEqual(teamInfos, [ + TeamWithOptionalPlayers( + team: Team(id: 1, name: "Red"), + players: nil), + TeamWithOptionalPlayers( + team: Team(id: 2, name: "Blue"), + players: nil)]) + } + } + } + func testReorderedIncludingAll() throws { try makeDatabaseQueue().read { db in let teamInfos = try Team diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 1d9030aaf..9db22be08 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -190,7 +190,7 @@ class DatabaseConfigurationTests: GRDBTestCase { _ = s2.wait(timeout: .distantFuture) try dbQueue2.inTransaction(.exclusive) { db in return .commit } XCTFail("Expected error") - } catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY { + } catch DatabaseError.SQLITE_BUSY { } catch { XCTFail("\(error)") } @@ -240,7 +240,7 @@ class DatabaseConfigurationTests: GRDBTestCase { // _ = s2.wait(timeout: .distantFuture) // try dbQueue2.inTransaction(.exclusive) { db in return .commit } // XCTFail("Expected error") -// } catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY { +// } catch DatabaseError.SQLITE_BUSY { // } catch { // XCTFail("\(error)") // } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 5c807313a..4247fb829 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -46,16 +46,21 @@ private enum StrategyCustom: StrategyProvider { static let strategy: DatabaseDateEncodingStrategy = .custom { _ in "custom" } } -private struct RecordWithDate: PersistableRecord, Encodable { +private struct RecordWithDate: EncodableRecord, Encodable { static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } var date: Date } -private struct RecordWithOptionalDate: PersistableRecord, Encodable { +private struct RecordWithOptionalDate: EncodableRecord, Encodable { static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } var date: Date? } +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension RecordWithDate: Identifiable { + var id: Date { date } +} + class DatabaseDateEncodingStrategyTests: GRDBTestCase { let testedDates = [ Date(timeIntervalSince1970: -987654.321), @@ -64,7 +69,7 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase { Date(timeIntervalSinceReferenceDate: 123456.789), ] - private func test( + private func test( record: T, expectedStorage: DatabaseValue.Storage) { @@ -210,3 +215,117 @@ extension DatabaseDateEncodingStrategyTests { ]) { test(strategy: StrategyCustom.self, encodesDate: date, as: value) } } } + +// MARK: - Filter + +extension DatabaseDateEncodingStrategyTests { + func testFilterKey() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + + do { + let request = Table>("t").filter(key: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '1969-12-20 13:39:05.679' + """) + } + + do { + let request = Table>("t").filter(keys: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('1969-12-20 13:39:05.679', '1970-01-02 10:17:36.789', '2001-01-01 00:00:00.000', '2001-01-02 10:17:36.789') + """) + } + + do { + let request = Table>("t").filter(key: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = -979294854.321 + """) + } + + do { + let request = Table>("t").filter(keys: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) + """) + } + } + } + + func testFilterID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + + do { + let request = Table>("t").filter(id: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '1969-12-20 13:39:05.679' + """) + } + + do { + let request = Table>("t").filter(ids: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('1969-12-20 13:39:05.679', '1970-01-02 10:17:36.789', '2001-01-01 00:00:00.000', '2001-01-02 10:17:36.789') + """) + } + + do { + let request = Table>("t").filter(id: testedDates[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = -979294854.321 + """) + } + + do { + let request = Table>("t").filter(ids: testedDates) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) + """) + } + } + } + + func testDeleteID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + + do { + try Table>("t").deleteOne(db, id: testedDates[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '1969-12-20 13:39:05.679' + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDates) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('1969-12-20 13:39:05.679', '1970-01-02 10:17:36.789', '2001-01-01 00:00:00.000', '2001-01-02 10:17:36.789') + """) + } + + do { + try Table>("t").deleteOne(db, id: testedDates[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = -979294854.321 + """) + } + + do { + try Table>("t").deleteAll(db, ids: testedDates) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (-979294854.321, -978183743.211, 0.0, 123456.789) + """) + } + } + } +} diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 4b396dd3d..acfa29399 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -398,9 +398,9 @@ class DatabaseMigratorTests : GRDBTestCase { // The first migration should be committed. // The second migration should be rollbacked. - XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try dbQueue.inDatabase { db in try String.fetchAll(db, sql: "SELECT name FROM persons") @@ -418,9 +418,9 @@ class DatabaseMigratorTests : GRDBTestCase { // The second migration should be rollbacked. let error = error as! DatabaseError - XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try! String.fetchAll(db, sql: "SELECT name FROM persons") XCTAssertEqual(names, ["Arthur"]) @@ -461,9 +461,9 @@ class DatabaseMigratorTests : GRDBTestCase { // Migration 1 and 2 should be committed. // Migration 3 should not be committed. - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) try dbQueue.inDatabase { db in // Arthur inserted (migration 1), Barbara (migration 3) not inserted. @@ -848,4 +848,153 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssertEqual(migrator.migrations, ["foo", "bar"]) } } + + func testMigrationForeignKeyChecks() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + let transientForeignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + DELETE FROM child; + """ + + // Foreign key violation + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + try dbQueue.read { try $0.checkForeignKeys() } + } + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + try dbQueue.read { try $0.checkForeignKeys() } + } + + // Transient foreign key violation + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + try dbQueue.read { try $0.checkForeignKeys() } + } + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + try dbQueue.read { try $0.checkForeignKeys() } + } + } + + func testDisablingDeferredForeignKeyChecks() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + let transientForeignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + DELETE FROM child; + """ + + // Foreign key violation + do { + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + do { + // The unique opportunity for corrupt data! + try dbQueue.read { try $0.checkForeignKeys() } + XCTFail("Expected foreign key violation") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + } + do { + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + try dbQueue.read { try $0.checkForeignKeys() } + } + + // Transient foreign key violation + do { + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() + migrator.registerMigration("A") { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + try dbQueue.read { try $0.checkForeignKeys() } + } + do { + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + try dbQueue.read { try $0.checkForeignKeys() } + } + } + + func test_disablingDeferredForeignKeyChecks_applies_to_newly_registered_migrations_only() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + migrator = migrator.disablingDeferredForeignKeyChecks() + migrator.registerMigration("B") { db in + XCTFail("Should not run") + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } + } } diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index b2c3b35f6..a85a24de9 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -75,4 +75,151 @@ class DatabasePoolTests: GRDBTestCase { // calls `sqlite3_file_control` as part of the preparation function. try migrator.migrate(dbQueue) } + + // MARK: - Closing + + func testClose() throws { + let dbPool = try makeDatabasePool() + try dbPool.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + do { + try dbPool.read { db in + _ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbPool.close() + } + + func testCloseAfterUse() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + try dbPool.read { db in + _ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master") + } + try dbPool.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + do { + try dbPool.read { db in + _ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbPool.close() + } + + func testCloseAfterCachedStatement() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + _ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master") + } + try dbPool.read { db in + _ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master") + } + try dbPool.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + do { + try dbPool.read { db in + _ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbPool.close() + } + + func testCloseFailedDueToWriter() throws { + let dbPool = try makeDatabasePool() + let statement = try dbPool.write { db in + try db.makeStatement(sql: "SELECT * FROM sqlite_master") + } + + try withExtendedLifetime(statement) { + do { + try dbPool.close() + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_BUSY { } + } + XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + + // Database is not closed: no error + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + try dbPool.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + } + + func testCloseFailedDueToReader() throws { + let dbPool = try makeDatabasePool() + let statement = try dbPool.read { db in + try db.makeStatement(sql: "SELECT * FROM sqlite_master") + } + + try withExtendedLifetime(statement) { + do { + try dbPool.close() + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_BUSY { } + } + + // The error message can be: + // - unfinalized statement: SELECT * FROM sqlite_master + // - close deferred due to unfinalized statement: "SELECT * FROM sqlite_master" + // + // The first comes from GRDB, and the second, depending on the SQLite + // version, from `sqlite3_close_v2()`. Write the test so that it always pass: + XCTAssert(lastMessage!.contains("unfinalized statement")) + + // Database is in a zombie state. + // In the zombie state, access throws SQLITE_MISUSE + do { + try dbPool.write { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + do { + try dbPool.read { db in + _ = try Row.fetchOne(db, sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // In the zombie state, closing is a noop + try dbPool.close() + } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 3a14dc58c..027496ca3 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -193,4 +193,80 @@ class DatabaseQueueTests: GRDBTestCase { try test(qos: .background) try test(qos: .userInitiated) } + + // MARK: - Closing + + func testClose() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbQueue.close() + } + + func testCloseAfterUse() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + try dbQueue.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbQueue.close() + } + + func testCloseWithCachedStatement() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + _ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master") + } + try dbQueue.close() + + // After close, access throws SQLITE_MISUSE + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try dbQueue.close() + } + + func testFailedClose() throws { + let dbQueue = try makeDatabaseQueue() + let statement = try dbQueue.inDatabase { db in + try db.makeStatement(sql: "SELECT * FROM sqlite_master") + } + + try withExtendedLifetime(statement) { + do { + try dbQueue.close() + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_BUSY { } + } + XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + + // Database is not closed: no error + try dbQueue.inDatabase { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + } } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index a8e1d4455..00d941c29 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -37,7 +37,7 @@ class DatabaseReaderTests : GRDBTestCase { try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)") } XCTFail("Expected error") - } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { + } catch DatabaseError.SQLITE_READONLY { } } diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index f0f5582d6..dd62435d3 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -2,6 +2,41 @@ import XCTest import GRDB class DatabaseRegionObservationTests: GRDBTestCase { + func testDatabaseRegionObservation_FullDatabase() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) + observation.extent = .databaseLifetime + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + func testDatabaseRegionObservationVariadic() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 329dfc379..874c57a6d 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -358,4 +358,80 @@ class DatabaseSnapshotTests: GRDBTestCase { XCTAssertNotNil(db.schemaCache[.main].primaryKey("t")) } } + + // MARK: - Closing + + func testClose() throws { + let snapshot = try makeDatabasePool().makeSnapshot() + try snapshot.close() + + // After close, access throws SQLITE_MISUSE + do { + try snapshot.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try snapshot.close() + } + + func testCloseAfterUse() throws { + let snapshot = try makeDatabasePool().makeSnapshot() + try snapshot.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + try snapshot.close() + + // After close, access throws SQLITE_MISUSE + do { + try snapshot.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try snapshot.close() + } + + func testCloseWithCachedStatement() throws { + let snapshot = try makeDatabasePool().makeSnapshot() + try snapshot.read { db in + _ = try db.cachedStatement(sql: "SELECT * FROM sqlite_master") + } + try snapshot.close() + + // After close, access throws SQLITE_MISUSE + do { + try snapshot.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_MISUSE { } + + // After close, closing is a noop + try snapshot.close() + } + + func testFailedClose() throws { + let snapshot = try makeDatabasePool().makeSnapshot() + let statement = try snapshot.read { db in + try db.makeStatement(sql: "SELECT * FROM sqlite_master") + } + + try withExtendedLifetime(statement) { + do { + try snapshot.close() + XCTFail("Expected Error") + } catch DatabaseError.SQLITE_BUSY { } + } + XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + + // Database is not closed: no error + try snapshot.read { db in + try db.execute(sql: "SELECT * FROM sqlite_master") + } + } } diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index b58f7c2f8..268ec77e4 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -10,22 +10,31 @@ private enum StrategyDeferredToUUID: StrategyProvider { static let strategy: DatabaseUUIDEncodingStrategy = .deferredToUUID } -private enum StrategyString: StrategyProvider { - static let strategy: DatabaseUUIDEncodingStrategy = .string +private enum StrategyUppercaseString: StrategyProvider { + static let strategy: DatabaseUUIDEncodingStrategy = .uppercaseString } -private struct RecordWithUUID: PersistableRecord, Encodable { +private enum StrategyLowercaseString: StrategyProvider { + static let strategy: DatabaseUUIDEncodingStrategy = .lowercaseString +} + +private struct RecordWithUUID: EncodableRecord, Encodable { static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } var uuid: UUID } -private struct RecordWithOptionalUUID: PersistableRecord, Encodable { +private struct RecordWithOptionalUUID: EncodableRecord, Encodable { static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } var uuid: UUID? } +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension RecordWithUUID: Identifiable { + var id: UUID { uuid } +} + class DatabaseUUIDEncodingStrategyTests: GRDBTestCase { - private func test( + private func test( record: T, expectedStorage: DatabaseValue.Storage) { @@ -61,26 +70,218 @@ extension DatabaseUUIDEncodingStrategyTests { } } -// MARK: - string +// MARK: - UppercaseString extension DatabaseUUIDEncodingStrategyTests { - func testString() { - testNullEncoding(strategy: StrategyString.self) + func testUppercaseString() { + testNullEncoding(strategy: StrategyUppercaseString.self) test( - strategy: StrategyString.self, + strategy: StrategyUppercaseString.self, encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, as: "61626364-6566-6768-696A-6B6C6D6E6F70") test( - strategy: StrategyString.self, + strategy: StrategyUppercaseString.self, encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, as: "56E7D8D3-E9E4-48B6-968E-8D102833AF00") let uuid = UUID() test( - strategy: StrategyString.self, + strategy: StrategyUppercaseString.self, encodesUUID: uuid, as: uuid.uuidString.uppercased()) // Assert stable casing } } + +// MARK: - LowercaseString + +extension DatabaseUUIDEncodingStrategyTests { + func testLowercaseString() { + testNullEncoding(strategy: StrategyLowercaseString.self) + + test( + strategy: StrategyLowercaseString.self, + encodesUUID: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + as: "61626364-6566-6768-696a-6b6c6d6e6f70") + + test( + strategy: StrategyLowercaseString.self, + encodesUUID: UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, + as: "56e7d8d3-e9e4-48b6-968e-8d102833af00") + + let uuid = UUID() + test( + strategy: StrategyLowercaseString.self, + encodesUUID: uuid, + as: uuid.uuidString.lowercased()) // Assert stable casing + } +} + +// MARK: - Filter + +extension DatabaseUUIDEncodingStrategyTests { + func testFilterKey() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + let uuids = [ + UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, + ] + + do { + let request = Table>("t").filter(key: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'6162636465666768696a6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(keys: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'6162636465666768696a6b6c6d6e6f70', x'56e7d8d3e9e448b6968e8d102833af00') + """) + } + + do { + let request = Table>("t").filter(key: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696A-6B6C6D6E6F70' + """) + } + + do { + let request = Table>("t").filter(keys: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696A-6B6C6D6E6F70', '56E7D8D3-E9E4-48B6-968E-8D102833AF00') + """) + } + + do { + let request = Table>("t").filter(key: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696a-6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(keys: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') + """) + } + } + } + + func testFilterID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + let uuids = [ + UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, + ] + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = x'6162636465666768696a6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN (x'6162636465666768696a6b6c6d6e6f70', x'56e7d8d3e9e448b6968e8d102833af00') + """) + } + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696A-6B6C6D6E6F70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696A-6B6C6D6E6F70', '56E7D8D3-E9E4-48B6-968E-8D102833AF00') + """) + } + + do { + let request = Table>("t").filter(id: uuids[0]) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" = '61626364-6566-6768-696a-6b6c6d6e6f70' + """) + } + + do { + let request = Table>("t").filter(ids: uuids) + try assertEqualSQL(db, request, """ + SELECT * FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') + """) + } + } + } + + func testDeleteID() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable not available") + } + + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.column("id").primaryKey() } + let uuids = [ + UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")!, + UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!, + ] + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = x'6162636465666768696a6b6c6d6e6f70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN (x'6162636465666768696a6b6c6d6e6f70', x'56e7d8d3e9e448b6968e8d102833af00') + """) + } + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '61626364-6566-6768-696A-6B6C6D6E6F70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('61626364-6566-6768-696A-6B6C6D6E6F70', '56E7D8D3-E9E4-48B6-968E-8D102833AF00') + """) + } + + do { + try Table>("t").deleteOne(db, id: uuids[0]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" = '61626364-6566-6768-696a-6b6c6d6e6f70' + """) + } + + do { + try Table>("t").deleteAll(db, ids: uuids) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "t" WHERE "id" IN ('61626364-6566-6768-696a-6b6c6d6e6f70', '56e7d8d3-e9e4-48b6-968e-8d102833af00') + """) + } + } + } +} diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 707cff6f3..483db5179 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -54,27 +54,181 @@ class ForeignKeyInfoTests: GRDBTestCase { do { let foreignKeys = try db.foreignKeys(on: "children1") XCTAssertEqual(foreignKeys.count, 1) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId", destination: "id")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents1", mapping: [(origin: "parentId", destination: "id")])) } do { let foreignKeys = try db.foreignKeys(on: "children2") XCTAssertEqual(foreignKeys.count, 2) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId2", destination: "id")])) - assertEqual(foreignKeys[1], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId1", destination: "id")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents1", mapping: [(origin: "parentId2", destination: "id")])) + assertEqual(foreignKeys[1], ForeignKeyInfo(id: foreignKeys[1].id, destinationTable: "parents1", mapping: [(origin: "parentId1", destination: "id")])) } do { let foreignKeys = try db.foreignKeys(on: "children3") XCTAssertEqual(foreignKeys.count, 1) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA", destination: "a"), (origin: "parentB", destination: "b")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents2", mapping: [(origin: "parentA", destination: "a"), (origin: "parentB", destination: "b")])) } do { let foreignKeys = try db.foreignKeys(on: "children4") XCTAssertEqual(foreignKeys.count, 2) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA2", destination: "b"), (origin: "parentB2", destination: "a")])) - assertEqual(foreignKeys[1], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA1", destination: "a"), (origin: "parentB1", destination: "b")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents2", mapping: [(origin: "parentA2", destination: "b"), (origin: "parentB2", destination: "a")])) + assertEqual(foreignKeys[1], ForeignKeyInfo(id: foreignKeys[1].id, destinationTable: "parents2", mapping: [(origin: "parentA1", destination: "a"), (origin: "parentB1", destination: "b")])) + } + } + } + + func testForeignKeyViolations() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child1(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + CREATE TABLE child2(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child1 (id, parentId) VALUES (13, '1'); + INSERT INTO child1 (id, parentId) VALUES (42, '2'); + INSERT INTO child2 (id, parentId) VALUES (17, '3'); + """) + + let violations = try Array(db.foreignKeyViolations()) + XCTAssertEqual(violations.count, 3) + + if let violation = violations.first(where: { $0.originTable == "child1" && $0.originRowID == 13 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originTable == "child1" && $0.originRowID == 42 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originTable == "child2" && $0.originRowID == 17 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + } + + func testForeignKeyViolationsInTable() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child1(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + CREATE TABLE child2(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child1 (id, parentId) VALUES (13, '1'); + INSERT INTO child1 (id, parentId) VALUES (42, '2'); + INSERT INTO child2 (id, parentId) VALUES (17, '3'); + """) + + do { + let violations = try Array(db.foreignKeyViolations(in: "child1")) + XCTAssertEqual(violations.count, 2) + + if let violation = violations.first(where: { $0.originRowID == 13 }) { + XCTAssertEqual(violation.originTable, "child1") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originRowID == 42 }) { + XCTAssertEqual(violation.originTable, "child1") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + do { + let violations = try Array(db.foreignKeyViolations(in: "child2")) + XCTAssertEqual(violations.count, 1) + + if let violation = violations.first(where: { $0.originRowID == 17 }) { + XCTAssertEqual(violation.originTable, "child2") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + // Case insensitivity + do { + let violations = try Array(db.foreignKeyViolations(in: "cHiLd2")) + XCTAssertEqual(violations.count, 1) + + if let violation = violations.first(where: { $0.originRowID == 17 }) { + XCTAssertEqual(violation.originTable, "child2") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + // Missing table + do { + _ = try db.foreignKeyViolations(in: "missing") + } catch DatabaseError.SQLITE_ERROR { } + } + } + + func testCheckForeignKeys() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentId) VALUES (13, '1'); + """) + + do { + try db.checkForeignKeys() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: FOREIGN KEY constraint violation - from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + } + } + + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(a TEXT NOT NULL, b TEXT NOT NULL, PRIMARY KEY (a, b)); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parent(a, b)); + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentA, parentB) VALUES (13, 'foo', 'bar'); + """) + + do { + try db.checkForeignKeys() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + } + } + + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(a TEXT NOT NULL, b TEXT NOT NULL, PRIMARY KEY (a, b)); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parent(a, b)) WITHOUT ROWID; + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentA, parentB) VALUES (13, 'foo', 'bar'); + """) + + do { + try db.checkForeignKeys() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, "FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b)") + XCTAssertEqual(error.description, "SQLite error 19: FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b)") } } } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 6cfd9771d..11eefc9c9 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -117,7 +117,19 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "Arthur") } } - + + func testInsertedMutablePersistableRecordPerson() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let person = try MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24).inserted(db) + + let rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0]["id"] as Int64, person.id!) + XCTAssertEqual(rows[0]["name"] as String, "Arthur") + } + } + func testUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -233,7 +245,43 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "Barbara") } } - + + func testSavedMutablePersistableRecordPerson() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var person1 = try MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24).saved(db) + + var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) + XCTAssertEqual(rows[0]["name"] as String, "Arthur") + + let person2 = try MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24).saved(db) + + person1.name = "Craig" + var savedPerson1 = try person1.saved(db) + XCTAssertEqual(person1.id, savedPerson1.id) + + rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) + XCTAssertEqual(rows[0]["name"] as String, "Craig") + XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) + XCTAssertEqual(rows[1]["name"] as String, "Barbara") + + try person1.delete(db) + savedPerson1 = try person1.saved(db) + XCTAssertEqual(person1.id, savedPerson1.id) + + rows = try Row.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["id"] as Int64, savedPerson1.id!) + XCTAssertEqual(rows[0]["name"] as String, "Craig") + XCTAssertEqual(rows[1]["id"] as Int64, person2.id!) + XCTAssertEqual(rows[1]["name"] as String, "Barbara") + } + } + func testDeleteMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -286,7 +334,19 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["name"] as String, "France") } } - + + func testInsertedMutablePersistableRecordCountry() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let country = try MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France").inserted(db) + + let rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0]["rowID"] as Int64, country.rowID!) + XCTAssertEqual(rows[0]["name"] as String, "France") + } + } + func testUpdateMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -343,7 +403,42 @@ class MutablePersistableRecordTests: GRDBTestCase { XCTAssertEqual(rows[1]["name"] as String, "France Métropolitaine") } } - + + func testSavedMutablePersistableRecordCountry() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var country1 = try MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France").saved(db) + + var rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries") + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) + XCTAssertEqual(rows[0]["name"] as String, "France") + + let country2 = try MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States").saved(db) + + country1.name = "France Métropolitaine" + var savedCountry1 = try country1.saved(db) + XCTAssertEqual(country1.rowID, savedCountry1.rowID) + + rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) + XCTAssertEqual(rows[0]["name"] as String, "France Métropolitaine") + XCTAssertEqual(rows[1]["rowID"] as Int64, country2.rowID!) + XCTAssertEqual(rows[1]["name"] as String, "United States") + + try country1.delete(db) + savedCountry1 = try country1.saved(db) + + rows = try Row.fetchAll(db, sql: "SELECT rowID, * FROM countries ORDER BY rowID") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["rowID"] as Int64, country2.rowID!) + XCTAssertEqual(rows[0]["name"] as String, "United States") + XCTAssertEqual(rows[1]["rowID"] as Int64, savedCountry1.rowID!) + XCTAssertEqual(rows[1]["name"] as String, "France Métropolitaine") + } + } + func testDeleteMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 2b6f010b1..1be985ede 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -978,4 +978,23 @@ class QueryInterfaceRequestTests: GRDBTestCase { } } } + + // MARK: - Exists + + func testIsEmpty() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try XCTAssertTrue(tableRequest.isEmpty(db)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"readers\")") + + try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) + try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) + + try XCTAssertFalse(tableRequest.isEmpty(db)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"readers\")") + + try XCTAssertFalse(tableRequest.filter(Column("name") == "Arthur").isEmpty(db)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"readers\" WHERE \"name\" = 'Arthur')") + } + } } diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift new file mode 100644 index 000000000..7ea72f443 --- /dev/null +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -0,0 +1,625 @@ +import XCTest +import GRDB + +class SharedValueObservationTests: GRDBTestCase { + func test_immediate_observationLifetime() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .immediate, + extent: .observationLifetime) + XCTAssertEqual(log.flush(), []) + + do { + var value: Int? + let cancellable = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value = $0 }) + + XCTAssertEqual(value, 0) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + + cancellable.cancel() + XCTAssertEqual(log.flush(), []) + } + + do { + var value: Int? + let cancellable = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value = $0 }) + + XCTAssertEqual(value, 0) + XCTAssertEqual(log.flush(), []) + + cancellable.cancel() + XCTAssertEqual(log.flush(), []) + } + + sharedObservation = nil + XCTAssertEqual(log.flush(), ["cancel"]) + } + + func test_immediate_observationLifetime_reentrancy() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .immediate, + extent: .observationLifetime) + XCTAssertEqual(log.flush(), []) + + do { + var value1: Int? + var value2: Int? + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + value1 = value + _ = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + value2 = value + }) + }) + + XCTAssertEqual(value1, 0) + XCTAssertEqual(value2, 0) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + + cancellable1.cancel() + XCTAssertEqual(log.flush(), []) + } + + sharedObservation = nil + XCTAssertEqual(log.flush(), ["cancel"]) + } + +#if canImport(Combine) + func test_immediate_publisher() throws { + guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Combine is not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let publisher = ValueObservation + .tracking(Table("player").fetchCount) + .shared( + in: dbQueue, + scheduling: .immediate) + .publisher() + + do { + let recorder = publisher.record() + try XCTAssertEqual(recorder.next().get(), 0) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + } + + do { + let recorder = publisher.record() + try XCTAssertEqual(recorder.next().get(), 1) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2) + } + } +#endif + + func test_immediate_whileObserved() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .immediate, + extent: .whileObserved) + XCTAssertEqual(log.flush(), []) + + do { + var value: Int? + let cancellable = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value = $0 }) + + XCTAssertEqual(value, 0) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + + cancellable.cancel() + XCTAssertEqual(log.flush(), ["cancel"]) + } + + do { + var value: Int? + let cancellable = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value = $0 }) + + XCTAssertEqual(value, 0) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + + cancellable.cancel() + XCTAssertEqual(log.flush(), ["cancel"]) + } + + sharedObservation = nil + XCTAssertEqual(log.flush(), []) + } + + func test_immediate_whileObserved_reentrancy() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .immediate, + extent: .whileObserved) + XCTAssertEqual(log.flush(), []) + + do { + var value1: Int? + var value2: Int? + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + value1 = value + _ = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + value2 = value + }) + }) + + XCTAssertEqual(value1, 0) + XCTAssertEqual(value2, 0) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + + cancellable1.cancel() + XCTAssertEqual(log.flush(), ["cancel"]) + } + + sharedObservation = nil + XCTAssertEqual(log.flush(), []) + } + + func test_async_observationLifetime() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .async(onQueue: .main), + extent: .observationLifetime) + XCTAssertEqual(log.flush(), []) + + // --- Start observation 1 + var values1: [Int] = [] + let exp1 = expectation(description: "") + exp1.expectedFulfillmentCount = 2 + exp1.assertForOverFulfill = false + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values1.append($0) + exp1.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp1], timeout: 1) + XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(log.flush(), [ + "start", "fetch", "value: 0", "tracked region: player(*)", + "database did change", "fetch", "value: 1"]) + + // --- Start observation 2 + var values2: [Int] = [] + let exp2 = expectation(description: "") + exp2.expectedFulfillmentCount = 2 + exp2.assertForOverFulfill = false + let cancellable2 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values2.append($0) + exp2.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp2], timeout: 1) + XCTAssertEqual(values1, [0, 1, 2]) + XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) + + // --- Stop observation 1 + cancellable1.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Start observation 3 + var values3: [Int] = [] + let exp3 = expectation(description: "") + exp3.expectedFulfillmentCount = 2 + exp3.assertForOverFulfill = false + let cancellable3 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values3.append($0) + exp3.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp3], timeout: 1) + XCTAssertEqual(values1, [0, 1, 2]) + XCTAssertEqual(values2, [1, 2, 3]) + XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) + + // --- Stop observation 2 + cancellable2.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Stop observation 3 + cancellable3.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Release shared observation + sharedObservation = nil + XCTAssertEqual(log.flush(), ["cancel"]) + } + + func test_async_observationLifetime_early_release() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .async(onQueue: .main), + extent: .observationLifetime) + XCTAssertEqual(log.flush(), []) + + // --- + let exp = expectation(description: "") + exp.expectedFulfillmentCount = 3 + let cancellable = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + // Early release + sharedObservation = nil + + switch value { + case 0: + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"]) + case 1: + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 1"]) + case 2: + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) + default: + break + } + + exp.fulfill() + + try! dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + }) + + wait(for: [exp], timeout: 1) + + cancellable.cancel() + XCTAssertTrue(log.flush().contains("cancel")) // Ignore eventual notification of value: 3 + } + +#if canImport(Combine) + func test_async_publisher() throws { + guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Combine is not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let publisher = ValueObservation + .tracking(Table("player").fetchCount) + .shared(in: dbQueue) // default async + .publisher() + + do { + let recorder = publisher.record() + try XCTAssert(recorder.availableElements.get().isEmpty) + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 0) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + } + + do { + let recorder = publisher.record() + try XCTAssert(recorder.availableElements.get().isEmpty) + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2) + } + } +#endif + + func test_async_whileObserved() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .async(onQueue: .main), + extent: .whileObserved) + XCTAssertEqual(log.flush(), []) + + // --- Start observation 1 + var values1: [Int] = [] + let exp1 = expectation(description: "") + exp1.expectedFulfillmentCount = 2 + exp1.assertForOverFulfill = false + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values1.append($0) + exp1.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp1], timeout: 1) + XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(log.flush(), [ + "start", "fetch", "value: 0", "tracked region: player(*)", + "database did change", "fetch", "value: 1"]) + + // --- Start observation 2 + var values2: [Int] = [] + let exp2 = expectation(description: "") + exp2.expectedFulfillmentCount = 2 + exp2.assertForOverFulfill = false + let cancellable2 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values2.append($0) + exp2.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp2], timeout: 1) + XCTAssertEqual(values1, [0, 1, 2]) + XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) + + // --- Stop observation 1 + cancellable1.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Start observation 3 + var values3: [Int] = [] + let exp3 = expectation(description: "") + exp3.expectedFulfillmentCount = 2 + exp3.assertForOverFulfill = false + let cancellable3 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { + values3.append($0) + exp3.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp3], timeout: 1) + XCTAssertEqual(values1, [0, 1, 2]) + XCTAssertEqual(values2, [1, 2, 3]) + XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) + + // --- Stop observation 2 + cancellable2.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Stop observation 3 + cancellable3.cancel() + XCTAssertEqual(log.flush(), ["cancel"]) + + // --- Release shared observation + sharedObservation = nil + XCTAssertEqual(log.flush(), []) + } + +#if canImport(Combine) + func test_error_recovery_observationLifetime() throws { + guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Combine is not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var fetchError: Error? = nil + let publisher = ValueObservation + .tracking { db -> Int in + if let error = fetchError { throw error } + return try Table("player").fetchCount(db) + } + .print(to: log) + .shared(in: dbQueue, extent: .observationLifetime) + .publisher() + + do { + let recorder1 = publisher.record() + let recorder2 = publisher.record() + + try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) + try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) + + fetchError = TestError() + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + + if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } + if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") } + XCTAssertEqual(log.flush(), [ + "start", "fetch", "value: 0", "tracked region: player(*)", + "database did change", "fetch", "failure: TestError()"]) + } + + do { + let recorder = publisher.record() + if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") } + XCTAssertEqual(log.flush(), []) + } + + do { + fetchError = nil + let recorder = publisher.record() + if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") } + XCTAssertEqual(log.flush(), []) + } + } +#endif + +#if canImport(Combine) + func test_error_recovery_whileObserved() throws { + guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { + throw XCTSkip("Combine is not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var fetchError: Error? = nil + let publisher = ValueObservation + .tracking { db -> Int in + if let error = fetchError { throw error } + return try Table("player").fetchCount(db) + } + .print(to: log) + .shared(in: dbQueue, extent: .whileObserved) + .publisher() + + do { + let recorder1 = publisher.record() + let recorder2 = publisher.record() + + try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) + try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) + + fetchError = TestError() + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + + if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } + if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") } + XCTAssertEqual(log.flush(), [ + "start", "fetch", "value: 0", "tracked region: player(*)", + "database did change", "fetch", "failure: TestError()"]) + } + + do { + let recorder = publisher.record() + if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") } + XCTAssertEqual(log.flush(), ["start", "fetch", "failure: TestError()"]) + } + + do { + fetchError = nil + let recorder = publisher.record() + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + XCTAssertEqual(log.flush(), ["start", "fetch", "value: 1", "tracked region: player(*)"]) + } + } +#endif +} + +private class Log: TextOutputStream { + var strings: [String] = [] + let lock = NSLock() + + func write(_ string: String) { + lock.lock() + strings.append(string) + lock.unlock() + } + + @discardableResult + func flush() -> [String] { + lock.lock() + let result = strings + strings = [] + lock.unlock() + return result + } +} + +private struct TestError: Error { } diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 9b62128ec..9277b99ce 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -12,7 +12,6 @@ private struct Reader : TableRecord { static let databaseTableName = "readers" } - class TableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { @@ -297,4 +296,110 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, Reader.limit(1, offset: 2).limit(3)), "SELECT * FROM \"readers\" LIMIT 3") } + + // MARK: - Exists + + func testExists() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + struct Player: TableRecord { } + try db.create(table: "player") { t in + t.column("a").unique() + t.column("b") + t.column("c") + t.uniqueKey(["b", "c"]) + } + + try XCTAssertFalse(Player.exists(db, key: 1)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"rowid\" = 1)") + + try XCTAssertFalse(Player.exists(db, key: ["a": 1])) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"a\" = 1)") + + try XCTAssertFalse(Player.exists(db, key: ["a": 1, "b": 2])) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE (\"a\" = 1) AND (\"b\" = 2))") + + try XCTAssertFalse(Player.exists(db, key: ["b": 1, "c": 2])) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE (\"b\" = 1) AND (\"c\" = 2))") + + return .rollback + } + + try dbQueue.inTransaction { db in + struct Player: TableRecord { } + try db.create(table: "player") { t in + t.column("a", .integer).notNull().primaryKey() + } + + try XCTAssertFalse(Player.exists(db, key: 1)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"a\" = 1)") + + try XCTAssertFalse(Player.exists(db, key: ["a": 2])) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"a\" = 2)") + + return .rollback + } + + try dbQueue.inTransaction { db in + struct Player: TableRecord { } + try db.create(table: "player") { t in + t.column("id", .text).notNull().primaryKey() + } + + try XCTAssertFalse(Player.exists(db, key: "foo")) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 'foo')") + + try XCTAssertFalse(Player.exists(db, key: ["id": "bar"])) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 'bar')") + + return .rollback + } + } + + func testExistsIdentifiable() throws { + guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else { + throw XCTSkip("Identifiable is not available") + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + struct Player: TableRecord, Identifiable { + var id: Int64 + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + + try XCTAssertFalse(Player.exists(db, id: 1)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 1)") + + return .rollback + } + try dbQueue.inTransaction { db in + struct Player: TableRecord, Identifiable { + var id: Int64? + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + + try XCTAssertFalse(Player.exists(db, id: 1)) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 1)") + + return .rollback + } + try dbQueue.inTransaction { db in + struct Player: TableRecord, Identifiable { + var id: String + } + try db.create(table: "player") { t in + t.column("id", .text).notNull().primaryKey() + } + + try XCTAssertFalse(Player.exists(db, id: "foo")) + XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 'foo')") + + return .rollback + } + } } diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index 5233b3248..6f9afb8b5 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -17,8 +17,8 @@ private enum Namespace { class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { "CustomizedRecordSubClass" } } class CustomizedPlainRecord: Record { override class var databaseTableName: String { "CustomizedPlainRecord" } } } -struct HTTPRequest: TableRecord { } -struct TOEFL: TableRecord { } +private struct HTTPRequest: TableRecord { } +private struct TOEFL: TableRecord { } class TableRecordTests: GRDBTestCase { diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 86f9761bc..a82d6b723 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -860,4 +860,73 @@ class TableTests: GRDBTestCase { } } } + + func test_exists() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("a").unique() + t.column("b") + t.column("c") + t.uniqueKey(["b", "c"]) + } + try db.create(table: "country") { t in + t.column("code", .text).notNull().primaryKey() + } + try db.create(table: "document") { t in + t.column("a") + } + + // Use Table when we want to make sure the generic type is not used. + + do { + try XCTAssertFalse(Table("player").exists(db, key: 1)) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "player" WHERE "id" = 1) + """) + + try XCTAssertFalse(Table("country").exists(db, key: "FR")) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "country" WHERE "code" = 'FR') + """) + + try XCTAssertFalse(Table("document").exists(db, key: 1)) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "document" WHERE "rowid" = 1) + """) + } + + do { + try XCTAssertFalse(Table("player").exists(db, key: ["a": "foo"])) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "player" WHERE "a" = 'foo') + """) + + try XCTAssertFalse(Table("player").exists(db, key: ["b": "bar", "c": "baz"])) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "player" WHERE ("b" = 'bar') AND ("c" = 'baz')) + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Non-optional ID + struct Country: Identifiable { var id: String } + + try XCTAssertFalse(Table("country").exists(db, id: "FR")) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "country" WHERE "code" = 'FR') + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Optional ID + struct Country: Identifiable { var id: String? } + + try XCTAssertFalse(Table("country").exists(db, id: "FR")) + XCTAssertEqual(lastSQLQuery, """ + SELECT EXISTS (SELECT * FROM "country" WHERE "code" = 'FR') + """) + } + } + } } diff --git a/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift b/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift index 31accf5c2..91edbada0 100644 --- a/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift @@ -4,7 +4,7 @@ import GRDB import SQLite #endif -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 /// Here we test the extraction of row values by column name. class FetchNamedValuesTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift index 216a4e07c..90f39ded9 100644 --- a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift @@ -4,7 +4,7 @@ import GRDB import SQLite #endif -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 /// Here we test the extraction of row values by column index. class FetchPositionalValuesTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift index 96257b0d6..b2a13dbdb 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift @@ -5,7 +5,7 @@ import CoreData import RealmSwift #endif -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 /// Here we test the extraction of model objects able to tell if they were /// modified since last fetched from the database. diff --git a/Tests/Performance/GRDBPerformance/FetchRecordDecodableTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordDecodableTests.swift index 1deb6f675..03e9c7aaa 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordDecodableTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordDecodableTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 /// Here we test the extraction of Decodable GRDB records. class FetchRecordDecodableTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift index db6d4c14d..9921c19d8 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 /// A record optimized for fetching performance private struct Item: Codable, FetchableRecord, PersistableRecord { diff --git a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift index 7b78b61b7..a8b734954 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift @@ -4,7 +4,7 @@ import GRDB import SQLite #endif -private let expectedRowCount = 100_000 +private let expectedRowCount = 200_000 private struct Item { var i0: Int diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index ef77a0749..604f254f6 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/realm/realm-cocoa.git", "state": { "branch": null, - "revision": "7a3e25994d4d917efe30fa4496775d3f024b71b6", - "version": "10.13.0" + "revision": "328425bfc372ce77ec1f4f2701f61ececbb97d84", + "version": "10.19.0" } }, { @@ -24,8 +24,8 @@ "repositoryURL": "https://github.com/realm/realm-core", "state": { "branch": null, - "revision": "9a7d09994e85b7eda8e3553b444bcfef6ec3f9ea", - "version": "11.3.0" + "revision": "b170db6a47789ff5f2fbc3eeed0220b4b0a3f6b7", + "version": "11.6.0" } }, { diff --git a/Tests/Performance/GRDBPerformance/InsertNamedValuesTests.swift b/Tests/Performance/GRDBPerformance/InsertNamedValuesTests.swift index b0e321b7b..bb607db7c 100644 --- a/Tests/Performance/GRDBPerformance/InsertNamedValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertNamedValuesTests.swift @@ -4,7 +4,7 @@ import GRDB import SQLite #endif -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 // Here we insert rows, referencing statement arguments by name. class InsertNamedValuesTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift b/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift index e3bd97873..382c6b516 100644 --- a/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift @@ -4,7 +4,7 @@ import GRDB import SQLite #endif -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 // Here we insert rows, referencing statement arguments by index. class InsertPositionalValuesTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift index a936c8838..1bd3349c6 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift @@ -5,7 +5,7 @@ import CoreData import RealmSwift #endif -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 // Here we insert record classes. class InsertRecordClassTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/InsertRecordEncodableTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordEncodableTests.swift index 7879f133a..479b966af 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordEncodableTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordEncodableTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 // Here we insert records. class InsertRecordEncodableTests: XCTestCase { diff --git a/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift index 9735b512c..b0bf10bce 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 /// A record optimized for batch insert performance private struct Item: Codable, FetchableRecord, PersistableRecord { diff --git a/Tests/Performance/GRDBPerformance/InsertRecordStructTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordStructTests.swift index 3a055537d..b94e2d584 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordStructTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordStructTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private let insertedRowCount = 20_000 +private let insertedRowCount = 50_000 // Here we insert records. class InsertRecordStructTests: XCTestCase { diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj index 9ee40e3c6..e8a1f3b3a 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -196,7 +196,7 @@ }; }; buildConfigurationList = 56537C6D1BA8871A00E87787 /* Build configuration list for PBXProject "GRDBProfiling" */; - compatibilityVersion = "Xcode 3.2"; + compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -429,7 +429,10 @@ CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBProfiling; PRODUCT_NAME = "$(TARGET_NAME)"; }; @@ -443,7 +446,10 @@ CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBProfiling; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index 1dcb8cd83..ec8ae5286 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -51,18 +51,33 @@ DERIVED_DATA = tmp SPM_CHECKOUTS = File.join(DERIVED_DATA, 'SourcePackages', 'checkouts') # Extract versions -grdb_version = info_plist_version('Support/Info.plist') -fmdb_version = info_plist_version("#{SPM_CHECKOUTS}/fmdb/src/fmdb/Info.plist") -sqlite_swift_version = git_tag_version("#{SPM_CHECKOUTS}/SQLite.swift") -realm_version = git_tag_version("#{SPM_CHECKOUTS}/realm-cocoa") -`xcodebuild -version` =~ /Xcode (.*)$/; xcode_version = $1 -`curl -s https://support-sp.apple.com/sp/product?cc=$(system_profiler SPHardwareDataType | awk '/Serial/ {print $4}' | cut -c 9-)` =~ /(.*)<\/configCode>/; hardware = $1 -STDERR.puts "GRDB #{grdb_version}" -STDERR.puts "FMDB #{fmdb_version}" -STDERR.puts "SQLite.swift #{sqlite_swift_version}" -STDERR.puts "Realm #{realm_version}" -STDERR.puts "Xcode #{xcode_version}" -STDERR.puts "Hardware #{hardware}" +GRDB_VERSION = info_plist_version('Support/Info.plist') +FMDB_VERSION = info_plist_version("#{SPM_CHECKOUTS}/fmdb/src/fmdb/Info.plist") +SQLITE_SWIFT_VERSION = git_tag_version("#{SPM_CHECKOUTS}/SQLite.swift") +REALM_VERSION = git_tag_version("#{SPM_CHECKOUTS}/realm-cocoa") + +`xcodebuild -version` =~ /Xcode (.*)$/ +XCODE_VERSION = $1 + +# Hardware name: https://apple.stackexchange.com/a/98089 +`curl -s https://support-sp.apple.com/sp/product?cc=$( + system_profiler SPHardwareDataType \ + | awk '/Serial/ {print $4}' \ + | cut -c 9-)` =~ /(.*)<\/configCode>/ +hardware = $1 +if hardware + HARDWARE = hardware +else + # in case the previous technique does not work + HARDWARE = `system_profiler SPHardwareDataType | awk '/Model Identifier/ {print $3}'`.chomp +end + +STDERR.puts "GRDB_VERSION: #{GRDB_VERSION}" +STDERR.puts "FMDB_VERSION: #{FMDB_VERSION}" +STDERR.puts "SQLITE_SWIFT_VERSION: #{SQLITE_SWIFT_VERSION}" +STDERR.puts "REALM_VERSION: #{REALM_VERSION}" +STDERR.puts "XCODE_VERSION: #{XCODE_VERSION}" +STDERR.puts "HARDWARE: #{HARDWARE}" # Generate puts <<-REPORT @@ -70,9 +85,9 @@ puts <<-REPORT *Last updated #{Date.today.strftime('%B %-d, %Y')}* -Below are performance benchmarks made on for [GRDB #{grdb_version}](https://github.com/groue/GRDB.swift), [FMDB #{fmdb_version}](https://github.com/ccgus/fmdb), and [SQLite.swift #{sqlite_swift_version}](https://github.com/stephencelis/SQLite.swift). They are compared to Core Data, [Realm #{realm_version}](https://realm.io) and the raw use of the SQLite C API from Swift. +Below are performance benchmarks made on for [GRDB #{GRDB_VERSION}](https://github.com/groue/GRDB.swift), [FMDB #{FMDB_VERSION}](https://github.com/ccgus/fmdb), and [SQLite.swift #{SQLITE_SWIFT_VERSION}](https://github.com/stephencelis/SQLite.swift). They are compared to Core Data, [Realm #{REALM_VERSION}](https://realm.io) and the raw use of the SQLite C API from Swift. -This report was generated on a #{hardware}, with Xcode #{xcode_version}, by running the following command: +This report was generated on a #{HARDWARE}, with Xcode #{XCODE_VERSION}, by running the following command: ```sh make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb @@ -115,13 +130,13 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho - **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift)) - This test fetches 100000 rows of 10 ints and extracts each int given its position in the row. + This test fetches 200000 rows of 10 ints and extracts each int given its position in the row. It uses FMDB's `-[FMResultSet longForColumnIndex:]`, GRDB's `Row.value(atIndex:)`, and the low-level SQL API of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift)) - This test inserts 20000 rows of 10 ints, by setting query arguments given their position. + This test inserts 50000 rows of 10 ints, by setting query arguments given their position. It uses FMDB's `-[FMDatabase executeUpdate:withArgumentsInArray:]` with statement caching, GRDB's `UpdateStatement.execute(arguments:Array)`, and the low-level SQL API of SQLite.swift. @@ -129,13 +144,13 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho - **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/FetchNamedValuesTests.swift)) - This test fetches 100000 rows of 10 ints and extracts each int given its column name. + This test fetches 200000 rows of 10 ints and extracts each int given its column name. It uses FMDB's `-[FMResultSet longForColumn:]`, GRDB's `Row.value(named:)`, and the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/InsertNamedValuesTests.swift)) - This test inserts 20000 rows of 10 ints, by setting query arguments given their argument name. + This test inserts 50000 rows of 10 ints, by setting query arguments given their argument name. It uses FMDB's `-[FMDatabase executeUpdate:withParameterDictionary:]` with statement caching, GRDB's `UpdateStatement.execute(arguments:Dictionary)`, and the high-level query builder of SQLite.swift. @@ -143,25 +158,25 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho - **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift)) - This test fetches an array of 100000 record objects initiated from rows of 10 ints. + This test fetches an array of 200000 record objects initiated from rows of 10 ints. It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [FetchableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#fetchablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/InsertRecordStructTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [PersistableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#persistablerecord-protocol) protocol. + This tests inserts 50000 records with the persistence method provided by GRDB's [PersistableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#persistablerecord-protocol) protocol. - **Codable Records**: - **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/FetchRecordDecodableTests.swift)) - This test fetches an array of 100000 record objects initiated from rows of 10 ints. + This test fetches an array of 200000 record objects initiated from rows of 10 ints. It builds records from GRDB's built-in support for the [Decodable standard protocols](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records). - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/InsertRecordEncodableTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's built-in support for the [Encodable standard protocols](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records). + This tests inserts 50000 records with the persistence method provided by GRDB's built-in support for the [Encodable standard protocols](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records). - **Optimized Records**: @@ -177,11 +192,11 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho - **Fetch** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/FetchRecordClassTests.swift)) - This test fetches an array of 100000 record objects initiated from rows of 10 ints. + This test fetches an array of 200000 record objects initiated from rows of 10 ints. It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/GRDBPerformance/InsertRecordClassTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. + This tests inserts 50000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. REPORT