Remove update hook when no observer is active. Allow truncate optimization when deletions are not observed.

This commit is contained in:
Gwendal Roué committed 2018-01-14 19:34:11 +01:00
1 parent 19e75576a8
commit 33e8d0875d
3 files changed
+61 -45

No files matched your search

-12
View File
@@ -489,10 +489,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
/// If true, the statement needs support from TruncateOptimizationBlocker
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
@@ -516,7 +512,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
try super.init(
database: database,
@@ -524,7 +519,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
statementEnd: statementEnd,
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
@@ -539,10 +533,6 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
reset()
database.updateStatementWillExecute(self)
if needsTruncateOptimizationPreventionDuringExecution {
database.authorizer = TruncateOptimizationBlocker()
}
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
@@ -565,12 +555,10 @@ public final class UpdateStatement : Statement, AuthorizedStatement {
continue
case SQLITE_DONE:
database.authorizer = nil
try database.updateStatementDidExecute(self)
return
case let code:
database.authorizer = nil
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
+10 -11
View File
@@ -32,9 +32,6 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// savepoint statement.
var transactionEffect: UpdateStatement.TransactionEffect?
/// True if statement may trigger the truncate optimization
var needsTruncateOptimizationPreventionDuringExecution = false
private var isDropStatement = false
func authorize(
@@ -84,12 +81,17 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
// Deletions from sqlite_master and sqlite_temp_master are not like
// other deletions: the update hook does not notify them, and they
// are prevented when the truncate optimization is disabled.
// Let's authorize such deletions by returning SQLITE_OK:
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
// Now we prevent the truncate optimization so that transaction
// observers are notified of individual row deletions.
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See also TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
@@ -159,11 +161,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
/// which makes transaction observers unable to observe individual deletions
/// when user runs `DELETE FROM t` statements.
//
/// Warning: to perform well, this authorizer requires that:
//
/// - It is used during statement execution, not during statement compilation.
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(
_ actionCode: Int32,
+51 -22
View File
@@ -165,11 +165,23 @@ extension Database {
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
unowned var database: Database
var savepointStack = SavepointStack()
var transactionState: TransactionState = .none
var transactionObservations: [TransactionObservation] = []
var statementObservations: [StatementObservation] = []
private unowned var database: Database
private var savepointStack = SavepointStack()
private var transactionState: TransactionState = .none
private var transactionObservations: [TransactionObservation] = []
private var statementObservations: [StatementObservation] = [] {
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
}
private var observesDatabaseChanges: Bool = false {
didSet {
if observesDatabaseChanges == oldValue { return }
if observesDatabaseChanges {
installUpdateHook()
} else {
uninstallUpdateHook()
}
}
}
init(_ database: Database) {
self.database = database
@@ -179,16 +191,10 @@ class DatabaseObservationBroker {
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
if transactionObservations.count == 1 {
installUpdateHook()
}
}
func remove(transactionObserver: TransactionObserver) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
@@ -214,9 +220,14 @@ class DatabaseObservationBroker {
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let databaseEventKinds = statement.databaseEventKinds
let eventKinds = statement.databaseEventKinds
switch databaseEventKinds.count {
// If any observer observes row deletions, we'll have to disable
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that observers are notified.
var observesRowDeletion = false
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
@@ -229,11 +240,17 @@ class DatabaseObservationBroker {
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.flatMap { observation in
guard databaseEventKinds.contains(where: observation.observes) else {
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
if case .delete = eventKind {
observesRowDeletion = true
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
@@ -247,22 +264,37 @@ class DatabaseObservationBroker {
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.flatMap { observation in
let observedKinds = databaseEventKinds.filter(observation.observes)
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (observation, DatabaseEventPredicate.matching(observedKinds))
}
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
} else {
database.authorizer = nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Wait for next statement
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.currentDatabaseObservationBroker = nil
database.authorizer = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
@@ -284,10 +316,11 @@ class DatabaseObservationBroker {
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Wait for next statement
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.currentDatabaseObservationBroker = nil
database.authorizer = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -455,10 +488,6 @@ class DatabaseObservationBroker {
private func databaseDidEndTransaction() {
transactionObservations = transactionObservations.filter { $0.isObserving }
if transactionObservations.isEmpty {
uninstallUpdateHook()
}
for observation in transactionObservations {
observation.isDisabledUntilNextTransaction = false
}