From 8f7a2b6a8ef5f8402949bfde00f1194010ed77ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Aug 2021 18:18:57 +0200 Subject: [PATCH] Documentation: Combine and Data Consistency --- CHANGELOG.md | 1 + Documentation/Combine.md | 106 +++++++++++++++++++++++++++------------ 2 files changed, 76 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8788f36e..d6ef2e8d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1036](https://github.com/groue/GRDB.swift/pull/1036) by [@groue](https://github.com/groue): Restore minimal CI tests - **New**: [#1037](https://github.com/groue/GRDB.swift/pull/1037) by [@groue](https://github.com/groue): Support BUILD_LIBRARY_FOR_DISTRIBUTION +- **Documentation Update**: A new [Combine and Data Consistency](Documentation/Combine.md#combine-and-data-consistency) chapter explains how to make sure database publishers do not break important database invariants. ## 5.9.0 diff --git a/Documentation/Combine.md b/Documentation/Combine.md index 3e47b8338..b83f71835 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -7,6 +7,7 @@ GRDB ❤️ Combine - [Demo Application] - [Asynchronous Database Access] - [Database Observation] +- [Combine and Data Consistency]: take care when you combine database publishers together ## Usage @@ -248,37 +249,6 @@ This publisher has the same behavior as ValueObservation: See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information. -:warning: **ValueObservation and Data Consistency** - -When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)). - -Instead, compose requests together into **one single** ValueObservation, as below: - -```swift -struct HallOfFame { - var totalPlayerCount: Int - var bestPlayers: [Player] -} - -// DATA CONSISTENCY GUARANTEED -let hallOfFamePublisher = ValueObservation - .tracking { db -> HallOfFame in - let totalPlayerCount = try Player.fetchCount(db) - - let bestPlayers = try Player - .order(Column("score").desc) - .limit(10) - .fetchAll(db) - - return HallOfFame( - totalPlayerCount: totalPlayerCount, - bestPlayers: bestPlayers) - } - .publisher(in: dbQueue) -``` - -See [ValueObservation] for more information. - #### `DatabaseRegionObservation.publisher(in:)` @@ -320,12 +290,86 @@ try dbQueue.write { db in See [DatabaseRegionObservation] for more information. +## Combine and Data Consistency + +When you compose database publishers together with Combine operators such as `combineLatest` or `zip`, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)). + +This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together. + +In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introduce bugs. + +To this end, remember that *all database publishers can perform several requests*. + +In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and ony one publisher: + +```swift +struct HallOfFame { + // Invariant: bestPlayers.count <= totalPlayerCount + var totalPlayerCount: Int + var bestPlayers: [Player] +} + +// CORRECT: DATA CONSISTENCY GUARANTEED +let hallOfFamePublisher = ValueObservation + .tracking { db -> HallOfFame in + // 1st request + let totalPlayerCount = try Player.fetchCount(db) + + // 2nd request + let bestPlayers = try Player + .order(Column("score").desc) + .limit(10) + .fetchAll(db) + + // 100% guaranteed + assert(bestPlayers.count <= totalPlayerCount) + + // Merge results together + return HallOfFame( + totalPlayerCount: totalPlayerCount, + bestPlayers: bestPlayers) + } + .publisher(in: dbQueue) +``` + +Compare with the incorrect version that combines two database publishers together: + +```swift +// OK +let totalPlayerCountPublisher = ValueObservation + .tracking(Player.fetchCount) + .publisher(in: dbQueue) + +// OK +let bestPlayerPublisher = ValueObservation + .tracking(Player + .order(Column("score").desc) + .limit(10) + .fetchAll) + .publisher(in: dbQueue) + +// NOT OK: DATA CONSISTENCY NOT GUARANTEED +let hallOfFamePublisher = totalPlayerCountPublisher + .combineLatest(bestPlayerPublisher) + .map(HallOfFame.init(totalPlayerCount:bestPlayers)) + +let cancellable = hallOfFamePublisher.sink( + receiveCompletion: { completion in ... }, + receiveValue: { hallOfFame in + // ASSERTION MAY FAIL if some players are deleted + // at the wrong time + assert(hallOfFame.bestPlayers.count <= hallOfFame.totalPlayerCount) + }) +``` + + [Database Connections]: ../README.md#database-connections [Usage]: #usage [Asynchronous Database Access]: #asynchronous-database-access [Combine]: https://developer.apple.com/documentation/combine [Database Changes Observation]: ../README.md#database-changes-observation [Database Observation]: #database-observation +[Combine and Data Consistency]: #combine-and-data-consistency [DatabaseRegionObservation]: ../README.md#databaseregionobservation [Demo Application]: DemoApps/GRDBCombineDemo/README.md [SQLite]: http://sqlite.org