TransactionObserver.playground

This commit is contained in:
Gwendal Roué committed 2016-01-15 20:32:41 +01:00
1 parent ca2fa83e80
commit fae1cdae93
4 files changed
+91

No files matched your search

+3
View File
@@ -10,6 +10,9 @@
<FileRef
location = "group:Record.playground">
</FileRef>
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
</Group>
<FileRef
location = "group:GRDB.xcodeproj">
@@ -0,0 +1,78 @@
//: Playground - noun: a place where people can play
import GRDB
// Create the databsae
var configuration = Configuration()
let dbQueue = DatabaseQueue(configuration: configuration) // Memory database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL " +
")")
}
migrator.registerMigration("createPets") { db in
try db.execute("CREATE TABLE pets (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT, " +
"ownerId INTEGER NOT NULL REFERENCES persons(id) ON DELETE CASCADE" +
")")
}
try! migrator.migrate(dbQueue)
/// TableChangeObserver prints on the main thread the changes database tables.
class TableChangeObserver : NSObject, TransactionObserverType {
private var changedTableNames: Set<String> = []
func databaseDidChangeWithEvent(event: DatabaseEvent) {
changedTableNames.insert(event.tableName)
}
func databaseWillCommit() throws {
}
func databaseDidCommit(db: Database) {
print("Changed table(s): \(changedTableNames.joinWithSeparator(", "))")
changedTableNames = []
}
func databaseDidRollback(db: Database) {
changedTableNames = []
}
}
// Register observer
dbQueue.inDatabase { db in
db.addTransactionObserver(TableChangeObserver())
}
//
print("-- Changes 1")
try! dbQueue.inDatabase { db in
let arthurId = try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"]).insertedRowID
let barbaraId = try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"]).insertedRowID
let pet = try db.execute("INSERT INTO pets (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"]).insertedRowID
}
print("-- Changes 2")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES ('Arthur')").insertedRowID
try db.execute("INSERT INTO persons (name) VALUES ('Barbara')").insertedRowID
return .Rollback
}
print("-- Changes 3")
try dbQueue.inDatabase { db in
try db.execute("DELETE FROM persons")
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx'>
<timeline fileName='timeline.xctimeline'/>
</playground>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>