mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
BREAKING: Handles both commits and rollbacks
Replace afterNextTransactionCommit(_:) with afterNextTransaction(onCommit:onRollback:)
This commit is contained in:
1 parent
8f562d3e11
commit
422e0ae85a
7 files changed
+104
-51
No files matched your search
@@ -107,6 +107,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- **Breaking**: `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
|
||||
- **Breaking**: The `DatabaseRegionObservation.extent` property was removed.
|
||||
- **Breaking**: The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`.
|
||||
- **Breaking**: The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
- **Breaking**: Record types can no longer override persistence methods. You use persistence callbacks instead.
|
||||
- **New**: Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md).
|
||||
- **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
|
||||
|
||||
@@ -315,3 +315,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
+let sql = cursor.sql
|
||||
+let columns = cursor.columnNames
|
||||
```
|
||||
|
||||
- The transaction hook `Database.afterNextTransactionCommit(_:)` was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Succesful commit")
|
||||
}
|
||||
```
|
||||
@@ -39,40 +39,54 @@ extension Database {
|
||||
observationBroker.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
|
||||
/// Registers a closure to be executed after the next or current
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completion.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// db.afterNextTransactionCommit { _ in
|
||||
/// db.afterNextTransaction { _ in
|
||||
/// print("success")
|
||||
/// }
|
||||
/// ...
|
||||
/// } // prints "success"
|
||||
/// } // prints "commit"
|
||||
///
|
||||
/// If the transaction is rollbacked, the closure is not executed.
|
||||
/// Closure are executed in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
///
|
||||
/// If the transaction is committed, the closure is executed in a protected
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) {
|
||||
class CommitHandler: TransactionObserver {
|
||||
let closure: (Database) -> Void
|
||||
|
||||
init(_ closure: @escaping (Database) -> Void) {
|
||||
self.closure = closure
|
||||
/// - precondition: Database is not read-only.
|
||||
/// - parameter onCommit: A closure execute on transaction commit.
|
||||
/// - parameter onRollback: A closure execute on transaction rollback.
|
||||
public func afterNextTransaction(
|
||||
onCommit: @escaping (Database) -> Void,
|
||||
onRollback: @escaping (Database) -> Void = { _ in })
|
||||
{
|
||||
class TransactionHandler: TransactionObserver {
|
||||
let onCommit: (Database) -> Void
|
||||
let onRollback: (Database) -> Void
|
||||
|
||||
init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) {
|
||||
self.onCommit = onCommit
|
||||
self.onRollback = onRollback
|
||||
}
|
||||
|
||||
// Ignore individual changes and transaction rollbacks
|
||||
// Ignore changes
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
|
||||
// On commit, run closure
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
closure(db)
|
||||
onCommit(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
onRollback(db)
|
||||
}
|
||||
}
|
||||
|
||||
add(transactionObserver: CommitHandler(closure), extent: .nextTransaction)
|
||||
// We don't notify read-only transactions to transaction observers
|
||||
GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
add(
|
||||
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
|
||||
extent: .nextTransaction)
|
||||
}
|
||||
|
||||
/// The extent of a transaction observation.
|
||||
@@ -497,7 +511,7 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// For example, is the code below expected to print "did commit"?
|
||||
//
|
||||
// db.afterNextTransactionCommit { _ in print("did commit") }
|
||||
// db.afterNextTransaction { _ in print("did commit") }
|
||||
// try db.inTransaction {
|
||||
// performSomeTask(db)
|
||||
// return .commit
|
||||
|
||||
@@ -36,6 +36,9 @@ extension Database {
|
||||
|
||||
@available(*, unavailable, renamed: "makeStatement(literal:)")
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, renamed: "afterNextTransaction(onCommit:)")
|
||||
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension DatabaseCursor {
|
||||
|
||||
@@ -3148,7 +3148,20 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut
|
||||
>
|
||||
> :warning: **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL.
|
||||
>
|
||||
> :warning: **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle committed changes, use the [After Commit Hook](#after-commit-hook).
|
||||
> :warning: **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [Transaction Hook](#transaction-hook). For example:
|
||||
>
|
||||
> ```swift
|
||||
> struct PictureFile: PersistableRecord {
|
||||
> var path: String
|
||||
>
|
||||
> func willDelete(_ db: Database) {
|
||||
> db.afterNextTransaction { _ in
|
||||
> try? deleteFileOnDisk()
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
## Identifiable Records
|
||||
|
||||
@@ -6122,7 +6135,7 @@ Database Changes Observation
|
||||
|
||||
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
|
||||
|
||||
- [After Commit Hook](#after-commit-hook): Handle successful transactions one by one.
|
||||
- [Transaction Hook](#transaction-hook): Handle transactions commits or rollbacks, one by one.
|
||||
- [ValueObservation]: Track changes of database values.
|
||||
- [DatabaseRegionObservation]: Tracking transactions that impact a database region.
|
||||
- [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation.
|
||||
@@ -6132,24 +6145,20 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas
|
||||
Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage.
|
||||
|
||||
|
||||
## After Commit Hook
|
||||
## Transaction Hook
|
||||
|
||||
When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method.
|
||||
|
||||
Its closure argument is called right after database changes have been successfully written to disk:
|
||||
When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransaction(onCommit:onRollback:)` method.
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
db.afterNextTransactionCommit { db in
|
||||
print("success")
|
||||
db.afterNextTransaction { db in
|
||||
print("successful commit")
|
||||
}
|
||||
...
|
||||
} // prints "success"
|
||||
} // prints "successful commit"
|
||||
```
|
||||
|
||||
The closure runs in a protected dispatch queue, serialized with all database updates.
|
||||
|
||||
**This "after commit hook" helps synchronizing the database with other resources, such as files, or system sensors.**
|
||||
**This hook helps synchronizing the database with other resources, such as files, or system sensors.**
|
||||
|
||||
In the example below, a [location manager](https://developer.apple.com/documentation/corelocation/cllocationmanager) starts monitoring a CLRegion if and only if it has successfully been stored in the database:
|
||||
|
||||
@@ -6165,7 +6174,7 @@ func startMonitoring(_ db: Database, region: CLRegion) throws {
|
||||
|
||||
// Start monitoring if and only if the insertion is
|
||||
// eventually committed
|
||||
db.afterNextTransactionCommit { _ in
|
||||
db.afterNextTransaction { _ in
|
||||
// locationManager prefers the main queue:
|
||||
DispatchQueue.main.async {
|
||||
locationManager.startMonitoring(for: region)
|
||||
@@ -8628,6 +8637,10 @@ This protocol has been renamed [TableRecord] in GRDB 3.0.
|
||||
|
||||
This chapter was replaced with [Persistence Callbacks].
|
||||
|
||||
#### After Commit Hook
|
||||
|
||||
This chapter was replaced with [Transaction Hook].
|
||||
|
||||
#### ValueObservation and DatabaseRegionObservation
|
||||
|
||||
This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation].
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
- [?] expose throwing row accessors
|
||||
- [ ] GRDB 6: Batch insert & Batch insert RETURNING - https://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database
|
||||
- [ ] GRDB 6: INSERT or UPDATE columns to their default value
|
||||
- [ ] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:)
|
||||
- [X] GRDB 6: afterNextTransactionCommit -> afterNextTransaction(onCommit:onRollback:)
|
||||
- [ ] GRDB 6: encoding errors for record (`EncodableRecord.encode(to:)`)
|
||||
- [ ] throwing EncodableRecord.encode FIRST
|
||||
- [?] GRDB 6: protocol-based record container? This could avoid computing & encoding values we do not need.
|
||||
|
||||
@@ -42,27 +42,28 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
var transactionCount = 0
|
||||
var commitCount = 0
|
||||
weak var deallocationWitness: Witness? = nil
|
||||
do {
|
||||
let witness = Witness()
|
||||
deallocationWitness = witness
|
||||
db.afterNextTransactionCommit { _ in
|
||||
// Usage test: single closure (the onCommit one)
|
||||
db.afterNextTransaction { _ in
|
||||
// use witness
|
||||
withExtendedLifetime(witness, { })
|
||||
transactionCount += 1
|
||||
commitCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertNotNil(deallocationWitness)
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
XCTAssertEqual(commitCount, 0)
|
||||
try db.execute(sql: startSQL)
|
||||
try db.execute(sql: endSQL)
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
@@ -72,9 +73,9 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
}
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,28 +85,38 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
var transactionCount = 0
|
||||
var commitCount = 0
|
||||
var rollbackCount = 0
|
||||
try db.execute(sql: startSQL)
|
||||
|
||||
weak var deallocationWitness: Witness? = nil
|
||||
do {
|
||||
let witness = Witness()
|
||||
deallocationWitness = witness
|
||||
db.afterNextTransactionCommit { _ in
|
||||
// use witness
|
||||
withExtendedLifetime(witness, { })
|
||||
transactionCount += 1
|
||||
}
|
||||
// Usage test: both closure
|
||||
db.afterNextTransaction(
|
||||
onCommit: { _ in
|
||||
// use witness
|
||||
withExtendedLifetime(witness, { })
|
||||
commitCount += 1
|
||||
},
|
||||
onRollback: { _ in
|
||||
// use witness
|
||||
withExtendedLifetime(witness, { })
|
||||
rollbackCount += 1
|
||||
})
|
||||
}
|
||||
|
||||
XCTAssertNotNil(deallocationWitness)
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
XCTAssertEqual(commitCount, 0)
|
||||
try db.execute(sql: endSQL)
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
@@ -115,9 +126,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
}
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
|
||||
XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user