mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-25 04:07:47 +00:00
Detailed database changes observation
This commit is contained in:
1 parent
a07c09b3d4
commit
6a466fcb12
7 files changed
+303
-41
No files matched your search
+95
-21
@@ -83,6 +83,7 @@ public final class Database {
|
||||
|
||||
// Transaction observers
|
||||
private var transactionObservers = [WeakTransactionObserver]()
|
||||
private var statementObservers = [WeakTransactionObserver]() // subset of transactionObservers, set in updateStatementWillExecute
|
||||
private var transactionState: TransactionState = .WaitForTransactionCompletion
|
||||
private var savepointStack = SavePointStack()
|
||||
|
||||
@@ -503,7 +504,8 @@ extension Database {
|
||||
database: self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
invalidatesDatabaseSchemaCache: observer.invalidatesDatabaseSchemaCache,
|
||||
savepointAction: observer.savepointAction)
|
||||
savepointAction: observer.savepointAction,
|
||||
databaseEventKinds: observer.databaseEventKinds)
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
@@ -1012,19 +1014,32 @@ public struct PrimaryKey {
|
||||
// =========================================================================
|
||||
// MARK: - StatementCompilationObserver
|
||||
|
||||
/// TODO
|
||||
public enum DatabaseEventKind {
|
||||
/// TODO
|
||||
case Insert(tableName: String)
|
||||
/// TODO
|
||||
case Delete(tableName: String)
|
||||
/// TODO
|
||||
case Update(tableName: String, columnNames: Set<String>)
|
||||
}
|
||||
|
||||
/// A class that gathers information about a statement during its compilation.
|
||||
final class StatementCompilationObserver {
|
||||
let database: Database
|
||||
|
||||
// The list of tables queried by a statement
|
||||
var sourceTables: Set<String> = []
|
||||
/// A dictionary [tablename: Set<columnName>] of accessed columns
|
||||
var readTables: [String: Set<String>] = [:]
|
||||
|
||||
// True if a statement alter the schema in a way that required schema cache
|
||||
// invalidation. Adding a column to a table does invalidate the schema
|
||||
// cache, but not adding a table.
|
||||
/// What this statement does to the database
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. Adding a column to a table does invalidate the schema
|
||||
/// cache, but not adding a table.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
// Not nil if a statement is a BEGIN/RELEASE/ROLLBACK savepoint statement.
|
||||
/// Not nil if a statement is a BEGIN/RELEASE/ROLLBACK savepoint statement.
|
||||
var savepointAction: (name: String, action: SavepointActionKind)?
|
||||
|
||||
init(_ database: Database) {
|
||||
@@ -1041,7 +1056,16 @@ final class StatementCompilationObserver {
|
||||
observer.invalidatesDatabaseSchemaCache = true
|
||||
case SQLITE_READ:
|
||||
let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self)
|
||||
observer.sourceTables.insert(String.fromCString(CString1)!)
|
||||
observer.insertRead(tableName: String.fromCString(CString1)!, columnName: String.fromCString(CString2)!)
|
||||
case SQLITE_INSERT:
|
||||
let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self)
|
||||
observer.databaseEventKinds.append(.Insert(tableName: String.fromCString(CString1)!))
|
||||
case SQLITE_DELETE:
|
||||
let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self)
|
||||
observer.databaseEventKinds.append(.Delete(tableName: String.fromCString(CString1)!))
|
||||
case SQLITE_UPDATE:
|
||||
let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self)
|
||||
observer.insertUpdateEventKind(tableName: String.fromCString(CString1)!, columnName: String.fromCString(CString2)!)
|
||||
case SQLITE_SAVEPOINT:
|
||||
let observer = unsafeBitCast(observerPointer, StatementCompilationObserver.self)
|
||||
let name = String.fromCString(CString2)!
|
||||
@@ -1056,11 +1080,32 @@ final class StatementCompilationObserver {
|
||||
|
||||
// Call this method between two calls to calling sqlite3_prepare_v2()
|
||||
func reset() {
|
||||
sourceTables = []
|
||||
readTables = [:]
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
savepointAction = nil
|
||||
}
|
||||
|
||||
func insertRead(tableName tableName: String, columnName: String) {
|
||||
if readTables[tableName] != nil {
|
||||
readTables[tableName]!.insert(columnName)
|
||||
} else {
|
||||
readTables[tableName] = [columnName]
|
||||
}
|
||||
}
|
||||
|
||||
func insertUpdateEventKind(tableName tableName: String, columnName: String) {
|
||||
for (index, eventKind) in databaseEventKinds.enumerate() {
|
||||
if case .Update(let t, let columnNames) = eventKind where t == tableName {
|
||||
var columnNames = columnNames
|
||||
columnNames.insert(columnName)
|
||||
databaseEventKinds[index] = .Update(tableName: tableName, columnNames: columnNames)
|
||||
return
|
||||
}
|
||||
}
|
||||
databaseEventKinds.append(.Update(tableName: tableName, columnNames: [columnName]))
|
||||
}
|
||||
|
||||
func stop() {
|
||||
sqlite3_set_authorizer(database.sqliteConnection, nil, nil)
|
||||
}
|
||||
@@ -1313,12 +1358,24 @@ extension Database {
|
||||
/// An INSERT statement will pass, but not DROP TABLE (which invalidates the
|
||||
/// database cache), or RELEASE SAVEPOINT (which alters the savepoint stack)
|
||||
static func preconditionValidSelectStatement(sql sql: String, observer: StatementCompilationObserver) {
|
||||
GRDBPrecondition(!observer.invalidatesDatabaseSchemaCache, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(observer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(observer.savepointAction == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(observer.databaseEventKinds.isEmpty, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
}
|
||||
|
||||
func updateStatementWillExecute(statement: UpdateStatement) {
|
||||
let databaseEventKinds = statement.databaseEventKinds
|
||||
statementObservers = transactionObservers.filter { weakObserver in
|
||||
guard let observer = weakObserver.observer else { return false }
|
||||
return databaseEventKinds.indexOf({ observer.observes($0) }) != nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Some failed statements interest transaction observers.
|
||||
func updateStatementDidFail(statement: UpdateStatement) throws {
|
||||
// Wait for next statement
|
||||
statementObservers = []
|
||||
|
||||
// Reset transactionState before didRollback eventually executes
|
||||
// other statements.
|
||||
let transactionState = self.transactionState
|
||||
@@ -1345,6 +1402,9 @@ extension Database {
|
||||
/// Some succeeded statements invalidate the database cache, others interest
|
||||
/// transaction observers, and others modify the savepoint stack.
|
||||
func updateStatementDidExecute(statement: UpdateStatement) {
|
||||
// Wait for next statement
|
||||
statementObservers = []
|
||||
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
@@ -1358,8 +1418,8 @@ extension Database {
|
||||
if savepointStack.isEmpty {
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
for event in eventsBuffer {
|
||||
for (event, transactionObservers) in eventsBuffer {
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
event.send(to: observer)
|
||||
}
|
||||
}
|
||||
@@ -1388,36 +1448,47 @@ extension Database {
|
||||
private func willCommit() throws {
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
for event in eventsBuffer {
|
||||
var observersForCommit: [TransactionObserverType] = transactionObservers.flatMap({ $0.observer })
|
||||
for (event, transactionObservers) in eventsBuffer {
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
event.send(to: observer)
|
||||
if !observersForCommit.contains({ $0 === observer }) {
|
||||
observersForCommit.append(observer)
|
||||
}
|
||||
}
|
||||
}
|
||||
for observer in observersForCommit {
|
||||
try observer.databaseWillCommit()
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Transaction hook
|
||||
private func willChangeWithEvent(event: DatabasePreUpdateEvent)
|
||||
{
|
||||
private func willChangeWithEvent(event: DatabasePreUpdateEvent) {
|
||||
// Don't notify all transactionObservers about the database event.
|
||||
// Only notify "statement observers" set in updateStatementWillExecute.
|
||||
if savepointStack.isEmpty {
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
for observer in statementObservers.flatMap({ $0.observer }) {
|
||||
observer.databaseWillChangeWithEvent(event)
|
||||
}
|
||||
} else {
|
||||
savepointStack.eventsBuffer.append(event.copy())
|
||||
// Buffer both event and the observers that should be notified of the event.
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), transactionObservers: statementObservers))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Transaction hook
|
||||
private func didChangeWithEvent(event: DatabaseEvent) {
|
||||
// Don't notify all transactionObservers about the database event.
|
||||
// Only notify "statement observers" set in updateStatementWillExecute.
|
||||
if savepointStack.isEmpty {
|
||||
for observer in transactionObservers.flatMap({ $0.observer }) {
|
||||
for observer in statementObservers.flatMap({ $0.observer }) {
|
||||
observer.databaseDidChangeWithEvent(event)
|
||||
}
|
||||
} else {
|
||||
savepointStack.eventsBuffer.append(event.copy())
|
||||
// Buffer both event and the observers that should be notified of the event.
|
||||
savepointStack.eventsBuffer.append((event: event.copy(), transactionObservers: statementObservers))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1531,6 +1602,9 @@ private enum TransactionState {
|
||||
/// Adopting types must be a class.
|
||||
public protocol TransactionObserverType : class {
|
||||
|
||||
/// TODO
|
||||
func observes(eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Notifies a database change (insert, update, or delete).
|
||||
///
|
||||
/// The change is pending until the end of the current transaction, notified
|
||||
@@ -1969,7 +2043,7 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
|
||||
/// rollbacked.
|
||||
class SavePointStack {
|
||||
/// The buffered events. See Database.didChangeWithEvent()
|
||||
var eventsBuffer: [DatabaseEventType] = []
|
||||
var eventsBuffer: [(event: DatabaseEventType, transactionObservers: [WeakTransactionObserver])] = []
|
||||
|
||||
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
|
||||
/// Indexes let us drop rollbacked events from the event buffer.
|
||||
|
||||
@@ -198,16 +198,15 @@ public class Statement {
|
||||
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
/// The tables this statement feeds on.
|
||||
var sourceTables: Set<String>
|
||||
/// A dictionary [tablename: Set<columnName>] of accessed columns
|
||||
private(set) var readTables: [String: Set<String>]
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
self.sourceTables = []
|
||||
|
||||
self.readTables = [:]
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
|
||||
self.sourceTables = observer.sourceTables
|
||||
self.readTables = observer.readTables
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
@@ -343,20 +342,24 @@ public final class UpdateStatement : Statement {
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache: Bool
|
||||
private(set) var savepointAction: (name: String, action: SavepointActionKind)?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, savepointAction: (name: String, action: SavepointActionKind)?) {
|
||||
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, savepointAction: (name: String, action: SavepointActionKind)?, databaseEventKinds: [DatabaseEventKind]) {
|
||||
self.invalidatesDatabaseSchemaCache = invalidatesDatabaseSchemaCache
|
||||
self.savepointAction = savepointAction
|
||||
self.databaseEventKinds = databaseEventKinds
|
||||
super.init(database: database, sqliteStatement: sqliteStatement)
|
||||
}
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.databaseEventKinds = []
|
||||
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
|
||||
self.savepointAction = observer.savepointAction
|
||||
self.databaseEventKinds = observer.databaseEventKinds
|
||||
}
|
||||
|
||||
/// Executes the SQL query.
|
||||
@@ -370,6 +373,8 @@ public final class UpdateStatement : Statement {
|
||||
try! prepareWithArguments(arguments)
|
||||
try! reset()
|
||||
|
||||
database.updateStatementWillExecute(self)
|
||||
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE, SQLITE_ROW:
|
||||
// When SQLITE_ROW, the statement did return a row. That's
|
||||
|
||||
@@ -104,7 +104,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
|
||||
if let checkForChanges = checkForChanges {
|
||||
let observer = FetchedRecordsObserver(
|
||||
observedTables: statement.sourceTables,
|
||||
observedTables: statement.readTables,
|
||||
checkForChanges: checkForChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
@@ -254,7 +254,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
|
||||
let statement = try! self.request.selectStatement(db)
|
||||
let observer = FetchedRecordsObserver(
|
||||
observedTables: statement.sourceTables,
|
||||
observedTables: statement.readTables,
|
||||
checkForChanges: checkForChanges)
|
||||
self.observer = observer
|
||||
if let initialItems = initialItems {
|
||||
@@ -306,7 +306,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
|
||||
let statement = try! self.request.selectStatement(db)
|
||||
let observer = FetchedRecordsObserver(
|
||||
observedTables: statement.sourceTables,
|
||||
observedTables: statement.readTables,
|
||||
checkForChanges: checkForChanges)
|
||||
self.observer = observer
|
||||
if let initialItems = initialItems {
|
||||
@@ -607,13 +607,13 @@ private class FetchedChangesController<Record: RowConvertible, T> {
|
||||
/// monitor changes to its fetched records.
|
||||
private final class FetchedRecordsObserver<Record: RowConvertible> : TransactionObserverType {
|
||||
var isValid: Bool
|
||||
let observedTables: Set<String>
|
||||
let observedTables: [String: Set<String>]
|
||||
var needsComputeChanges: Bool
|
||||
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
|
||||
let queue: dispatch_queue_t // protects items
|
||||
var checkForChanges: (FetchedRecordsObserver<Record>) -> ()
|
||||
|
||||
init(observedTables: Set<String>, checkForChanges: (FetchedRecordsObserver<Record>) -> ()) {
|
||||
init(observedTables: [String: Set<String>], checkForChanges: (FetchedRecordsObserver<Record>) -> ()) {
|
||||
self.isValid = true
|
||||
self.items = nil
|
||||
self.observedTables = observedTables
|
||||
@@ -626,6 +626,22 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
isValid = false
|
||||
}
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func observes(eventKind: DatabaseEventKind) -> Bool {
|
||||
switch eventKind {
|
||||
case .Delete(let tableName):
|
||||
return observedTables[tableName] != nil
|
||||
case .Insert(let tableName):
|
||||
return observedTables[tableName] != nil
|
||||
case .Update(let tableName, let updatedColumnNames):
|
||||
if let observedColumnNames = observedTables[tableName] {
|
||||
return !updatedColumnNames.isDisjointWith(observedColumnNames)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent) { }
|
||||
@@ -633,9 +649,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseDidChangeWithEvent(event: DatabaseEvent) {
|
||||
if !needsComputeChanges && observedTables.contains(event.tableName) {
|
||||
needsComputeChanges = true
|
||||
}
|
||||
needsComputeChanges = true
|
||||
}
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
|
||||
@@ -9,16 +9,66 @@ import XCTest
|
||||
|
||||
class StatementInformationTests : GRDBTestCase {
|
||||
|
||||
func testSelectStatementSourceTables() {
|
||||
func testSelectStatement() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE foo (id INTEGER)")
|
||||
try db.execute("CREATE TABLE bar (id INTEGER, fooId INTEGER)")
|
||||
let statement = try db.selectStatement("SELECT * FROM FOO JOIN BAR ON fooId = foo.id")
|
||||
XCTAssertTrue(statement.sourceTables.count == 2)
|
||||
XCTAssertTrue(statement.sourceTables.contains("foo"))
|
||||
XCTAssertTrue(statement.sourceTables.contains("bar"))
|
||||
XCTAssertEqual(statement.readTables, ["foo": Set(["id"]), "bar": Set(["id", "fooId"])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUpdateStatement() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
|
||||
let statement = try db.updateStatement("UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .Update(let tableName, let columnNames) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
XCTAssertEqual(columnNames, Set(["bar", "baz"]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testInsertStatement() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
|
||||
let statement = try db.updateStatement("INSERT INTO foo (id, bar) VALUES (1, 'bar')")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .Insert(let tableName) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDeleteStatement() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)")
|
||||
let statement = try db.updateStatement("DELETE FROM foo")
|
||||
XCTAssertFalse(statement.invalidatesDatabaseSchemaCache)
|
||||
XCTAssertEqual(statement.databaseEventKinds.count, 1)
|
||||
guard case .Delete(let tableName) = statement.databaseEventKinds[0] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(tableName, "foo")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ private class TransactionObserver : TransactionObserverType {
|
||||
#endif
|
||||
}
|
||||
|
||||
func observes(eventKind: DatabaseEventKind) -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
var allRecordedPreUpdateEvents: [DatabasePreUpdateEvent] = []
|
||||
func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent) {
|
||||
|
||||
@@ -11,6 +11,10 @@ private class TransactionObserver : TransactionObserverType {
|
||||
var lastCommittedEvents: [DatabaseEvent] = []
|
||||
var events: [DatabaseEvent] = []
|
||||
|
||||
func observes(eventKind: DatabaseEventKind) -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
var preUpdateEvents: [DatabasePreUpdateEvent] = []
|
||||
func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent) {
|
||||
|
||||
@@ -12,9 +12,11 @@ private class TransactionObserver : TransactionObserverType {
|
||||
var events: [DatabaseEvent] = []
|
||||
var commitError: ErrorType?
|
||||
var deinitBlock: (() -> ())?
|
||||
var filterEvents: ((DatabaseEventKind) -> Bool)?
|
||||
|
||||
init(deinitBlock: (() -> ())? = nil) {
|
||||
init(deinitBlock: (() -> ())? = nil, filterEvents: ((DatabaseEventKind) -> Bool)? = nil) {
|
||||
self.deinitBlock = deinitBlock
|
||||
self.filterEvents = filterEvents
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -38,6 +40,14 @@ private class TransactionObserver : TransactionObserverType {
|
||||
#endif
|
||||
}
|
||||
|
||||
func observes(eventKind: DatabaseEventKind) -> Bool {
|
||||
if let filterEvents = filterEvents {
|
||||
return filterEvents(eventKind)
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
var willChangeCount: Int = 0
|
||||
var lastCommittedPreUpdateEvents: [DatabasePreUpdateEvent] = []
|
||||
@@ -1163,5 +1173,106 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Filtered database events
|
||||
|
||||
func testFilterDatabaseEvents() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
do {
|
||||
let observer = TransactionObserver(filterEvents: { event in return false })
|
||||
dbQueue.addTransactionObserver(observer)
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
try artist.insert(db)
|
||||
try artist.update(db)
|
||||
try artist.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 0)
|
||||
}
|
||||
|
||||
do {
|
||||
let observer = TransactionObserver(filterEvents: { event in return true })
|
||||
dbQueue.addTransactionObserver(observer)
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
try artist.insert(db)
|
||||
try artist.update(db)
|
||||
try artist.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 3)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 3)
|
||||
}
|
||||
|
||||
do {
|
||||
let observer = TransactionObserver(filterEvents: { event in
|
||||
switch event {
|
||||
case .Insert:
|
||||
return true
|
||||
case .Update:
|
||||
return false
|
||||
case .Delete:
|
||||
return false
|
||||
}
|
||||
})
|
||||
dbQueue.addTransactionObserver(observer)
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
try artist.insert(db)
|
||||
try artist.update(db)
|
||||
try artist.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 1)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let observer = TransactionObserver(filterEvents: { event in
|
||||
switch event {
|
||||
case .Insert:
|
||||
return true
|
||||
case .Update:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
})
|
||||
dbQueue.addTransactionObserver(observer)
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
let artist = Artist(name: "Gerhard Richter")
|
||||
try artist.insert(db)
|
||||
try artist.update(db)
|
||||
try artist.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didChangeCount, 2)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user