Optimize value observation for views that feed from a single table

By removing views from the observed database region, we allow the "single-table observation optimization" to kick in.

Thank you @foxware00 for revealing this opportunity in #441 :-)
This commit is contained in:
Gwendal Roué committed 2018-11-17 16:29:31 +01:00
1 parent 0ea9a1ce0d
commit ead2b13362
4 files changed
+77 -7

No files matched your search

+7
View File
@@ -148,6 +148,13 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
public mutating func formUnion(_ other: DatabaseRegion) {
self = union(other)
}
func ignoring(_ tables: Set<String>) -> DatabaseRegion {
guard tables.isEmpty == false else { return self }
guard let tableRegions = tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter { tables.contains($0.key) == false }
return DatabaseRegion(tableRegions: filteredRegions)
}
}
extension DatabaseRegion {
+4 -3
View File
@@ -238,7 +238,7 @@ extension DatabaseWriter {
startValue = try reducer.value(observation.fetchInitial(db))
}
}
// Start observing the database
let valueObserver = try ValueObserver(
region: observation.observedRegion(db),
@@ -297,8 +297,9 @@ extension ValueObservation where Reducer: ValueReducer {
/// Support for ValueObservation.
/// See DatabaseWriter.add(observation:onError:onChange:)
private class ValueObserver<Reducer: ValueReducer>: TransactionObserver {
private let region: DatabaseRegion
/// Internal for testability
/* private */ class ValueObserver<Reducer: ValueReducer>: TransactionObserver {
/* private */ let region: DatabaseRegion // Internal for testability
private var reducer: Reducer
private let fetch: (Database, Reducer) -> Future<Reducer.Fetched>
private let notificationQueue: DispatchQueue?
+9 -1
View File
@@ -484,7 +484,15 @@ public struct ValueObservation<Reducer> {
tracking region: @escaping (Database) throws -> DatabaseRegion,
reducer: Reducer)
{
self.observedRegion = region
self.observedRegion = { db in
// Remove views from the observed region.
//
// We can do it because we are only interested in modifications in
// actual tables. And we want to do it because we have a fast path
// for simple regions that span a single table.
let views = try db.schema().names(ofType: .view)
return try region(db).ignoring(views)
}
self.reducer = reducer
}
@@ -1,15 +1,15 @@
import XCTest
#if GRDBCIPHER
import GRDBCipher
@testable import GRDBCipher
#elseif GRDBCUSTOMSQLITE
import GRDBCustomSQLite
@testable import GRDBCustomSQLite
#else
#if SWIFT_PACKAGE
import CSQLite
#else
import SQLite3
#endif
import GRDB
@testable import GRDB
#endif
private struct Name: DatabaseValueConvertible {
@@ -143,4 +143,58 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
["foo", nil],
[nil]])
}
func testViewOptimization() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute("""
CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
CREATE VIEW v AS SELECT * FROM t
""")
}
var results: [[Name]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
// Test that view v is included in the request region
let request = SQLRequest<Name>("SELECT name FROM v ORDER BY id")
try dbQueue.inDatabase { db in
let region = try request.databaseRegion(db)
XCTAssertEqual(region.description, "t(id,name),v(id,name)")
}
// Test that view v is not included in the observed region.
// This optimization helps observation of views that feed from a
// single table.
var observation = ValueObservation.trackingAll(request)
observation.extent = .databaseLifetime
let transactionObserver = try observation.start(in: dbQueue) { names in
results.append(names)
notificationExpectation.fulfill()
}
let valueObserver = transactionObserver as! ValueObserver<ValueReducers.Values<Name>>
XCTAssertEqual(valueObserver.region.description, "t(id,name)")
// Test view observation
try dbQueue.inDatabase { db in
try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute("UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute("DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute("DELETE FROM t WHERE id = 1") // -1
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [
[],
["foo"],
["foo", "bar"],
["bar"]])
}
}