From a0ed1bfd33efa1837097de5c98d9888114257cdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 15 Mar 2023 16:23:43 +0100 Subject: [PATCH 01/18] Move ValueObservation documentation in an extension file --- .../Extension/ValueObservation.md | 264 ++++++++++++++ GRDB/ValueObservation/ValueObservation.swift | 338 ------------------ 2 files changed, 264 insertions(+), 338 deletions(-) create mode 100644 GRDB/Documentation.docc/Extension/ValueObservation.md diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md new file mode 100644 index 000000000..fbb434d52 --- /dev/null +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -0,0 +1,264 @@ +# ``GRDB/ValueObservation`` + +`ValueObservation` tracks changes in the results of database requests, and notifies fresh values whenever the database changes. + +## Overview + +`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or . This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +The only changes that are not notified are: + +- Changes performed by external database connections. See for more information. +- Changes to the database schema, changes to internal system tables such as `sqlite_master`. +- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. + +## ValueObservation Usage + +1. Make sure that a unique database connection, ``DatabaseQueue`` or ``DatabasePool``, is kept open during the whole duration of the observation. + +2. Create a `ValueObservation` with a closure that fetches the observed value: + + ```swift + let observation = ValueObservation.tracking { db in + // Fetch and return the observed value + } + + // For example, an observation of [Player], which tracks all players: + let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) + } + + // The same observation, using shorthand notation: + let observation = ValueObservation.tracking(Player.fetchAll) + ``` + + There is no limit on the values that can be observed. An observation can perform multiple requests, from multiple database tables, and use raw SQL. See ``tracking(_:)`` for some examples. + +3. Start the observation in order to be notified of changes: + + ```swift + let cancellable = observation.start(in: dbQueue) { error in + // Handle error + } onChange: { (players: [Player]) in + print("Fresh players", players) + } + ``` + +4. Stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated: + + ```swift + cancellable.cancel() + ``` + +`ValueObservation` can also be turned into an async sequence, a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): + +- Async sequence: + + ```swift + do { + for try await players in observation.values(in: dbQueue) { + print("Fresh players", players) + } + } catch { + // Handle error + } + ``` + +- Combine Publisher: + + ```swift + let cancellable = observation.publisher(in: dbQueue).sink { completion in + // Handle completion + } receiveValue: { (players: [Player]) in + print("Fresh players", players) + } + ``` + +## ValueObservation Behavior + +`ValueObservation` notifies an initial value before the eventual changes. + +`ValueObservation` only notifies changes committed to disk. + +By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see . + +By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously. This can be configured: see . + +`ValueObservation` may coalesce subsequent changes into a single notification. + +`ValueObservation` may notify consecutive identical values. You can filter out the undesired duplicates with the ``removeDuplicates()`` method. + +Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated. + +The database observation stops when the cancellable returned by the `start` method is cancelled or deallocated, or if an error occurs. + +> Important: Take care that there are use cases that `ValueObservation` is unfit for. +> +> For example, an application may need to process absolutely all changes, and avoid any coalescing. An application may also need to process changes before any further modifications could be performed in the database file. In those cases, the application needs to track *individual transactions*, not values: use ``DatabaseRegionObservation``. +> +> If you need to process changes before they are committed to disk, use ``TransactionObserver``. + +## ValueObservation Scheduling + +By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously: + +```swift +// The default scheduling +let cancellable = observation.start(in: dbQueue) { error in + // Called asynchronously on the main dispatch queue +} onChange: { value in + // Called asynchronously on the main dispatch queue + print("Fresh value", value) +} +``` + +You can change this behavior by adding a `scheduling` argument to the `start()` method. + +For example, the ``ValueObservationScheduler/immediate`` scheduler notifies all values on the main dispatch queue, and notifies the first one immediately when the observation starts. + +It is very useful in graphic applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Take care that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests! + +The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise): + +```swift +let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in + // Called on the main dispatch queue +} onChange: { value in + // Called on the main dispatch queue + print("Fresh value", value) +} +// <- Here "Fresh value" has already been printed. +``` + +The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice. + +## ValueObservation Sharing + +Sharing a `ValueObservation` spares database resources. When a database change happens, a fresh value is fetched only once, and then notified to all clients of the shared observation. + +You build a shared observation with ``shared(in:scheduling:extent:)``: + +```swift +// SharedValueObservation<[Player]> +let sharedObservation = ValueObservation + .tracking { db in try Player.fetchAll(db) } + .shared(in: dbQueue) +``` + +`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. As a replacement, you may for example use Combine apis: + +```swift +let cancellable = try sharedObservation + .publisher() // Turn shared observation into a Combine Publisher + .map { ... } // The map operator from Combine + .sink(...) +``` + + +## Specifying the Tracked Region + +While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control. + +Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:fetch:)`` to do just that: + +```swift +let observation = ValueObservation.tracking( + // Define the tracked database region + // (the score column of the player with id 1) + region: Player.select(Column("score")).filter(id: 1), + // Define what to fetch upon such change to the tracked region + // (the player with id 1) + fetch: { db in try Player.fetchOne(db, id: 1) } +) +``` + +This ``tracking(region:fetch:)`` method lets you entirely separate the **observed region** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked. + +## ValueObservation Performance + +This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications. + +**`ValueObservation` is triggered by database transactions that may modify the tracked value.** + +Precisely speaking, `ValueObservation` tracks changes in a ``DatabaseRegion``, not changes in values. + +For example, if you track the maximum score of players, all transactions that impact the `score` column of the `player` database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed. + +You can filter out undesired duplicate notifications with the ``removeDuplicates()`` method. + +**ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components. + +When needed, you can help GRDB optimize observations and reduce database contention: + +> Tip: Stop observations when possible. +> +> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`. +> +> In a SwiftUI application, you can profit from the [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) method. + +> Tip: Share observations when possible. +> +> Each call to `ValueObservation.start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing the observation with ``shared(in:scheduling:extent:)``. + +> Tip: When the observation processes some raw fetched values, use the ``map(_:)`` operator: +> +> ```swift +> // Plain observation +> let observation = ValueObservation.tracking { db -> MyValue in +> let players = try Player.fetchAll(db) +> return computeMyValue(players) +> } +> +> // Optimized observation +> let observation = ValueObservation +> .tracking { db try Player.fetchAll(db) } +> .map { players in computeMyValue(players) } +> ``` +> +> The `map` operator performs its job without blocking database accesses, and without blocking the main thread. + +> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization. + +## Topics + +### Creating a ValueObservation + +- ``tracking(_:)`` +- ``trackingConstantRegion(_:)`` +- ``tracking(region:fetch:)`` +- ``tracking(regions:fetch:)`` + +### Creating a Shared Observation + +- ``shared(in:scheduling:extent:)`` +- ``SharedValueObservationExtent`` + +### Accessing Observed Values + +- ``publisher(in:scheduling:)`` +- ``start(in:scheduling:onError:onChange:)`` +- ``values(in:scheduling:bufferingPolicy:)`` +- ``DatabaseCancellable`` +- ``ValueObservationScheduler`` + +### Mapping Values + +- ``map(_:)`` + +### Filtering Values + +- ``removeDuplicates()`` +- ``removeDuplicates(by:)`` + +### Requiring Write Access + +- ``requiresWriteAccess`` + +### Debugging + +- ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` +- ``print(_:to:)`` + +### Support + +- ``ValueReducer`` diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 9ad5e29a4..6859dfa51 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -4,344 +4,6 @@ import Combine import Dispatch import Foundation -/// `ValueObservation` tracks changes in the results of database requests, and -/// notifies fresh values whenever the database changes. -/// -/// ## Overview -/// -/// Tracked changes are insertions, updates, and deletions that impact the -/// tracked value, whether performed with raw SQL, or . -/// This includes indirect changes triggered by -/// [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) -/// or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -/// -/// Changes to internal system tables (such as `sqlite_master`) and changes to -/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are -/// not notified. -/// -/// ## ValueObservation Usage -/// -/// 1. Make sure that a unique database connection, ``DatabaseQueue`` or -/// ``DatabasePool``, is kept open during the whole duration of -/// the observation. -/// -/// `ValueObservation` does not notify changes performed by -/// external connections. -/// See -/// for more information. -/// -/// 2. Create a `ValueObservation` with a closure that fetches the -/// observed value: -/// -/// ```swift -/// let observation = ValueObservation.tracking { db in -/// // Fetch and return the observed value -/// } -/// -/// // For example, an observation of [Player], which tracks all players: -/// let observation = ValueObservation.tracking { db in -/// try Player.fetchAll(db) -/// } -/// -/// // The same observation, using shorthand notation: -/// let observation = ValueObservation.tracking(Player.fetchAll) -/// ``` -/// -/// There is no limit on the values that can be observed. An observation -/// can perform multiple requests, from multiple database tables, and use -/// raw SQL. See ``tracking(_:)`` for some examples. -/// -/// 3. Start the observation in order to be notified of changes: -/// -/// ```swift -/// let cancellable = observation.start(in: dbQueue) { error in -/// // Handle error -/// } onChange: { (players: [Player]) in -/// print("Fresh players", players) -/// } -/// ``` -/// -/// 4. Stop the observation by calling the ``DatabaseCancellable/cancel()`` -/// method on the object returned by the `start` method. Cancellation is -/// automatic when the cancellable is deallocated: -/// -/// ```swift -/// cancellable.cancel() -/// ``` -/// -/// `ValueObservation` can also be turned into an async sequence, a Combine -/// publisher, or an RxSwift observable (see the companion library -/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): -/// -/// - Async sequence: -/// -/// ```swift -/// do { -/// for try await players in observation.values(in: dbQueue) { -/// print("Fresh players", players) -/// } -/// } catch { -/// // Handle error -/// } -/// ``` -/// -/// - Combine Publisher: -/// -/// ```swift -/// let cancellable = observation.publisher(in: dbQueue).sink { completion in -/// // Handle completion -/// } receiveValue: { (players: [Player]) in -/// print("Fresh players", players) -/// } -/// ``` -/// -/// ## ValueObservation Behavior -/// -/// `ValueObservation` notifies an initial value before the eventual changes. -/// -/// `ValueObservation` only notifies changes committed to disk. -/// -/// By default, `ValueObservation` notifies a fresh value whenever any component -/// of its fetched value is modified (any fetched column, row, etc.). This can -/// be configured: -/// see . -/// -/// By default, `ValueObservation` notifies the initial value, as well as -/// eventual changes and errors, on the main dispatch queue, asynchronously. -/// This can be configured: -/// see . -/// -/// `ValueObservation` may coalesce subsequent changes into a -/// single notification. -/// -/// `ValueObservation` may notify consecutive identical values. You can filter -/// out the undesired duplicates with the ``removeDuplicates()`` method. -/// -/// Starting an observation retains the database connection, until it is -/// stopped. As long as the observation is active, the database connection -/// won't be deallocated. -/// -/// The database observation stops when the cancellable returned by the `start` -/// method is cancelled or deallocated, or if an error occurs. -/// -/// Take care that there are use cases that `ValueObservation` is unfit for. -/// For example, an application may need to process absolutely all changes, -/// and avoid any coalescing. An application may also need to process changes -/// before any further modifications could be performed in the database file. In -/// those cases, the application needs to track *individual transactions*, not -/// values: use ``DatabaseRegionObservation``. If you need to process -/// changes before they are committed to disk, use ``TransactionObserver``. -/// -/// ## ValueObservation Scheduling -/// -/// By default, `ValueObservation` notifies the initial value, as well as -/// eventual changes and errors, on the main dispatch queue, asynchronously: -/// -/// ```swift -/// // The default scheduling -/// let cancellable = observation.start(in: dbQueue) { error in -/// // Called asynchronously on the main dispatch queue -/// } onChange: { value in -/// // Called asynchronously on the main dispatch queue -/// print("Fresh value", value) -/// } -/// ``` -/// -/// You can change this behavior by adding a `scheduling` argument to the -/// `start()` method. -/// -/// For example, the ``ValueObservationScheduler/immediate`` scheduler -/// notifies all values on the main dispatch queue, and notifies the first -/// one immediately when the observation starts. -/// -/// It is very useful in graphic applications, because you can configure views -/// right away, without waiting for the initial value to be fetched eventually. -/// You don't have to implement any empty or loading screen, or to prevent some -/// undesired initial animation. -/// -/// The `immediate` scheduling requires that the observation starts from the -/// main dispatch queue (a fatal error is raised otherwise): -/// -/// ```swift -/// let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in -/// // Called on the main dispatch queue -/// } onChange: { value in -/// // Called on the main dispatch queue -/// print("Fresh value", value) -/// } -/// // <- Here "Fresh value" has already been printed. -/// ``` -/// -/// The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` -/// asynchronously schedules values and errors on the dispatch queue of -/// your choice. -/// -/// ## ValueObservation Sharing -/// -/// Sharing a `ValueObservation` spares database resources. When a database -/// change happens, a fresh value is fetched only once, and then notified to -/// all clients of the shared observation. -/// -/// You build a shared observation with ``shared(in:scheduling:extent:)``: -/// -/// ```swift -/// // SharedValueObservation<[Player]> -/// let sharedObservation = ValueObservation -/// .tracking { db in try Player.fetchAll(db) } -/// .shared(in: dbQueue) -/// ``` -/// -/// `ValueObservation` and `SharedValueObservation` are nearly identical, but -/// the latter has no operator such as `map`. As a replacement, you may -/// for example use Combine apis: -/// -/// ```swift -/// let cancellable = try sharedObservation -/// .publisher() // Turn shared observation into a Combine Publisher -/// .map { ... } // The map operator from Combine -/// .sink(...) -/// ``` -/// -/// -/// ## Specifying the Tracked Region -/// -/// While the standard ``tracking(_:)`` method lets you track changes to a -/// fetched value and receive any changes to it, sometimes your use case might -/// require more granular control. -/// -/// Consider a scenario where you'd like to get a specific Player's row, but -/// only when their `score` column changes. You can use -/// ``tracking(region:fetch:)`` to do just that: -/// -/// ```swift -/// let observation = ValueObservation.tracking( -/// // Define what database region constitutes a "change" -/// region: Player.select(Column("score")).filter(id: 1), -/// // Define what to fetch upon such change -/// fetch: { db in try Player.fetchOne(db, id: 1) } -/// ) -/// ``` -/// -/// This overload of `ValueObservation` lets you entirely separate the -/// **observed region** from the **fetched value** itself, providing utmost -/// flexibility. See ``DatabaseRegionConvertible`` for more information about -/// the regions that can be tracked. -/// -/// ## ValueObservation Performance -/// -/// This section further describes runtime aspects of `ValueObservation`, and -/// provides some optimization tips for demanding applications. -/// -/// **`ValueObservation` is triggered by database transactions that may modify -/// the tracked value.** -/// -/// Precisely speaking, `ValueObservation` tracks changes in a -/// ``DatabaseRegion``, not changes in values. -/// -/// For example, if you track the maximum score of players, all transactions -/// that impact the `score` column of the `player` database table (any update, -/// insertion, or deletion) trigger the observation, even if the maximum score -/// itself is not changed. -/// -/// You can filter out undesired duplicate notifications with the -/// ``removeDuplicates()`` method. -/// -/// **ValueObservation can create database contention.** In other words, active -/// observations take a toll on the constrained database resources. When -/// triggered by impactful transactions, observations fetch fresh values, and -/// can delay read and write database accesses of other application components. -/// -/// When needed, you can help GRDB optimize observations and reduce -/// database contention: -/// -/// > Tip: Stop observations when possible. -/// > -/// > For example, if a `UIViewController` needs to display database values, it -/// > can start the observation in `viewWillAppear`, and stop it in -/// > `viewWillDisappear`. -/// > -/// > In a SwiftUI application, you can profit from the -/// > [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its -/// > [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) -/// > method. -/// -/// > Tip: Share observations when possible. -/// > -/// > Each call to `ValueObservation.start` method triggers independent values -/// > refreshes. When several components of your app are interested in the same -/// > value, consider sharing the observation -/// > with ``shared(in:scheduling:extent:)``. -/// -/// > Tip: Use a ``DatabasePool``, because it can perform multi-threaded -/// > database accesses. -/// -/// > Tip: When the observation processes some raw fetched values, use the -/// > ``map(_:)`` operator: -/// > -/// > ```swift -/// > // Plain observation -/// > let observation = ValueObservation.tracking { db -> MyValue in -/// > let players = try Player.fetchAll(db) -/// > return computeMyValue(players) -/// > } -/// > -/// > // Optimized observation -/// > let observation = ValueObservation -/// > .tracking { db try Player.fetchAll(db) } -/// > .map { players in computeMyValue(players) } -/// > ``` -/// > -/// > The `map` operator helps reducing database contention because it performs -/// > its job without blocking database accesses. -/// -/// > Tip: When the observation tracks a constant database region, create an -/// > optimized observation with the ``trackingConstantRegion(_:)`` method. See -/// > the documentation of this method for more information about what -/// > constitutes a "constant region", and the nature of the optimization. -/// -/// ## Topics -/// -/// ### Creating a ValueObservation -/// -/// - ``tracking(_:)`` -/// - ``trackingConstantRegion(_:)`` -/// - ``tracking(region:fetch:)`` -/// - ``tracking(regions:fetch:)`` -/// -/// ### Creating a Shared Observation -/// -/// - ``shared(in:scheduling:extent:)`` -/// - ``SharedValueObservationExtent`` -/// -/// ### Accessing Observed Values -/// -/// - ``publisher(in:scheduling:)`` -/// - ``start(in:scheduling:onError:onChange:)`` -/// - ``values(in:scheduling:bufferingPolicy:)`` -/// - ``DatabaseCancellable`` -/// - ``ValueObservationScheduler`` -/// -/// ### Mapping Values -/// -/// - ``map(_:)`` -/// -/// ### Filtering Values -/// -/// - ``removeDuplicates()`` -/// - ``removeDuplicates(by:)`` -/// -/// ### Requiring Write Access -/// -/// - ``requiresWriteAccess`` -/// -/// ### Debugging -/// -/// - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` -/// - ``print(_:to:)`` -/// -/// ### Support -/// -/// - ``ValueReducer`` public struct ValueObservation { var events = ValueObservationEvents() From 3f876978a1d65298bac71b936c6fecce91aafc5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 15 Mar 2023 16:44:07 +0100 Subject: [PATCH 02/18] Move TransactionObserver documentation in an extension file --- GRDB/Core/TransactionObserver.swift | 305 ------------------ .../Extension/TransactionObserver.md | 255 +++++++++++++++ 2 files changed, 255 insertions(+), 305 deletions(-) create mode 100644 GRDB/Documentation.docc/Extension/TransactionObserver.md diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 28e902426..ad0af7728 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -739,311 +739,6 @@ class DatabaseObservationBroker { // MARK: - TransactionObserver -/// A type that tracks database changes and transactions performed in -/// a database. -/// -/// ## Overview -/// -/// `TransactionObserver` is the low-level protocol that supports all -/// features. -/// -/// A transaction observer is notified of individual changes (inserts, updates -/// and deletes), before they are committed to disk, as well as transaction -/// commits and rollbacks. -/// -/// ## Activate a Transaction Observer -/// -/// An observer starts receiving change notifications after it has been added to -/// a database connection with the -/// ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method, -/// or the ``Database/add(transactionObserver:extent:)`` `Database` method: -/// -/// ```swift -/// let observer = MyObserver() -/// dbQueue.add(transactionObserver: observer) -/// ``` -/// -/// By default, database holds weak references to its transaction observers: -/// they are not retained, and stop getting notifications after they are -/// deallocated. See for -/// more options. -/// -/// ## Database Changes And Transactions -/// -/// Database changes are notified to the ``databaseDidChange(with:)`` callback. -/// This includes indirect changes triggered by `ON DELETE` and `ON UPDATE` -/// actions associated to -/// [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and -/// [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -/// -/// Transaction completions are notified to the ``databaseWillCommit()-7mksu``, -/// ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks. -/// -/// Read-only transactions, changes and transactions performed by external -/// database connections, changes to internal system tables (such as -/// `sqlite_master`), changes to -/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the -/// deletion of duplicate rows triggered by -/// [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses -/// (this last exception might change in a future release of SQLite) are -/// not notified. -/// -/// Notified changes are not actually written to disk until the transaction -/// commits, and the `databaseDidCommit` callback is called. On the other -/// side, `databaseDidRollback` confirms their invalidation: -/// -/// ```swift -/// try dbQueue.write { db in -/// try db.execute(sql: "INSERT ...") // 1. didChange -/// try db.execute(sql: "UPDATE ...") // 2. didChange -/// } // 3. willCommit, 4. didCommit -/// -/// try dbQueue.inTransaction { db in -/// try db.execute(sql: "INSERT ...") // 1. didChange -/// try db.execute(sql: "UPDATE ...") // 2. didChange -/// return .rollback // 3. didRollback -/// } -/// -/// try dbQueue.write { db in -/// try db.execute(sql: "INSERT ...") // 1. didChange -/// throw SomeError() -/// } // 2. didRollback -/// ``` -/// -/// Database statements that are executed outside of any explicit transaction -/// do not drop off the radar: -/// -/// ```swift -/// try dbQueue.writeWithoutTransaction { db in -/// try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit -/// try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit -/// } -/// ``` -/// -/// Changes that are on hold because of a -/// [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified -/// after the savepoint has been released. This makes sure that notified events -/// are only those that have an opportunity to be committed: -/// -/// ```swift -/// try dbQueue.inTransaction { db in -/// try db.execute(sql: "INSERT ...") // 1. didChange -/// -/// try db.execute(sql: "SAVEPOINT foo") -/// try db.execute(sql: "UPDATE ...") // delayed -/// try db.execute(sql: "UPDATE ...") // delayed -/// try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange -/// -/// try db.execute(sql: "SAVEPOINT bar") -/// try db.execute(sql: "UPDATE ...") // not notified -/// try db.execute(sql: "ROLLBACK TO SAVEPOINT bar") -/// try db.execute(sql: "RELEASE SAVEPOINT bar") -/// -/// return .commit // 4. willCommit, 5. didCommit -/// } -/// ``` -/// -/// Eventual errors thrown from `databaseWillCommit` are exposed to the -/// application code: -/// -/// ```swift -/// do { -/// try dbQueue.inTransaction { db in -/// ... -/// return .commit // 1. willCommit (throws), 2. didRollback -/// } -/// } catch { -/// // 3. The error thrown by the transaction observer. -/// } -/// ``` -/// -/// - Note: All callbacks are called in the writer dispatch queue, and -/// serialized with all database updates. -/// -/// - Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not -/// touch the SQLite database. This limitation does not apply to -/// `databaseDidCommit` and `databaseDidRollback` which can use their -/// database argument. -/// -/// ## Filtering Database Events -/// -/// **Transaction observers can choose the database changes they are -/// interested in.** -/// -/// The filtering happens in the ``observes(eventsOfKind:)`` method, which tells -/// whether the observer wants notifications of specific kinds of changes, -/// or not. -/// -/// The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can -/// distinguish insertions from deletions and updates, and is also able to -/// tell the columns that are about to be changed. -/// -/// For example, an observer can focus on the changes that happen on the -/// "player" database table only: -/// -/// ```swift -/// class PlayerObserver: TransactionObserver { -/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { -/// // Only observe changes to the "player" table. -/// eventKind.tableName == "player" -/// } -/// -/// func databaseDidChange(with event: DatabaseEvent) { -/// // This method is only called for changes that happen to -/// // the "player" table. -/// } -/// } -/// ``` -/// -/// When the `observes(eventsOfKind:)` method returns false for all event kinds, -/// the observer is still notified of transactions. -/// -/// ## Observation Extent -/// -/// **You can specify how long an observer is notified of database changes -/// and transactions.** -/// -/// The `remove(transactionObserver:)` method explicitly stops notifications, -/// at any time: -/// -/// ```swift -/// // From a database queue or pool: -/// dbQueue.remove(transactionObserver: observer) -/// -/// // From a database connection: -/// dbQueue.inDatabase { db in -/// db.remove(transactionObserver: observer) -/// } -/// ``` -/// -/// Alternatively, use the `extent` parameter of the -/// `add(transactionObserver:extent:)` method: -/// -/// ```swift -/// let observer = MyObserver() -/// -/// // On a database queue or pool: -/// dbQueue.add(transactionObserver: observer) // default extent -/// dbQueue.add(transactionObserver: observer, extent: .observerLifetime) -/// dbQueue.add(transactionObserver: observer, extent: .nextTransaction) -/// dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) -/// -/// // On a database connection: -/// dbQueue.inDatabase { db in -/// db.add(transactionObserver: ...) -/// } -/// ``` -/// -/// - The default extent is `.observerLifetime`: the database holds a weak -/// reference to the observer, and the observation automatically ends when the -/// observer is deallocated. Meanwhile, the observer is notified of all changes -/// and transactions. -/// -/// - `.nextTransaction` activates the observer until the current or next -/// transaction completes. The database keeps a strong reference to the observer -/// until its `databaseDidCommit` or `databaseDidRollback` callback is called. -/// Hereafter the observer won't get any further notification. -/// -/// - `.databaseLifetime` has the database retain and notify the observer until -/// the database connection is closed. -/// -/// Finally, an observer can avoid processing database changes until the end -/// of the current transaction. After -/// ``stopObservingDatabaseChangesUntilNextTransaction()``, the -/// `databaseDidChange` callback will not be called until the current -/// transaction completes: -/// -/// ```swift -/// class PlayerObserver: TransactionObserver { -/// var playerTableWasModified = false -/// -/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { -/// eventKind.tableName == "player" -/// } -/// -/// func databaseDidChange(with event: DatabaseEvent) { -/// playerTableWasModified = true -/// -/// // It is pointless to keep on tracking further changes: -/// stopObservingDatabaseChangesUntilNextTransaction() -/// } -/// } -/// ``` -/// -/// ### Support for SQLite Pre-Update Hooks -/// -/// When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, -/// `TransactionObserver` gets an extra callback which lets you observe -/// individual column values in the rows modified by a transaction: -/// -/// ```swift -/// protocol TransactionObserver: AnyObject { -/// #if SQLITE_ENABLE_PREUPDATE_HOOK -/// /// Notifies before a database change (insert, update, or delete) -/// /// with change information (initial / final values for the row's -/// /// columns). -/// /// -/// /// The event is only valid for the duration of this method call. If you -/// /// need to keep it longer, store a copy: event.copy(). -/// func databaseWillChange(with event: DatabasePreUpdateEvent) -/// #endif -/// } -/// ``` -/// -/// This extra API can be activated in two ways: -/// -/// 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. -/// It uses the system SQLite, which is compiled with -/// `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't -/// know the minimum version of macOS, tvOS, watchOS): -/// -/// ```ruby -/// pod 'GRDB.swift' -/// platform :ios, '11.0' # or above -/// -/// post_install do |installer| -/// installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| -/// target.build_configurations.each do |config| -/// # Enable extra GRDB APIs -/// config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" -/// # Enable extra SQLite APIs -/// config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" -/// end -/// end -/// end -/// ``` -/// -/// **Warning**: make sure you use the right platform version! You will get -/// runtime errors on devices with a lower version. -/// -/// **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in -/// `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that -/// are lacking from the system `` header. When Xcode eventually -/// ships with an SDK that includes a complete header, you may get a -/// compiler error about duplicate function definitions. When this happens, -/// just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option. -/// -/// 2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) -/// and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option. -/// -/// ## Topics -/// -/// ### Filtering Database Changes -/// -/// - ``observes(eventsOfKind:)`` -/// - ``DatabaseEventKind`` -/// -/// ### Handling Database Changes -/// -/// - ``databaseDidChange(with:)`` -/// - ``stopObservingDatabaseChangesUntilNextTransaction()`` -/// - ``DatabaseEvent`` -/// -/// ### Handling Transactions -/// -/// - ``databaseWillCommit()-7mksu`` -/// - ``databaseDidCommit(_:)`` -/// - ``databaseDidRollback(_:)`` public protocol TransactionObserver: AnyObject { /// Returns whether specific kinds of database changes should be notified diff --git a/GRDB/Documentation.docc/Extension/TransactionObserver.md b/GRDB/Documentation.docc/Extension/TransactionObserver.md new file mode 100644 index 000000000..feaf9f9c2 --- /dev/null +++ b/GRDB/Documentation.docc/Extension/TransactionObserver.md @@ -0,0 +1,255 @@ +# ``GRDB/TransactionObserver`` + +A type that tracks database changes and transactions performed in a database. + +## Overview + +`TransactionObserver` is the low-level protocol that supports all features. + +A transaction observer is notified of individual changes (inserts, updates and deletes), before they are committed to disk, as well as transaction commits and rollbacks. + +## Activate a Transaction Observer + +An observer starts receiving change notifications after it has been added to a database connection with the ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method, or the ``Database/add(transactionObserver:extent:)`` `Database` method: + +```swift +let observer = MyObserver() +dbQueue.add(transactionObserver: observer) +``` + +By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See for more options. + +## Database Changes And Transactions + +Database changes are notified to the ``databaseDidChange(with:)`` callback. This includes indirect changes triggered by `ON DELETE` and `ON UPDATE` actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks. + +The only changes and transactions that are not notified are: + +- Read-only transactions. +- Changes and transactions performed by external database connections. +- Changes to the database schema, changes to internal system tables such as `sqlite_master`. +- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. +- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). + +Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: + +```swift +try dbQueue.write { db in + try db.execute(sql: "INSERT ...") // 1. didChange + try db.execute(sql: "UPDATE ...") // 2. didChange +} // 3. willCommit, 4. didCommit + +try dbQueue.inTransaction { db in + try db.execute(sql: "INSERT ...") // 1. didChange + try db.execute(sql: "UPDATE ...") // 2. didChange + return .rollback // 3. didRollback +} + +try dbQueue.write { db in + try db.execute(sql: "INSERT ...") // 1. didChange + throw SomeError() +} // 2. didRollback +``` + +Database statements that are executed outside of any explicit transaction do not drop off the radar: + +```swift +try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit + try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit +} +``` + +Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only those that have an opportunity to be committed: + +```swift +try dbQueue.inTransaction { db in + try db.execute(sql: "INSERT ...") // 1. didChange + + try db.execute(sql: "SAVEPOINT foo") + try db.execute(sql: "UPDATE ...") // delayed + try db.execute(sql: "UPDATE ...") // delayed + try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange + + try db.execute(sql: "SAVEPOINT bar") + try db.execute(sql: "UPDATE ...") // not notified + try db.execute(sql: "ROLLBACK TO SAVEPOINT bar") + try db.execute(sql: "RELEASE SAVEPOINT bar") + + return .commit // 4. willCommit, 5. didCommit +} +``` + +Eventual errors thrown from `databaseWillCommit` are exposed to the application code: + +```swift +do { + try dbQueue.inTransaction { db in + ... + return .commit // 1. willCommit (throws), 2. didRollback + } +} catch { + // 3. The error thrown by the transaction observer. +} +``` + +- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates. + +- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument. + +## Filtering Database Events + +**Transaction observers can choose the database changes they are interested in.** + +The ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking: + +```swift +// Calls `observes(eventsOfKind:)` once. +// Calls `databaseDidChange(with:)` for every updated row, or not at all. +try db.execute(sql: "UPDATE player SET score = score + 1") +``` + +The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can distinguish insertions from deletions and updates, and is also able to tell the columns that are about to be changed. + +For example, an observer can focus on the changes that happen on the "player" database table only: + +```swift +class PlayerObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Only observe changes to the "player" table. + eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + // This method is only called for changes that happen to + // the "player" table. + } +} +``` + +When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions. + +## Observation Extent + +**You can specify how long an observer is notified of database changes and transactions.** + +The `remove(transactionObserver:)` method explicitly stops notifications, at any time: + +```swift +// From a database queue or pool: +dbQueue.remove(transactionObserver: observer) + +// From a database connection: +dbQueue.inDatabase { db in + db.remove(transactionObserver: observer) +} +``` + +Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: + +```swift +let observer = MyObserver() + +// On a database queue or pool: +dbQueue.add(transactionObserver: observer) // default extent +dbQueue.add(transactionObserver: observer, extent: .observerLifetime) +dbQueue.add(transactionObserver: observer, extent: .nextTransaction) +dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) + +// On a database connection: +dbQueue.inDatabase { db in + db.add(transactionObserver: ...) +} +``` + +- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, the observer is notified of all changes and transactions. + +- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. Hereafter the observer won't get any further notification. + +- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. + +Finally, an observer can avoid processing database changes until the end of the current transaction. After ``stopObservingDatabaseChangesUntilNextTransaction()``, the `databaseDidChange` callback will not be called until the current transaction completes: + +```swift +class PlayerObserver: TransactionObserver { + var playerTableWasModified = false + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + playerTableWasModified = true + + // It is pointless to keep on tracking further changes: + stopObservingDatabaseChangesUntilNextTransaction() + } +} +``` + +### Support for SQLite Pre-Update Hooks + +When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction: + +```swift +protocol TransactionObserver: AnyObject { + #if SQLITE_ENABLE_PREUPDATE_HOOK + /// Notifies before a database change (insert, update, or delete) + /// with change information (initial / final values for the row's + /// columns). + /// + /// The event is only valid for the duration of this method call. If you + /// need to keep it longer, store a copy: event.copy(). + func databaseWillChange(with event: DatabasePreUpdateEvent) + #endif +} +``` + +This extra API can be activated in two ways: + +1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. + + It uses the system SQLite, which is compiled with `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS): + + ```ruby + pod 'GRDB.swift' + platform :ios, '11.0' # or above + + post_install do |installer| + installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| + target.build_configurations.each do |config| + # Enable extra GRDB APIs + config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK" + # Enable extra SQLite APIs + config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1" + end + end + end + ``` + + **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version. + + **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option. + +2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option. + +## Topics + +### Filtering Database Changes + +- ``observes(eventsOfKind:)`` +- ``DatabaseEventKind`` + +### Handling Database Changes + +- ``databaseDidChange(with:)`` +- ``stopObservingDatabaseChangesUntilNextTransaction()`` +- ``DatabaseEvent`` + +### Handling Transactions + +- ``databaseWillCommit()-7mksu`` +- ``databaseDidCommit(_:)`` +- ``databaseDidRollback(_:)`` From 7c81c37e1f8ca3cf2d95e2f05b5da7894cd04da8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 15 Mar 2023 16:51:31 +0100 Subject: [PATCH 03/18] Move DatabaseRegionObservation documentation in an extension file --- GRDB/Core/DatabaseRegionObservation.swift | 103 ------------------ .../Extension/DatabaseRegionObservation.md | 91 ++++++++++++++++ 2 files changed, 91 insertions(+), 103 deletions(-) create mode 100644 GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 0e69ea865..a831e063b 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -3,109 +3,6 @@ import Combine #endif import Foundation -/// `DatabaseRegionObservation` tracks transactions that modify a -/// database region. -/// -/// ## Overview -/// -/// Tracked changes are insertions, updates, and deletions that impact the -/// tracked region, whether performed with raw SQL, or . -/// This includes indirect changes triggered by -/// [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) -/// or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). -/// -/// Changes to internal system tables (such as `sqlite_master`) and changes to -/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are -/// not notified. -/// -/// `DatabaseRegionObservation` calls your application right after changes have -/// been committed in the database, and before any other thread had any -/// opportunity to perform further changes. *This is a pretty strong guarantee, -/// that most applications do not really need.* Instead, most applications -/// prefer to be notified with fresh values: make sure you check -/// ``ValueObservation`` before using `DatabaseRegionObservation`. -/// -/// ## DatabaseRegionObservation Usage -/// -/// Create a `DatabaseRegionObservation` with one or several requests to track: -/// -/// ```swift -/// // Tracks the full player table -/// let observation = DatabaseRegionObservation(tracking: Player.all()) -/// ``` -/// -/// Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``: -/// -/// ```swift -/// let cancellable = try observation.start(in: dbQueue) { error in -/// // Handle error -/// } onChange: { (db: Database) in -/// print("Players were changed") -/// } -/// ``` -/// -/// Enjoy the changes notifications: -/// -/// ```swift -/// try dbQueue.write { db in -/// try Player(name: "Arthur").insert(db) -/// } -/// // Prints "Players were changed" -/// ``` -/// -/// You stop the observation by calling the ``DatabaseCancellable/cancel()`` -/// method on the object returned by the `start` method. Cancellation is -/// automatic when the cancellable is deallocated: -/// -/// ```swift -/// cancellable.cancel() -/// ``` -/// -/// `DatabaseRegionObservation` can also be turned into a Combine publisher, or -/// an RxSwift observable (see the companion library -/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): -/// -/// ```swift -/// let cancellable = observation.publisher(in: dbQueue).sink { completion in -/// // Handle completion -/// } receiveValue: { (db: Database) in -/// print("Players were changed") -/// } -/// ``` -/// -/// You can feed `DatabaseRegionObservation` with any type that conforms to -/// the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``, -/// ``DatabaseRegion``, ``Table``, etc. For example: -/// -/// ```swift -/// // Observe the score column of the 'player' table -/// let observation = DatabaseRegionObservation( -/// tracking: Player.select(Column("score"))) -/// -/// // Observe the 'score' column of the 'player' table -/// let observation = DatabaseRegionObservation( -/// tracking: SQLRequest("SELECT score FROM player")) -/// -/// // Observe both the 'player' and 'team' tables -/// let observation = DatabaseRegionObservation( -/// tracking: Table("player"), Table("team")) -/// -/// // Observe the full database -/// let observation = DatabaseRegionObservation( -/// tracking: .fullDatabase) -/// ``` -/// -/// ## Topics -/// -/// ### Creating DatabaseRegionObservation -/// -/// - ``init(tracking:)-5ldbe`` -/// - ``init(tracking:)-2nqjd`` -/// -/// ### Observing Database Transactions -/// -/// - ``publisher(in:)`` -/// - ``start(in:onError:onChange:)`` public struct DatabaseRegionObservation { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. diff --git a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md new file mode 100644 index 000000000..01c1e1f06 --- /dev/null +++ b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md @@ -0,0 +1,91 @@ +# ``GRDB/DatabaseRegionObservation`` + +`DatabaseRegionObservation` tracks changes in a database region, and notifies impactful transactions. + +## Overview + +`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or . This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +The only changes that are not notified are: + +- Changes performed by external database connections. +- Changes to the database schema, changes to internal system tables such as `sqlite_master`. +- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. + +`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`. + +## DatabaseRegionObservation Usage + +Create a `DatabaseRegionObservation` with one or several requests to track: + +```swift +// Tracks the full player table +let observation = DatabaseRegionObservation(tracking: Player.all()) +``` + +Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``: + +```swift +let cancellable = try observation.start(in: dbQueue) { error in + // Handle error +} onChange: { (db: Database) in + print("Players were changed") +} +``` + +Enjoy the changes notifications: + +```swift +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} +// Prints "Players were changed" +``` + +You stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated: + +```swift +cancellable.cancel() +``` + +`DatabaseRegionObservation` can also be turned into a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)): + +```swift +let cancellable = observation.publisher(in: dbQueue).sink { completion in + // Handle completion +} receiveValue: { (db: Database) in + print("Players were changed") +} +``` + +You can feed `DatabaseRegionObservation` with any type that conforms to the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``, ``DatabaseRegion``, ``Table``, etc. For example: + +```swift +// Observe the score column of the 'player' table +let observation = DatabaseRegionObservation( + tracking: Player.select(Column("score"))) + +// Observe the 'score' column of the 'player' table +let observation = DatabaseRegionObservation( + tracking: SQLRequest("SELECT score FROM player")) + +// Observe both the 'player' and 'team' tables +let observation = DatabaseRegionObservation( + tracking: Table("player"), Table("team")) + +// Observe the full database +let observation = DatabaseRegionObservation( + tracking: .fullDatabase) +``` + +## Topics + +### Creating DatabaseRegionObservation + +- ``init(tracking:)-5ldbe`` +- ``init(tracking:)-2nqjd`` + +### Observing Database Transactions + +- ``publisher(in:)`` +- ``start(in:onError:onChange:)`` From 6d392f0a87cb94da348d35048f1efe636806f032 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Thu, 16 Mar 2023 13:44:08 +0100 Subject: [PATCH 04/18] Use DatabaseError.connectionIsClosed() where appropriate --- GRDB/Core/DatabasePool.swift | 4 ++-- GRDB/Core/DatabaseSnapshotPool.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 4abc2e085..d9962c159 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -361,7 +361,7 @@ extension DatabasePool: DatabaseReader { public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { - value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) + value(.failure(DatabaseError.connectionIsClosed())) return } @@ -405,7 +405,7 @@ extension DatabasePool: DatabaseReader { public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { - value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) + value(.failure(DatabaseError.connectionIsClosed())) return } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 33cee1292..8701754a4 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -294,7 +294,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func asyncRead(_ value: @escaping (Result) -> Void) { guard let readerPool else { - value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed"))) + value(.failure(DatabaseError.connectionIsClosed())) return } From 378c6785eac6c2bb674e1def66293b1f8511f69f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Mar 2023 18:44:38 +0100 Subject: [PATCH 05/18] Clarification on the truncate optimization --- GRDB/Core/TransactionObserver.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index ad0af7728..7f2cf179c 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -761,7 +761,7 @@ public protocol TransactionObserver: AnyObject { /// When this method returns true for deletion events, the observer /// prevents the /// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization) - /// from being applied. + /// from being applied on the observed tables. func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool /// Called when the database is changed by an insert, update, or From 5d7fdeae5a7ab1c7acfa9fe2d68a19038bd382bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 17 Mar 2023 13:52:01 +0100 Subject: [PATCH 06/18] Fix compiler warnings in tests --- Tests/GRDBTests/DataMemoryTests.swift | 84 +++++++++++++------- Tests/GRDBTests/TableRecordDeleteTests.swift | 12 ++- 2 files changed, 66 insertions(+), 30 deletions(-) diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index f2b95d91c..a6f329298 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -34,16 +34,6 @@ class DataMemoryTests: GRDBTestCase { } } } - - do { - // This data should not be copied - // (The deprecation warning is expected: we test a deprecated method.) - let nonCopiedData = row.dataNoCopy(atIndex: 0)! - XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { - XCTAssertEqual($0.baseAddress, blobPointer) - } - } } } @@ -72,16 +62,6 @@ class DataMemoryTests: GRDBTestCase { } } } - - do { - // This data should not be copied - // (The deprecation warning is expected: we test a deprecated method.) - let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)! - XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { - XCTAssertEqual($0.baseAddress, blobPointer) - } - } } } @@ -109,14 +89,62 @@ class DataMemoryTests: GRDBTestCase { } } } - do { - // This data should not be copied: - // (The deprecation warning is expected: we test a deprecated method.) - let nonCopiedData = row.dataNoCopy(atIndex: 0)! - XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { nonCopiedBuffer in - XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) - } + } + default: + XCTFail("Not a blob") + } + } + } + } + + @available(*, deprecated) + func testDeprecatedMemoryBehavior() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + // Make sure Data is on the heap (15 bytes is enough) + // For more context, see: + // https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue + let data = Data(repeating: 0xaa, count: 15) + + do { + let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data]) + while let row = try rows.next() { + let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0) + // This data should not be copied + let nonCopiedData = row.dataNoCopy(atIndex: 0)! + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) + } + } + } + + do { + let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)]) + let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data], adapter: adapter) + while let row = try rows.next() { + let blobPointer = sqlite3_column_blob(row.unadapted.sqliteStatement, 0) + let nestedRow = row.scopes["nested"]! + // This data should not be copied + let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)! + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) + } + } + } + + do { + let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])! + let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple + switch dbValue.storage { + case .blob(let data): + data.withUnsafeBytes { buffer in + // This data should not be copied: + let nonCopiedData = row.dataNoCopy(atIndex: 0)! + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { nonCopiedBuffer in + XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) } } default: diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index e88a87c65..23df2f131 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -277,7 +277,8 @@ class TableRecordDeleteTests: GRDBTestCase { _ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") - + +#if GRDBCUSTOMSQLITE || GRDBCIPHER if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") @@ -285,7 +286,14 @@ class TableRecordDeleteTests: GRDBTestCase { _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") } - +#else + _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") + + _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") +#endif + _ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *") From 0d4c6e592e98e7f491f394bfa507dade405b5a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Mar 2023 20:03:20 +0100 Subject: [PATCH 07/18] SerializedDatabase.allowsUnsafeTransactions --- GRDB/Core/SerializedDatabase.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index bcec3e9f7..9736ffde0 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -8,6 +8,9 @@ final class SerializedDatabase { /// The database configuration var configuration: Configuration { db.configuration } + /// If true, overrides `configuration.allowsUnsafeTransactions`. + var allowsUnsafeTransactions = false + /// The path to the database file let path: String @@ -242,7 +245,7 @@ final class SerializedDatabase { line: UInt = #line) { GRDBPrecondition( - configuration.allowsUnsafeTransactions || !db.isInsideTransaction, + allowsUnsafeTransactions || configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line) From e66dfacab82792f5d6df994f3d83224b268e50d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Mar 2023 20:23:02 +0100 Subject: [PATCH 08/18] WALSnapshotTransaction --- GRDB.xcodeproj/project.pbxproj | 4 ++ GRDB/Core/DatabasePool.swift | 37 +++++++++++++ GRDB/Core/SerializedDatabase.swift | 2 + GRDB/Core/WALSnapshotTransaction.swift | 74 ++++++++++++++++++++++++++ GRDBCustom.xcodeproj/project.pbxproj | 4 ++ 5 files changed, 121 insertions(+) create mode 100644 GRDB/Core/WALSnapshotTransaction.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1d711ca40..43c7d6af6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -281,6 +281,7 @@ 56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; }; 56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; }; 56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */; }; 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; }; 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -753,6 +754,7 @@ 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = ""; }; 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = ""; }; 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; + 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; @@ -1466,6 +1468,7 @@ 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, + 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */, 56E9FAD7221053DC00C703A8 /* SQL.swift */, 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */, 56FBFED82210731A00945324 /* SQLRequest.swift */, @@ -2157,6 +2160,7 @@ 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */, 560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */, 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d9962c159..57db0d254 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -640,6 +640,43 @@ extension DatabasePool: DatabaseReader { return readers.first { $0.onValidQueue } } + // MARK: - WAL Snapshot Transactions + + // swiftlint:disable:next line_length +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + /// Returns a long-lived WAL snapshot transaction on one of the + /// reader connections. + func walSnapshotTransaction() throws -> WALSnapshotTransaction { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let (reader, releaseReader) = try readerPool.get() + return try WALSnapshotTransaction(reader: reader) { transactionCompleted in + releaseReader(transactionCompleted ? .reuse : .discard) + } + } + + /// Returns a long-lived WAL snapshot transaction on one of the + /// reader connections. + func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { + guard let readerPool else { + completion(.failure(DatabaseError.connectionIsClosed())) + return + } + + readerPool.asyncGet { result in + completion(result.flatMap { reader, releaseReader in + Result { + try WALSnapshotTransaction(reader: reader) { transactionCompleted in + releaseReader(transactionCompleted ? .reuse : .discard) + } + } + }) + } + } +#endif + // MARK: - Database Observation public func _add( diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 9736ffde0..76ba8d8a0 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -9,6 +9,8 @@ final class SerializedDatabase { var configuration: Configuration { db.configuration } /// If true, overrides `configuration.allowsUnsafeTransactions`. + /// + /// See `WALSnapshotTransaction`. var allowsUnsafeTransactions = false /// The path to the database file diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift new file mode 100644 index 000000000..a3eb5e141 --- /dev/null +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -0,0 +1,74 @@ +// swiftlint:disable:next line_length +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +/// A long-live read-only WAL transaction. +/// +/// `WALSnapshotTransaction` **takes ownership** of its reader +/// `SerializedDatabase` (TODO: make it a move-only type eventually). +class WALSnapshotTransaction { + private let reader: SerializedDatabase + private let transactionDidComplete: (Bool) -> Void + + /// The state of the database at the beginning of the transaction. + let walSnapshot: WALSnapshot + + /// Creates a long-live WAL transaction on a read-only connection. + /// + /// The `transactionDidComplete` closure is called when the + /// `WALSnapshotTransaction` is deallocated, or if the + /// initializer throws. Its argument tells if the long-lived + /// transaction could be properly terminated. + /// + /// - parameter reader: A read-only database connection. + /// - parameter transactionDidComplete: A closure to call when the + /// snapshot transaction ends. + init( + reader: SerializedDatabase, + transactionDidComplete: @escaping (Bool) -> Void) + throws + { + assert(reader.configuration.readonly) + + // Open a transaction and enter snapshot isolation + reader.allowsUnsafeTransactions = true + do { + try reader.sync { db in + try db.beginTransaction(.deferred) + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + } + } catch { + // self is not initialized, so deinit will not run. + Self.commitAndRelease(reader: reader, transactionDidComplete: transactionDidComplete) + throw error + } + + self.reader = reader + self.transactionDidComplete = transactionDidComplete + self.walSnapshot = try reader.sync { db in + return try WALSnapshot(db) + } + } + + deinit { + Self.commitAndRelease(reader: reader, transactionDidComplete: transactionDidComplete) + } + + /// Executes database operations in the snapshot transaction, and + /// returns their result after they have finished executing. + func read(_ value: (Database) throws -> T) rethrows -> T { + // TODO: we should check the validity of the snapshot, as DatabaseSnapshotPool does. + try reader.sync(value) + } + + private static func commitAndRelease( + reader: SerializedDatabase, + transactionDidComplete: (Bool) -> Void) + { + reader.allowsUnsafeTransactions = false + let success = reader.sync { db in + try? db.commit() + return db.isInsideTransaction + } + transactionDidComplete(success) + } +} +#endif diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3d8f50e2f..84a9f56a3 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -276,6 +276,7 @@ 56D110F528AFC90800E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */; }; 56D110F728AFC90800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */; }; 56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */; }; + 56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DA7D03260FAA1B00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; @@ -763,6 +764,7 @@ 56D110E728AFC90800E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = ""; }; 56D110E828AFC90800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = ""; }; 56D110FE28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = ""; }; + 56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DA7D02260FAA1A00A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; @@ -1462,6 +1464,7 @@ 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, + 56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */, 56A6EB2226076F6A00C27594 /* SQL.swift */, 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */, 56FBFED52210731000945324 /* SQLRequest.swift */, @@ -1981,6 +1984,7 @@ 56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, + 56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, From d64274474b2d6e0c08ced8c3a8c2763c8e85c6f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 16 Mar 2023 20:25:05 +0100 Subject: [PATCH 09/18] ValueObservation: stop creating a new connection on start Since #1248, ValueObservation on DatabasePool creates a new database connection when it starts. #1256 has revealed that opening a connection can take too much time, which unfortunate consequences: the first value is notified too late, and we block the main thread when the observation is started in the `.immediate` scheduling :-/ In this commit, ValueObservation on DatabasePool just uses one of the available readers, thus avoiding creating a new connection. When WAL snapshots are available, a long-running read-only transaction is kept opened on this reader, until we can start observing the write transactions, compare database versions, and perform a fetch+notification if and only if the database was modified. When WAL snapshots are not available (Xcode 14.0 and macOS, or specific SQLCipher or SQLite builds), a double notification of the initial value is always performed, since we can't prove that the database was not changed between the initial fetch and the write access. --- .../Observers/ValueConcurrentObserver.swift | 249 ++++++++++++++---- 1 file changed, 205 insertions(+), 44 deletions(-) diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 9508ee4a8..7211c20c0 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -250,6 +250,16 @@ extension ValueConcurrentObserver { return AnyDatabaseCancellable(self) } + private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) { + observationState.region = observedRegion + assert(observationState.isModified == false) + writerDB.add(transactionObserver: self, extent: .observerLifetime) + } +} + +// swiftlint:disable:next line_length +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +extension ValueConcurrentObserver { /// Synchronously starts the observation, and returns the initial value. /// /// Unlike `asyncStart()`, this method does not notify the initial value or error. @@ -259,27 +269,22 @@ extension ValueConcurrentObserver { // without having to wait for an eventual long-running write // transaction to complete. // - // Fetch value & tracked region in a synchronous way. - // - // We perform the initial read from a DatabaseSnapshot, because - // it is a handy way to keep a read transaction open until we grab a - // write access, and compare the database versions. - let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() - let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read { - db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in - // swiftlint:disable:previous closure_parameter_position - + // We perform the initial read from a long-lived WAL snapshot + // transaction, because it is a handy way to keep a read transaction + // open until we grab a write access, and compare the database versions. + let walSnapshotTransaction = try databaseAccess.dbPool.walSnapshotTransaction() + let (fetchedValue, initialRegion) = try walSnapshotTransaction.read { db -> (Reducer.Fetched, DatabaseRegion) in switch trackingMode { case let .constantRegion(regions): let fetchedValue = try databaseAccess.fetch(db) let region = try DatabaseRegion.union(regions)(db) let initialRegion = try region.observableRegion(db) - return (fetchedValue, initialRegion, try? WALSnapshot(db)) + return (fetchedValue, initialRegion) case .constantRegionRecordedFromSelection, .nonConstantRegionRecordedFromSelection: let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) - return (fetchedValue, initialRegion, try? WALSnapshot(db)) + return (fetchedValue, initialRegion) } } @@ -294,8 +299,7 @@ extension ValueConcurrentObserver { // Start observation asyncStartObservation( from: databaseAccess, - initialSnapshot: initialSnapshot, - initialWALSnapshot: initialWALSnapshot, + walSnapshotTransaction: walSnapshotTransaction, initialRegion: initialRegion) return initialValue @@ -310,20 +314,20 @@ extension ValueConcurrentObserver { // without having to wait for an eventual long-running write // transaction to complete. // - // We perform the initial read from a DatabaseSnapshot, because - // it is a handy way to keep a read transaction open until we grab a - // write access, and compare the database versions. - do { - let initialSnapshot = try databaseAccess.dbPool.makeSnapshot() - initialSnapshot.asyncRead { dbResult in - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - - do { - // Fetch + // We perform the initial read from a long-lived WAL snapshot + // transaction, because it is a handy way to keep a read transaction + // open until we grab a write access, and compare the database versions. + databaseAccess.dbPool.asyncWALSnapshotTransaction { result in + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + do { + // Fetch + let walSnapshotTransaction = try result.get() + try walSnapshotTransaction.read { db in let fetchedValue: Reducer.Fetched let initialRegion: DatabaseRegion - let db = try dbResult.get() + switch self.trackingMode { case let .constantRegion(regions): fetchedValue = try databaseAccess.fetch(db) @@ -362,22 +366,18 @@ extension ValueConcurrentObserver { // Start observation self.asyncStartObservation( from: databaseAccess, - initialSnapshot: initialSnapshot, - initialWALSnapshot: try? WALSnapshot(db), + walSnapshotTransaction: walSnapshotTransaction, initialRegion: initialRegion) - } catch { - self.notifyError(error) } + } catch { + self.notifyError(error) } - } catch { - self.notifyError(error) } } private func asyncStartObservation( from databaseAccess: DatabaseAccess, - initialSnapshot: DatabaseSnapshot, - initialWALSnapshot: WALSnapshot?, + walSnapshotTransaction: WALSnapshotTransaction, initialRegion: DatabaseRegion) { databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in @@ -389,17 +389,15 @@ extension ValueConcurrentObserver { // Transaction is needed for comparing version snapshots try writerDB.isolated(readOnly: true) { - // Keep initialSnapshot alive until we have compared + // Keep walSnapshotTransaction alive until we have compared // database versions. It prevents database checkpointing, // and keeps WAL snapshots (`sqlite3_snapshot`) valid // and comparable. - let isModified = withExtendedLifetime(initialSnapshot) { - guard let initialWALSnapshot, - let currentWALSnapshot = try? WALSnapshot(writerDB) - else { + let isModified = withExtendedLifetime(walSnapshotTransaction) { + guard let currentWALSnapshot = try? WALSnapshot(writerDB) else { return true } - let ordering = initialWALSnapshot.compare(currentWALSnapshot) + let ordering = walSnapshotTransaction.walSnapshot.compare(currentWALSnapshot) assert(ordering <= 0, "Unexpected snapshot ordering") return ordering < 0 } @@ -463,13 +461,176 @@ extension ValueConcurrentObserver { } } } +} +#else +extension ValueConcurrentObserver { + /// Synchronously starts the observation, and returns the initial value. + /// + /// Unlike `asyncStart()`, this method does not notify the initial value or error. + private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value { + // Start from a read access. The whole point of using a DatabasePool + // for observing the database is to be able to fetch the initial value + // without having to wait for an eventual long-running write + // transaction to complete. + let (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db -> (Reducer.Fetched, DatabaseRegion) in + switch trackingMode { + case let .constantRegion(regions): + let fetchedValue = try databaseAccess.fetch(db) + let region = try DatabaseRegion.union(regions)(db) + let initialRegion = try region.observableRegion(db) + return (fetchedValue, initialRegion) + + case .constantRegionRecordedFromSelection, + .nonConstantRegionRecordedFromSelection: + let (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) + return (fetchedValue, initialRegion) + } + } + + // Reduce + let initialValue = try reduceQueue.sync { + guard let initialValue = try reducer._value(fetchedValue) else { + fatalError("Broken contract: reducer has no initial value") + } + return initialValue + } + + // Start observation + asyncStartObservation( + from: databaseAccess, + initialRegion: initialRegion) + + return initialValue + } - private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) { - observationState.region = observedRegion - assert(observationState.isModified == false) - writerDB.add(transactionObserver: self, extent: .observerLifetime) + /// Asynchronously starts the observation + /// + /// Unlike `syncStart()`, this method does notify the initial value or error. + private func asyncStart(from databaseAccess: DatabaseAccess) { + // Start from a read access. The whole point of using a DatabasePool + // for observing the database is to be able to fetch the initial value + // without having to wait for an eventual long-running write + // transaction to complete. + databaseAccess.dbPool.asyncRead { dbResult in + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + do { + // Fetch + let fetchedValue: Reducer.Fetched + let initialRegion: DatabaseRegion + let db = try dbResult.get() + switch self.trackingMode { + case let .constantRegion(regions): + fetchedValue = try databaseAccess.fetch(db) + let region = try DatabaseRegion.union(regions)(db) + initialRegion = try region.observableRegion(db) + + case .constantRegionRecordedFromSelection, + .nonConstantRegionRecordedFromSelection: + (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) + } + + // Reduce + // + // Reducing is performed asynchronously, so that we do not lock + // a database dispatch queue longer than necessary. + self.reduceQueue.async { + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + do { + guard let initialValue = try self.reducer._value(fetchedValue) else { + fatalError("Broken contract: reducer has no initial value") + } + + // Notify + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(initialValue) + } + } catch { + self.notifyError(error) + } + } + + // Start observation + self.asyncStartObservation( + from: databaseAccess, + initialRegion: initialRegion) + } catch { + self.notifyError(error) + } + } + } + + private func asyncStartObservation( + from databaseAccess: DatabaseAccess, + initialRegion: DatabaseRegion) + { + databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in + let events = self.lock.synchronized { self.notificationCallbacks?.events } + guard let events else { return /* Cancelled */ } + events.databaseDidChange?() + + do { + try writerDB.isolated(readOnly: true) { + // Fetch + let fetchedValue: Reducer.Fetched + let observedRegion: DatabaseRegion + switch self.trackingMode { + case .constantRegion: + fetchedValue = try databaseAccess.fetch(writerDB) + observedRegion = initialRegion + events.willTrackRegion?(initialRegion) + self.startObservation(writerDB, observedRegion: initialRegion) + + case .constantRegionRecordedFromSelection, + .nonConstantRegionRecordedFromSelection: + (fetchedValue, observedRegion) = try databaseAccess.fetchRecordingObservedRegion(writerDB) + events.willTrackRegion?(observedRegion) + self.startObservation(writerDB, observedRegion: observedRegion) + } + + // Reduce + // + // Reducing is performed asynchronously, so that we do not lock + // the writer dispatch queue longer than necessary. + // + // Important: reduceQueue.async guarantees the same ordering + // between transactions and notifications! + self.reduceQueue.async { + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + do { + let value = try self.reducer._value(fetchedValue) + + // Notify + if let value { + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(value) + } + } + } catch { + let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool } + dbPool?.asyncWriteWithoutTransaction { writerDB in + self.stopDatabaseObservation(writerDB) + } + self.notifyError(error) + } + } + } + } catch { + self.notifyError(error) + } + } } } +#endif // MARK: - Observing Database Transactions From 0a544dc0d2c04f31246290adbcaa63adc726a726 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 17 Mar 2023 08:29:06 +0100 Subject: [PATCH 10/18] Cleanup relationships between SerializedDatabase, WALSnapshotTransaction, and DatabasePool SerializedDatabase hides its allowsUnsafeTransactions property, and makes it thread-safe by protecting it inside its serialized dispatch queue. WALSnapshotTransaction always notifies when the reader connection is no longer used, and reuses the "isInsideTransaction" wording. --- GRDB/Core/DatabasePool.swift | 24 +++++---- GRDB/Core/SerializedDatabase.swift | 35 +++++++++---- GRDB/Core/WALSnapshotTransaction.swift | 57 ++++++++++++--------- Tests/GRDBTests/ValueObservationTests.swift | 4 +- 4 files changed, 73 insertions(+), 47 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 57db0d254..5f49f41c3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -644,21 +644,22 @@ extension DatabasePool: DatabaseReader { // swiftlint:disable:next line_length #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) - /// Returns a long-lived WAL snapshot transaction on one of the - /// reader connections. + /// Returns a long-lived WAL snapshot transaction on a reader connection. func walSnapshotTransaction() throws -> WALSnapshotTransaction { guard let readerPool else { throw DatabaseError.connectionIsClosed() } let (reader, releaseReader) = try readerPool.get() - return try WALSnapshotTransaction(reader: reader) { transactionCompleted in - releaseReader(transactionCompleted ? .reuse : .discard) - } + return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in + // Discard the connection if the transaction could not be + // properly ended. If we'd reuse it, the next read would + // fail because we'd fail starting a read transaction. + releaseReader(isInsideTransaction ? .discard : .reuse) + }) } - /// Returns a long-lived WAL snapshot transaction on one of the - /// reader connections. + /// Returns a long-lived WAL snapshot transaction on a reader connection. func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) @@ -668,9 +669,12 @@ extension DatabasePool: DatabaseReader { readerPool.asyncGet { result in completion(result.flatMap { reader, releaseReader in Result { - try WALSnapshotTransaction(reader: reader) { transactionCompleted in - releaseReader(transactionCompleted ? .reuse : .discard) - } + try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in + // Discard the connection if the transaction could not be + // properly ended. If we'd reuse it, the next read would + // fail because we'd fail starting a read transaction. + releaseReader(isInsideTransaction ? .discard : .reuse) + }) } }) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 76ba8d8a0..482a34978 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -8,17 +8,15 @@ final class SerializedDatabase { /// The database configuration var configuration: Configuration { db.configuration } - /// If true, overrides `configuration.allowsUnsafeTransactions`. - /// - /// See `WALSnapshotTransaction`. - var allowsUnsafeTransactions = false - /// The path to the database file let path: String /// The dispatch queue private let queue: DispatchQueue + /// If true, overrides `configuration.allowsUnsafeTransactions`. + private var allowsUnsafeTransactions = false + init( path: String, configuration: Configuration = Configuration(), @@ -81,10 +79,25 @@ final class SerializedDatabase { } } - /// Synchronously executes a block the serialized dispatch queue, and - /// returns its result. + /// Executes database operations, returns their result after they have + /// finished executing, and allows or forbids long-lived transactions. /// - /// This method is *not* reentrant. + /// This method is not reentrant. + /// + /// - parameter allowingLongLivedTransaction: When true, the + /// ``Configuration/allowsUnsafeTransactions`` configuration flag is + /// ignored until this method is called again with false. + func sync(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T { + try sync { db in + self.allowsUnsafeTransactions = allowingLongLivedTransaction + return try body(db) + } + } + + /// Executes database operations, and returns their result after they + /// have finished executing. + /// + /// This method is not reentrant. func sync(_ block: (Database) throws -> T) rethrows -> T { // Three different cases: // @@ -127,8 +140,8 @@ final class SerializedDatabase { } } - /// Synchronously executes a block the serialized dispatch queue, and - /// returns its result. + /// Executes database operations, and returns their result after they + /// have finished executing. /// /// This method is reentrant. func reentrantSync(_ block: (Database) throws -> T) rethrows -> T { @@ -194,7 +207,7 @@ final class SerializedDatabase { } } - /// Asynchronously executes a block in the serialized dispatch queue. + // Schedules database operations for execution, and returns immediately. func async(_ block: @escaping (Database) -> Void) { queue.async { block(self.db) diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index a3eb5e141..fb0323cec 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -6,50 +6,60 @@ /// `SerializedDatabase` (TODO: make it a move-only type eventually). class WALSnapshotTransaction { private let reader: SerializedDatabase - private let transactionDidComplete: (Bool) -> Void + private let release: (_ isInsideTransaction: Bool) -> Void /// The state of the database at the beginning of the transaction. let walSnapshot: WALSnapshot /// Creates a long-live WAL transaction on a read-only connection. /// - /// The `transactionDidComplete` closure is called when the - /// `WALSnapshotTransaction` is deallocated, or if the - /// initializer throws. Its argument tells if the long-lived - /// transaction could be properly terminated. + /// The `release` closure is always called. It is called when the + /// `WALSnapshotTransaction` is deallocated, or if the initializer + /// throws. + /// + /// In normal operations, the argument to `release` is always false, + /// meaning that the connection is no longer in a transaction. If true, + /// the connection has been left inside a transaction, due to + /// some error. + /// + /// Usage: + /// + /// ```swift + /// let transaction = WALSnapshotTransaction( + /// reader: reader, + /// release: { isInsideTransaction in + /// ... + /// }) + /// ``` /// /// - parameter reader: A read-only database connection. - /// - parameter transactionDidComplete: A closure to call when the - /// snapshot transaction ends. + /// - parameter release: A closure to call when the read-only connection + /// is no longer used. init( - reader: SerializedDatabase, - transactionDidComplete: @escaping (Bool) -> Void) + onReader reader: SerializedDatabase, + release: @escaping (_ isInsideTransaction: Bool) -> Void) throws { assert(reader.configuration.readonly) - // Open a transaction and enter snapshot isolation - reader.allowsUnsafeTransactions = true do { - try reader.sync { db in + // Open a long-lived transaction, and enter snapshot isolation + self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in try db.beginTransaction(.deferred) try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + return try WALSnapshot(db) } + self.reader = reader + self.release = release } catch { // self is not initialized, so deinit will not run. - Self.commitAndRelease(reader: reader, transactionDidComplete: transactionDidComplete) + Self.commitAndRelease(reader: reader, release: release) throw error } - - self.reader = reader - self.transactionDidComplete = transactionDidComplete - self.walSnapshot = try reader.sync { db in - return try WALSnapshot(db) - } } deinit { - Self.commitAndRelease(reader: reader, transactionDidComplete: transactionDidComplete) + Self.commitAndRelease(reader: reader, release: release) } /// Executes database operations in the snapshot transaction, and @@ -61,14 +71,13 @@ class WALSnapshotTransaction { private static func commitAndRelease( reader: SerializedDatabase, - transactionDidComplete: (Bool) -> Void) + release: (_ isInsideTransaction: Bool) -> Void) { - reader.allowsUnsafeTransactions = false - let success = reader.sync { db in + let isInsideTransaction = reader.sync(allowingLongLivedTransaction: false) { db in try? db.commit() return db.isInsideTransaction } - transactionDidComplete(success) + release(isInsideTransaction) } } #endif diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 754b73046..798b389e4 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -412,8 +412,8 @@ class ValueObservationTests: GRDBTestCase { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try! dbPool.write { db in try db.execute(sql: """ - INSERT INTO t DEFAULT VALUES; - """) + INSERT INTO t DEFAULT VALUES; + """) } } } From 2f4d0c4588dc471a8a6e74e119cf2f0f42793fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 17 Mar 2023 08:41:22 +0100 Subject: [PATCH 11/18] CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4187848c..ff9744e3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,6 +107,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): ValueObservation on DatabasePool no longer opens a new database connection when it starts + ## 6.9.2 Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.1...v6.9.2) From 063877d49cefa8ac5c26621efc633b2b3b64ae8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 17 Mar 2023 13:28:49 +0100 Subject: [PATCH 12/18] Configuration.persistentReaderConnections --- GRDB/Core/Configuration.swift | 25 ++- GRDB/Core/DatabasePool.swift | 63 ++++-- .../Extension/Configuration.md | 1 + .../DatabasePoolReleaseMemoryTests.swift | 200 +++++++++++------- 4 files changed, 190 insertions(+), 99 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index db85192f2..f2868d108 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -301,7 +301,7 @@ public struct Configuration { /// If nil, GRDB picks a default one. var readonlyBusyMode: Database.BusyMode? = nil - /// The maximum number of concurrent readers. + /// The maximum number of concurrent read-only connections. /// /// This configuration applies to ``DatabasePool`` only. The default value /// is 5. @@ -372,7 +372,28 @@ public struct Configuration { /// The default is true. public var automaticMemoryManagement = true #endif - + + /// A boolean value indicating whether read-only connections should be + /// kept open as long as they remain in a valid state. + /// + /// This configuration applies to ``DatabasePool`` only. The default value + /// is false. + /// + /// A `DatabasePool` automatically closes read-only connections on + /// various occasions, in order to spare memory + /// (see ``DatabasePool/releaseMemory()``), or when connections enter an + /// invalid state. + /// + /// When this flag is true, only invalid connections are automatically + /// closed. Valid connections, once opened, are kept alive until the + /// `DatabasePool` is deinitialized, or one of those methods is called: + /// ``DatabaseReader/close()``, + /// ``DatabasePool/invalidateReadOnlyConnections()``. + /// + /// Consider using this flag when profiling your application reveals + /// that a lot of time is spent opening new SQLite connections. + public var persistentReaderConnections = false + // MARK: - Factory Configuration /// Creates a factory configuration. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5f49f41c3..b08a13906 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -168,12 +168,15 @@ extension DatabasePool { // MARK: - Memory management - /// Frees as much memory as possible, by disposing non-essential memory from - /// the writer connection, and closing all reader connections. + /// Frees as much memory as possible, by disposing non-essential memory. /// /// This method is synchronous, and blocks the current thread until all /// database accesses are completed. /// + /// This method closes all reader connections, unless the + /// ``Configuration/persistentReaderConnections`` configuration flag + /// is set. + /// /// - warning: This method can prevent concurrent reads from executing, /// until it returns. Prefer ``releaseMemoryEventually()`` if you intend /// to keep on using the database while releasing memory. @@ -181,34 +184,50 @@ extension DatabasePool { // Release writer memory writer.sync { $0.releaseMemory() } - // Release readers memory by closing all connections. - // - // We must use a barrier in order to guarantee that memory has been - // freed (reader connections closed) when the method exits, as - // documented. - // - // Without the barrier, connections would only close _eventually_ (after - // their eventual concurrent jobs have completed). - readerPool?.barrier { - readerPool?.removeAll() + if configuration.persistentReaderConnections { + // Keep existing readers + readerPool?.forEach { reader in + reader.sync { $0.releaseMemory() } + } + } else { + // Release readers memory by closing all connections. + // + // We must use a barrier in order to guarantee that memory has been + // freed (reader connections closed) when the method exits, as + // documented. + // + // Without the barrier, connections would only close _eventually_ (after + // their eventual concurrent jobs have completed). + readerPool?.barrier { + readerPool?.removeAll() + } } } - /// Eventually frees as much memory as possible, by disposing non-essential - /// memory from the writer connection, and closing all reader connections. + /// Eventually frees as much memory as possible, by disposing + /// non-essential memory. + /// + /// This method eventually closes all reader connections, unless the + /// ``Configuration/persistentReaderConnections`` configuration flag + /// is set. /// /// Unlike ``releaseMemory()``, this method does not prevent concurrent /// database accesses when it is executing. But it does not notify when /// non-essential memory has been freed. public func releaseMemoryEventually() { - // Release readers memory by eventually closing all reader connections - // (they will close after their current jobs have completed). - readerPool?.removeAll() + if configuration.persistentReaderConnections { + // Keep existing readers + readerPool?.forEach { reader in + reader.async { $0.releaseMemory() } + } + } else { + // Release readers memory by eventually closing all reader connections + // (they will close after their current jobs have completed). + readerPool?.removeAll() + } // Release writer memory eventually. - writer.async { db in - db.releaseMemory() - } + writer.async { $0.releaseMemory() } } #if os(iOS) @@ -610,6 +629,10 @@ extension DatabasePool: DatabaseReader { /// /// Eventual concurrent read-only accesses are not invalidated: they will /// proceed until completion. + /// + /// - This method closes all read-only connections, even if the + /// ``Configuration/persistentReaderConnections`` configuration flag + /// is set. public func invalidateReadOnlyConnections() { readerPool?.removeAll() } diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index 87464a9e7..aaf64e58f 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -92,6 +92,7 @@ do { - ``label`` - ``maximumReaderCount`` - ``observesSuspensionNotifications`` +- ``persistentReaderConnections`` - ``prepareDatabase(_:)`` - ``publicStatementArguments`` - ``transactionClock`` diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 30df8d81b..31e26faa8 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -120,83 +120,129 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { #endif - // TODO: fix flaky test -// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws { -// let countQueue = DispatchQueue(label: "GRDB") -// var openConnectionCount = 0 -// var totalOpenConnectionCount = 0 -// -// dbConfiguration.SQLiteConnectionDidOpen = { -// countQueue.sync { -// totalOpenConnectionCount += 1 -// openConnectionCount += 1 -// } -// } -// -// dbConfiguration.SQLiteConnectionDidClose = { -// countQueue.sync { -// openConnectionCount -= 1 -// } -// } -// -// let dbPool = try makeDatabasePool() -// try dbPool.write { db in -// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") -// for _ in 0..<2 { -// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") -// } -// } -// -// // Block 1 Block 2 Block3 -// // SELECT * FROM items -// // step -// // > -// let s1 = DispatchSemaphore(value: 0) -// // SELECT * FROM items -// // step -// // > -// let s2 = DispatchSemaphore(value: 0) -// // step step -// // > -// let s3 = DispatchSemaphore(value: 0) -// // end end releaseMemory -// -// let block1 = { () in -// try! dbPool.read { db in -// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") -// XCTAssertTrue(try cursor.next() != nil) -// s1.signal() -// _ = s2.wait(timeout: .distantFuture) -// XCTAssertTrue(try cursor.next() != nil) -// s3.signal() -// XCTAssertTrue(try cursor.next() == nil) -// } -// } -// let block2 = { () in -// _ = s1.wait(timeout: .distantFuture) -// try! dbPool.read { db in -// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") -// XCTAssertTrue(try cursor.next() != nil) -// s2.signal() -// XCTAssertTrue(try cursor.next() != nil) -// XCTAssertTrue(try cursor.next() == nil) -// } -// } -// let block3 = { () in -// _ = s3.wait(timeout: .distantFuture) -// dbPool.releaseMemory() -// } -// let blocks = [block1, block2, block3] -// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes -// blocks[index]() -// } -// -// // Two readers, one writer -// XCTAssertEqual(totalOpenConnectionCount, 3) -// -// // Writer is still open -// XCTAssertEqual(openConnectionCount, 1) -// } + func test_DatabasePool_releaseMemory_closes_reader_connections() throws { + // A complicated test setup that opens multiple reader connections. + let countQueue = DispatchQueue(label: "GRDB") + var openConnectionCount = 0 + var totalOpenConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + countQueue.sync { + totalOpenConnectionCount += 1 + openConnectionCount += 1 + } + } + + dbConfiguration.SQLiteConnectionDidClose = { + countQueue.sync { + openConnectionCount -= 1 + } + } + + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + for _ in 0..<2 { + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + } + } + + // Block 1 Block 2 Block3 + // SELECT * FROM items + // step + // > + let s1 = DispatchSemaphore(value: 0) + // SELECT * FROM items + // step + // > + let s2 = DispatchSemaphore(value: 0) + // step step + // > + let s3 = DispatchSemaphore(value: 0) + // end end releaseMemory + + let block1 = { () in + try! dbPool.read { db in + let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") + XCTAssertTrue(try cursor.next() != nil) + s1.signal() + _ = s2.wait(timeout: .distantFuture) + XCTAssertTrue(try cursor.next() != nil) + s3.signal() + XCTAssertTrue(try cursor.next() == nil) + } + } + let block2 = { () in + _ = s1.wait(timeout: .distantFuture) + try! dbPool.read { db in + let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") + XCTAssertTrue(try cursor.next() != nil) + s2.signal() + XCTAssertTrue(try cursor.next() != nil) + XCTAssertTrue(try cursor.next() == nil) + } + } + let block3 = { () in + _ = s3.wait(timeout: .distantFuture) + dbPool.releaseMemory() + } + let blocks = [block1, block2, block3] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes + blocks[index]() + } + + // Two readers, one writer + XCTAssertEqual(totalOpenConnectionCount, 3) + + // Writer is still open + XCTAssertEqual(openConnectionCount, 1) + } + + func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReaderConnections_is_false() throws { + var persistentConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + persistentConnectionCount += 1 + } + + dbConfiguration.SQLiteConnectionDidClose = { + persistentConnectionCount -= 1 + } + + dbConfiguration.persistentReaderConnections = false + + let dbPool = try makeDatabasePool() + XCTAssertEqual(persistentConnectionCount, 1) // writer + + try dbPool.read { _ in } + XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + + dbPool.releaseMemory() + XCTAssertEqual(persistentConnectionCount, 1) // writer + } + + func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReaderConnections_is_true() throws { + var persistentConnectionCount = 0 + + dbConfiguration.SQLiteConnectionDidOpen = { + persistentConnectionCount += 1 + } + + dbConfiguration.SQLiteConnectionDidClose = { + persistentConnectionCount -= 1 + } + + dbConfiguration.persistentReaderConnections = true + + let dbPool = try makeDatabasePool() + XCTAssertEqual(persistentConnectionCount, 1) // writer + + try dbPool.read { _ in } + XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + + dbPool.releaseMemory() + XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + } func testBlocksRetainConnection() throws { let countQueue = DispatchQueue(label: "GRDB") From 6ca4986bc2ba985d5b61a4359aa64731a6bca9f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Fri, 17 Mar 2023 13:51:29 +0100 Subject: [PATCH 13/18] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff9744e3a..e00294c10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,7 +109,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release -- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): ValueObservation on DatabasePool no longer opens a new database connection when it starts +- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts. ## 6.9.2 From 449c243a361c0e66213bb4038614eb9d2afdcae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 18 Mar 2023 11:08:56 +0100 Subject: [PATCH 14/18] Rename persistentReaderConnections to dbConfiguration.persistentReadOnlyConnections --- GRDB/Core/Configuration.swift | 26 +++++++------------ GRDB/Core/DatabasePool.swift | 16 ++++++------ .../Extension/Configuration.md | 2 +- .../DatabasePoolReleaseMemoryTests.swift | 8 +++--- 4 files changed, 23 insertions(+), 29 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index f2868d108..495b32690 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -374,25 +374,19 @@ public struct Configuration { #endif /// A boolean value indicating whether read-only connections should be - /// kept open as long as they remain in a valid state. + /// kept open. /// - /// This configuration applies to ``DatabasePool`` only. The default value - /// is false. + /// This configuration flag applies to ``DatabasePool`` only. The + /// default value is false. /// - /// A `DatabasePool` automatically closes read-only connections on - /// various occasions, in order to spare memory - /// (see ``DatabasePool/releaseMemory()``), or when connections enter an - /// invalid state. + /// When the flag is false, a `DatabasePool` closes read-only + /// connections when requested to dispose non-essential memory with + /// ``DatabasePool/releaseMemory()``. When true, those connections are + /// kept open. /// - /// When this flag is true, only invalid connections are automatically - /// closed. Valid connections, once opened, are kept alive until the - /// `DatabasePool` is deinitialized, or one of those methods is called: - /// ``DatabaseReader/close()``, - /// ``DatabasePool/invalidateReadOnlyConnections()``. - /// - /// Consider using this flag when profiling your application reveals - /// that a lot of time is spent opening new SQLite connections. - public var persistentReaderConnections = false + /// Consider setting this flag to true when profiling your application + /// reveals that a lot of time is spent opening new SQLite connections. + public var persistentReadOnlyConnections = false // MARK: - Factory Configuration diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b08a13906..a19baf918 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -173,8 +173,8 @@ extension DatabasePool { /// This method is synchronous, and blocks the current thread until all /// database accesses are completed. /// - /// This method closes all reader connections, unless the - /// ``Configuration/persistentReaderConnections`` configuration flag + /// This method closes all read-only connections, unless the + /// ``Configuration/persistentReadOnlyConnections`` configuration flag /// is set. /// /// - warning: This method can prevent concurrent reads from executing, @@ -184,7 +184,7 @@ extension DatabasePool { // Release writer memory writer.sync { $0.releaseMemory() } - if configuration.persistentReaderConnections { + if configuration.persistentReadOnlyConnections { // Keep existing readers readerPool?.forEach { reader in reader.sync { $0.releaseMemory() } @@ -207,15 +207,15 @@ extension DatabasePool { /// Eventually frees as much memory as possible, by disposing /// non-essential memory. /// - /// This method eventually closes all reader connections, unless the - /// ``Configuration/persistentReaderConnections`` configuration flag + /// This method eventually closes all read-only connections, unless the + /// ``Configuration/persistentReadOnlyConnections`` configuration flag /// is set. /// /// Unlike ``releaseMemory()``, this method does not prevent concurrent /// database accesses when it is executing. But it does not notify when /// non-essential memory has been freed. public func releaseMemoryEventually() { - if configuration.persistentReaderConnections { + if configuration.persistentReadOnlyConnections { // Keep existing readers readerPool?.forEach { reader in reader.async { $0.releaseMemory() } @@ -627,11 +627,11 @@ extension DatabasePool: DatabaseReader { /// After this method is called, read-only database access methods will use /// new SQLite connections. /// - /// Eventual concurrent read-only accesses are not invalidated: they will + /// Eventual concurrent read-only accesses are not interrupted, and /// proceed until completion. /// /// - This method closes all read-only connections, even if the - /// ``Configuration/persistentReaderConnections`` configuration flag + /// ``Configuration/persistentReadOnlyConnections`` configuration flag /// is set. public func invalidateReadOnlyConnections() { readerPool?.removeAll() diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index aaf64e58f..e2e4b2743 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -92,7 +92,7 @@ do { - ``label`` - ``maximumReaderCount`` - ``observesSuspensionNotifications`` -- ``persistentReaderConnections`` +- ``persistentReadOnlyConnections`` - ``prepareDatabase(_:)`` - ``publicStatementArguments`` - ``transactionClock`` diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 31e26faa8..9b6bb306c 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -198,7 +198,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { XCTAssertEqual(openConnectionCount, 1) } - func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReaderConnections_is_false() throws { + func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReadOnlyConnections_is_false() throws { var persistentConnectionCount = 0 dbConfiguration.SQLiteConnectionDidOpen = { @@ -209,7 +209,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { persistentConnectionCount -= 1 } - dbConfiguration.persistentReaderConnections = false + dbConfiguration.persistentReadOnlyConnections = false let dbPool = try makeDatabasePool() XCTAssertEqual(persistentConnectionCount, 1) // writer @@ -221,7 +221,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { XCTAssertEqual(persistentConnectionCount, 1) // writer } - func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReaderConnections_is_true() throws { + func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReadOnlyConnections_is_true() throws { var persistentConnectionCount = 0 dbConfiguration.SQLiteConnectionDidOpen = { @@ -232,7 +232,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { persistentConnectionCount -= 1 } - dbConfiguration.persistentReaderConnections = true + dbConfiguration.persistentReadOnlyConnections = true let dbPool = try makeDatabasePool() XCTAssertEqual(persistentConnectionCount, 1) // writer From 5d9b9edfe168099048481733769a97b850e08235 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Mar 2023 12:39:48 +0100 Subject: [PATCH 15/18] Fix asyncWALSnapshotTransaction usage. We must use its result asynchronously. --- GRDB/Core/DatabasePool.swift | 3 + GRDB/Core/SerializedDatabase.swift | 15 +++ GRDB/Core/WALSnapshotTransaction.swift | 13 ++- .../Observers/ValueConcurrentObserver.swift | 94 ++++++++++--------- 4 files changed, 79 insertions(+), 46 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index a19baf918..b89f0c4c1 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -683,6 +683,9 @@ extension DatabasePool: DatabaseReader { } /// Returns a long-lived WAL snapshot transaction on a reader connection. + /// + /// - important: The `completion` argument is executed in a serial + /// dispatch queue, so make sure you use the transaction asynchronously. func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 482a34978..d7c4d4fbf 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -140,6 +140,21 @@ final class SerializedDatabase { } } + /// Executes database operations, returns their result after they have + /// finished executing, and allows or forbids long-lived transactions. + /// + /// This method is not reentrant. + /// + /// - parameter allowingLongLivedTransaction: When true, the + /// ``Configuration/allowsUnsafeTransactions`` configuration flag is + /// ignored until this method is called again with false. + func reentrantSync(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T { + try reentrantSync { db in + self.allowsUnsafeTransactions = allowingLongLivedTransaction + return try body(db) + } + } + /// Executes database operations, and returns their result after they /// have finished executing. /// diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index fb0323cec..32eb3afca 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -65,15 +65,24 @@ class WALSnapshotTransaction { /// Executes database operations in the snapshot transaction, and /// returns their result after they have finished executing. func read(_ value: (Database) throws -> T) rethrows -> T { - // TODO: we should check the validity of the snapshot, as DatabaseSnapshotPool does. + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. try reader.sync(value) } + /// Schedules database operations for execution, and + /// returns immediately. + func asyncRead(_ value: @escaping (Database) -> Void) { + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + reader.async(value) + } + private static func commitAndRelease( reader: SerializedDatabase, release: (_ isInsideTransaction: Bool) -> Void) { - let isInsideTransaction = reader.sync(allowingLongLivedTransaction: false) { db in + // WALSnapshotTransaction may be deinitialized in the dispatch + // queue of its reader: allow reentrancy. + let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in try? db.commit() return db.isInsideTransaction } diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 7211c20c0..27a4184e8 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -324,50 +324,56 @@ extension ValueConcurrentObserver { do { // Fetch let walSnapshotTransaction = try result.get() - try walSnapshotTransaction.read { db in - let fetchedValue: Reducer.Fetched - let initialRegion: DatabaseRegion - - switch self.trackingMode { - case let .constantRegion(regions): - fetchedValue = try databaseAccess.fetch(db) - let region = try DatabaseRegion.union(regions)(db) - initialRegion = try region.observableRegion(db) + // Second async jump because that's how + // `DatabasePool.asyncWALSnapshotTransaction` has to be used. + walSnapshotTransaction.asyncRead { db in + do { + let fetchedValue: Reducer.Fetched + let initialRegion: DatabaseRegion - case .constantRegionRecordedFromSelection, - .nonConstantRegionRecordedFromSelection: - (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) - } - - // Reduce - // - // Reducing is performed asynchronously, so that we do not lock - // a database dispatch queue longer than necessary. - self.reduceQueue.async { - let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } - guard isNotifying else { return /* Cancelled */ } - - do { - guard let initialValue = try self.reducer._value(fetchedValue) else { - fatalError("Broken contract: reducer has no initial value") - } + switch self.trackingMode { + case let .constantRegion(regions): + fetchedValue = try databaseAccess.fetch(db) + let region = try DatabaseRegion.union(regions)(db) + initialRegion = try region.observableRegion(db) - // Notify - self.scheduler.schedule { - let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } - guard let onChange else { return /* Cancelled */ } - onChange(initialValue) - } - } catch { - self.notifyError(error) + case .constantRegionRecordedFromSelection, + .nonConstantRegionRecordedFromSelection: + (fetchedValue, initialRegion) = try databaseAccess.fetchRecordingObservedRegion(db) } + + // Reduce + // + // Reducing is performed asynchronously, so that we do not lock + // a database dispatch queue longer than necessary. + self.reduceQueue.async { + let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil } + guard isNotifying else { return /* Cancelled */ } + + do { + guard let initialValue = try self.reducer._value(fetchedValue) else { + fatalError("Broken contract: reducer has no initial value") + } + + // Notify + self.scheduler.schedule { + let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange } + guard let onChange else { return /* Cancelled */ } + onChange(initialValue) + } + } catch { + self.notifyError(error) + } + } + + // Start observation + self.asyncStartObservation( + from: databaseAccess, + walSnapshotTransaction: walSnapshotTransaction, + initialRegion: initialRegion) + } catch { + self.notifyError(error) } - - // Start observation - self.asyncStartObservation( - from: databaseAccess, - walSnapshotTransaction: walSnapshotTransaction, - initialRegion: initialRegion) } } catch { self.notifyError(error) @@ -389,10 +395,10 @@ extension ValueConcurrentObserver { // Transaction is needed for comparing version snapshots try writerDB.isolated(readOnly: true) { - // Keep walSnapshotTransaction alive until we have compared - // database versions. It prevents database checkpointing, - // and keeps WAL snapshots (`sqlite3_snapshot`) valid - // and comparable. + // Keep walSnapshotTransaction alive until we have + // compared database versions. `WALSnapshot` alone is + // not able to prevent database checkpointing, and keep + // snapshots comparable. let isModified = withExtendedLifetime(walSnapshotTransaction) { guard let currentWALSnapshot = try? WALSnapshot(writerDB) else { return true From 5629cfe6ffaba1ac45aa6413fcef9f4241f33845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Mar 2023 13:56:56 +0100 Subject: [PATCH 16/18] Fix documentation --- GRDB/Core/Configuration.swift | 11 +++++++---- GRDB/Core/SerializedDatabase.swift | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 495b32690..58889b4bb 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -301,13 +301,15 @@ public struct Configuration { /// If nil, GRDB picks a default one. var readonlyBusyMode: Database.BusyMode? = nil - /// The maximum number of concurrent read-only connections. + /// The maximum number of concurrent reader connections. /// - /// This configuration applies to ``DatabasePool`` only. The default value - /// is 5. + /// This configuration has effect on ``DatabasePool`` and + /// ``DatabaseSnapshotPool`` only. The default value is 5. /// /// You can query this value at runtime in order to get the actual capacity - /// for concurrent reads of any ``DatabaseReader``. For example: + /// for concurrent reads of any ``DatabaseReader``. In this context, + /// ``DatabaseQueue`` and ``DatabaseSnapshot`` have a capacity of 1, + /// because they can't perform two concurrent reads. For example: /// /// ```swift /// var config = Configuration() @@ -321,6 +323,7 @@ public struct Configuration { /// print(dbQueue.configuration.maximumReaderCount) // 1 /// print(dbPool.configuration.maximumReaderCount) // 5 /// print(dbSnapshot.configuration.maximumReaderCount) // 1 + /// ``` public var maximumReaderCount: Int = 5 /// The quality of service of database accesses. diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index d7c4d4fbf..8861deb9c 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -222,7 +222,7 @@ final class SerializedDatabase { } } - // Schedules database operations for execution, and returns immediately. + /// Schedules database operations for execution, and returns immediately. func async(_ block: @escaping (Database) -> Void) { queue.async { block(self.db) From 600d1b84b6daae23283d31581383dfbe338bead3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 20 Mar 2023 07:02:00 +0100 Subject: [PATCH 17/18] Update GRDB/Core/SerializedDatabase.swift Co-authored-by: Rogerio de Paula Assis --- GRDB/Core/SerializedDatabase.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 8861deb9c..f1dfe0572 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -143,7 +143,7 @@ final class SerializedDatabase { /// Executes database operations, returns their result after they have /// finished executing, and allows or forbids long-lived transactions. /// - /// This method is not reentrant. + /// This method is reentrant. /// /// - parameter allowingLongLivedTransaction: When true, the /// ``Configuration/allowsUnsafeTransactions`` configuration flag is From a551fbf4434d96c26aac5cd97731bf4cc9c82c09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 20 Mar 2023 07:53:28 +0100 Subject: [PATCH 18/18] v6.10.0 --- CHANGELOG.md | 5 ++++- GRDB.swift.podspec | 2 +- README.md | 4 ++-- Support/Info.plist | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e00294c10..67e289cf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.10.x` Releases - [6.10.0](#6100) - `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692) - `6.8.x` Releases - [6.8.0](#680) - `6.7.x` Releases - [6.7.0](#670) @@ -107,7 +108,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 6.10.0 + +Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0) - **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts. diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 84e7c2a19..11410caca 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.9.2' + s.version = '6.10.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index ae14c2c43..bd61b26e5 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: March 14, 2023 • [version 6.9.2](https://github.com/groue/GRDB.swift/tree/v6.9.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: March 20, 2023 • [version 6.10.0](https://github.com/groue/GRDB.swift/tree/v6.10.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.9.2** | +| **Swift 5.7+** | **v6.10.0** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | diff --git a/Support/Info.plist b/Support/Info.plist index 585756663..3bb5a6faa 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.9.2 + 6.10.0 CFBundleSignature ???? CFBundleVersion