mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
DatabaseTransactionDelegate documentation
This commit is contained in:
1 parent
5e8e9da629
commit
5c8d01373e
5 files changed
+217
-59
No files matched your search
+1
-17
@@ -3,23 +3,7 @@ Release Notes
|
||||
|
||||
## Next Release
|
||||
|
||||
- New protocol DatabaseTransactionDelegate:
|
||||
|
||||
```swift
|
||||
public protocol DatabaseTransactionDelegate: class {
|
||||
// Notify a database change (insert, update or delete):
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent)
|
||||
|
||||
// An opportunity to rollback database changes:
|
||||
func databaseShouldCommit() -> Bool
|
||||
|
||||
// Database changes have been committed:
|
||||
func databaseDidCommit()
|
||||
|
||||
// Database changes have been rollbacked:
|
||||
func databaseDidRollback()
|
||||
}
|
||||
```
|
||||
- DatabaseTransactionDelegate protocol.
|
||||
|
||||
|
||||
## 0.18.0
|
||||
|
||||
+88
-17
@@ -2,20 +2,23 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class TransactionDelegate : DatabaseTransactionDelegate {
|
||||
var committedEvents: [DatabaseEvent] = []
|
||||
var lastTransactionCompletion: Database.TransactionCompletion! = nil
|
||||
var lastCommittedEvents: [DatabaseEvent] = []
|
||||
var events: [DatabaseEvent] = []
|
||||
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent) {
|
||||
func database(db: Database, didChangeWithEvent event: DatabaseEvent) {
|
||||
events.append(event)
|
||||
}
|
||||
|
||||
func databaseDidCommit() {
|
||||
committedEvents = events
|
||||
func databaseDidCommit(db: Database) {
|
||||
lastTransactionCompletion = .Commit
|
||||
lastCommittedEvents = events
|
||||
events = []
|
||||
}
|
||||
|
||||
func databaseDidRollback() {
|
||||
committedEvents = []
|
||||
func databaseDidRollback(db: Database) {
|
||||
lastTransactionCompletion = .Rollback
|
||||
lastCommittedEvents = []
|
||||
events = []
|
||||
}
|
||||
}
|
||||
@@ -61,7 +64,7 @@ class Artwork : Record {
|
||||
var artistId: Int64?
|
||||
var title: String?
|
||||
|
||||
init(title: String?, artistId: Int64?) {
|
||||
init(title: String?, artistId: Int64? = nil) {
|
||||
self.title = title
|
||||
self.artistId = artistId
|
||||
super.init()
|
||||
@@ -122,8 +125,8 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
|
||||
|
||||
//
|
||||
try artist.save(db)
|
||||
XCTAssertEqual(delegate.committedEvents.count, 1)
|
||||
let event = delegate.committedEvents.filter { event in
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
|
||||
let event = delegate.lastCommittedEvents.filter { event in
|
||||
self.match(event: event, kind: .Insert, tableName: "artists", rowId: artist.id!)
|
||||
}.first
|
||||
XCTAssertTrue(event != nil)
|
||||
@@ -142,8 +145,8 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
|
||||
|
||||
//
|
||||
try artist.save(db)
|
||||
XCTAssertEqual(delegate.committedEvents.count, 1)
|
||||
let event = delegate.committedEvents.filter {
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
|
||||
let event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Update, tableName: "artists", rowId: artist.id!)
|
||||
}.first
|
||||
XCTAssertTrue(event != nil)
|
||||
@@ -161,8 +164,8 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
|
||||
|
||||
//
|
||||
try artist.delete(db)
|
||||
XCTAssertEqual(delegate.committedEvents.count, 1)
|
||||
let event = delegate.committedEvents.filter {
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 1)
|
||||
let event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Delete, tableName: "artists", rowId: artist.id!)
|
||||
}.first
|
||||
XCTAssertTrue(event != nil)
|
||||
@@ -184,20 +187,88 @@ class DatabaseTransactionDelegateTests: GRDBTestCase {
|
||||
|
||||
//
|
||||
try artist.delete(db)
|
||||
XCTAssertEqual(delegate.committedEvents.count, 3)
|
||||
let artistEvent = delegate.committedEvents.filter {
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 3)
|
||||
let artistEvent = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Delete, tableName: "artists", rowId: artist.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artistEvent != nil)
|
||||
let artwork1Event = delegate.committedEvents.filter {
|
||||
let artwork1Event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Delete, tableName: "artworks", rowId: artwork1.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artwork1Event != nil)
|
||||
let artwork2Event = delegate.committedEvents.filter {
|
||||
let artwork2Event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Delete, tableName: "artworks", rowId: artwork2.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artwork2Event != nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testTransactionCommit() {
|
||||
let delegate = TransactionDelegate()
|
||||
assertNoError {
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
let artwork1 = Artwork(title: "Cloud")
|
||||
let artwork2 = Artwork(title: "Ema (Nude on a Staircase)")
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
db.transactionDelegate = delegate
|
||||
|
||||
try artist.save(db)
|
||||
artwork1.artistId = artist.id
|
||||
artwork2.artistId = artist.id
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
try artwork1.save(db)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
try artwork2.save(db)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
return .Commit
|
||||
}
|
||||
XCTAssertEqual(delegate.lastTransactionCompletion, Database.TransactionCompletion.Commit)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 3)
|
||||
let artistEvent = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Insert, tableName: "artists", rowId: artist.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artistEvent != nil)
|
||||
let artwork1Event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Insert, tableName: "artworks", rowId: artwork1.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artwork1Event != nil)
|
||||
let artwork2Event = delegate.lastCommittedEvents.filter {
|
||||
self.match(event: $0, kind: .Insert, tableName: "artworks", rowId: artwork2.id!)
|
||||
}.first
|
||||
XCTAssertTrue(artwork2Event != nil)
|
||||
}
|
||||
}
|
||||
|
||||
func testTransactionRollback() {
|
||||
let delegate = TransactionDelegate()
|
||||
assertNoError {
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
let artwork1 = Artwork(title: "Cloud")
|
||||
let artwork2 = Artwork(title: "Ema (Nude on a Staircase)")
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
db.transactionDelegate = delegate
|
||||
|
||||
try artist.save(db)
|
||||
artwork1.artistId = artist.id
|
||||
artwork2.artistId = artist.id
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
try artwork1.save(db)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
try artwork2.save(db)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
|
||||
return .Rollback
|
||||
}
|
||||
XCTAssertEqual(delegate.lastTransactionCompletion, Database.TransactionCompletion.Rollback)
|
||||
XCTAssertEqual(delegate.lastCommittedEvents.count, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -243,9 +243,9 @@ public final class Database {
|
||||
if let transactionDelegate = transactionDelegate {
|
||||
switch pendingTransactionCompletion {
|
||||
case .Commit:
|
||||
transactionDelegate.databaseDidCommit()
|
||||
transactionDelegate.databaseDidCommit(self)
|
||||
case .Rollback:
|
||||
transactionDelegate.databaseDidRollback()
|
||||
transactionDelegate.databaseDidRollback(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,9 +258,9 @@ public final class Database {
|
||||
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
|
||||
|
||||
sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
let db = unsafeBitCast(dbPointer, Database.self)
|
||||
|
||||
guard let transactionDelegate = database.transactionDelegate else {
|
||||
guard let transactionDelegate = db.transactionDelegate else {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -269,18 +269,18 @@ public final class Database {
|
||||
databaseName: String.fromCString(databaseName)!,
|
||||
tableName: String.fromCString(tableName)!, // Tests have shown that pointers are reused for various table names: we can't use those pointers as a cache key.
|
||||
rowID: rowID)
|
||||
transactionDelegate.databaseDidChangeWithEvent(event)
|
||||
transactionDelegate.database(db, didChangeWithEvent: event)
|
||||
}, dbPointer)
|
||||
|
||||
sqlite3_commit_hook(sqliteConnection, { dbPointer in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
database.pendingTransactionCompletion = .Commit
|
||||
let db = unsafeBitCast(dbPointer, Database.self)
|
||||
db.pendingTransactionCompletion = .Commit
|
||||
|
||||
guard let transactionDelegate = database.transactionDelegate else {
|
||||
guard let transactionDelegate = db.transactionDelegate else {
|
||||
return 0 // commit
|
||||
}
|
||||
|
||||
if transactionDelegate.databaseShouldCommit() {
|
||||
if transactionDelegate.databaseShouldCommit(db) {
|
||||
return 0 // commit
|
||||
}
|
||||
|
||||
@@ -288,8 +288,8 @@ public final class Database {
|
||||
}, dbPointer)
|
||||
|
||||
sqlite3_rollback_hook(sqliteConnection, { dbPointer in
|
||||
let database = unsafeBitCast(dbPointer, Database.self)
|
||||
database.pendingTransactionCompletion = .Rollback
|
||||
let db = unsafeBitCast(dbPointer, Database.self)
|
||||
db.pendingTransactionCompletion = .Rollback
|
||||
}, dbPointer)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,64 @@
|
||||
/// EXPERIMENTAL
|
||||
/**
|
||||
The transaction delegate of a database is notified of all changes and
|
||||
transactions committed or rollbacked on a database.
|
||||
*/
|
||||
public protocol DatabaseTransactionDelegate: class {
|
||||
// Notify a database change (insert, update or delete):
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent)
|
||||
|
||||
// An opportunity to rollback database changes:
|
||||
func databaseShouldCommit() -> Bool
|
||||
/**
|
||||
Notifies a database change (insert, update, or delete).
|
||||
|
||||
// Database changes have been committed:
|
||||
func databaseDidCommit()
|
||||
The change is pending until the end of the current transaction, notified to
|
||||
databaseShouldCommit(_), databaseDidCommit(_) and databaseDidRollback(_).
|
||||
|
||||
// Database changes have been rollbacked:
|
||||
func databaseDidRollback()
|
||||
This method is called on the database queue.
|
||||
|
||||
**WARNING**: this method must not change the database.
|
||||
|
||||
- parameter db: A Database.
|
||||
- parameter event: A database event.
|
||||
*/
|
||||
func database(db: Database, didChangeWithEvent event: DatabaseEvent)
|
||||
|
||||
/**
|
||||
When a transaction is about to be committed, the transaction delegate has an
|
||||
opportunity to rollback pending changes.
|
||||
|
||||
This method is called on the database queue.
|
||||
|
||||
**WARNING**: this method must not change the database.
|
||||
|
||||
- parameter db: A Database.
|
||||
- returns: Whether the transaction should be committed.
|
||||
*/
|
||||
func databaseShouldCommit(db: Database) -> Bool
|
||||
|
||||
/**
|
||||
Database changes have been committed.
|
||||
|
||||
This method is called on the database queue. It can change the database.
|
||||
|
||||
- parameter db: A Database.
|
||||
*/
|
||||
func databaseDidCommit(db: Database)
|
||||
|
||||
|
||||
/**
|
||||
Database changes have been rollbacked.
|
||||
|
||||
This method is called on the database queue. It can change the database.
|
||||
|
||||
- parameter db: A Database.
|
||||
*/
|
||||
func databaseDidRollback(db: Database)
|
||||
}
|
||||
|
||||
public extension DatabaseTransactionDelegate {
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent) { }
|
||||
func databaseShouldCommit() -> Bool { return true }
|
||||
func databaseDidCommit() { }
|
||||
func databaseDidRollback() { }
|
||||
func database(db: Database, didChangeWithEvent event: DatabaseEvent) { }
|
||||
func databaseShouldCommit(db: Database) -> Bool { return true }
|
||||
func databaseDidCommit(db: Database) { }
|
||||
func databaseDidRollback(db: Database) { }
|
||||
}
|
||||
|
||||
/// EXPERIMENTAL
|
||||
public struct DatabaseEvent {
|
||||
public enum Kind: Int32 {
|
||||
case Insert = 18 // SQLITE_INSERT
|
||||
|
||||
@@ -132,6 +132,7 @@ To fiddle with the library, open the `GRDB.xcworkspace` workspace: it contains a
|
||||
- [Transactions](#transactions)
|
||||
- [Prepared Statements](#prepared-statements)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Transaction Delegate](#transaction-delegate)
|
||||
- [Concurrency](#concurrency)
|
||||
- [Migrations](#migrations)
|
||||
- [Records](#records)
|
||||
@@ -848,6 +849,70 @@ do {
|
||||
See [SQLite Result Codes](https://www.sqlite.org/rescode.html).
|
||||
|
||||
|
||||
#### Transaction Delegate
|
||||
|
||||
**The DatabaseTransactionDelegate protocol lets you observe database changes:**
|
||||
|
||||
```swift
|
||||
public protocol DatabaseTransactionDelegate: class {
|
||||
// Notifies a database change (insert, update, or delete):
|
||||
func database(db: Database, didChangeWithEvent event: DatabaseEvent)
|
||||
|
||||
// An opportunity to rollback pending changes.
|
||||
func databaseShouldCommit(db: Database) -> Bool
|
||||
|
||||
// Database changes have been committed.
|
||||
func databaseDidCommit(db: Database)
|
||||
|
||||
// Database changes have been rollbacked.
|
||||
func databaseDidRollback(db: Database)
|
||||
}
|
||||
```
|
||||
|
||||
Those four callbacks are invoked on the database queue.
|
||||
|
||||
The notified changes are not applied until the transaction eventually get committed or rollbacked.
|
||||
|
||||
As a sample code, let's write an object that uses NSNotificationCenter to notify, on the main thread, of modified database tables. Your view controllers can listen to those notifications and update their views accordingly.
|
||||
|
||||
```swift
|
||||
class TableChangeNotifier : DatabaseTransactionDelegate {
|
||||
var changedTableNames: Set<String> = []
|
||||
|
||||
func database(db: Database, didChangeWithEvent event: DatabaseEvent) {
|
||||
// Wait until transaction ends
|
||||
changedTableNames.insert(event.tableName)
|
||||
}
|
||||
|
||||
func databaseDidCommit(db: Database) {
|
||||
// Notify changes
|
||||
let changedTableNames = self.changedTableNames
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
NSNotificationCenter.defaultCenter().postNotificationName(
|
||||
"DatabaseDidChangeNotification",
|
||||
object: self,
|
||||
userInfo: ["ChangedTableNames": changedTableNames])
|
||||
}
|
||||
|
||||
// Wait until next transaction
|
||||
self.changedTableNames = []
|
||||
}
|
||||
|
||||
func databaseDidRollback(db: Database) {
|
||||
// Wait until next transaction
|
||||
self.changedTableNames = []
|
||||
}
|
||||
}
|
||||
|
||||
// Activate notifications:
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
let notifier = TableChangeNotifier()
|
||||
dbQueue.inDatabase { db in
|
||||
db.transactionDelegate = notifier
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Concurrency
|
||||
|
||||
**When your application has a single DatabaseQueue connected to the database file, it has no concurrency issue.** That is because all your database statements are executed in a single serial dispatch queue that is connected alone to the database.
|
||||
|
||||
Reference in new issue
Block a user