From ead2b1336284c522af3a469fe892a6ded115b3e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 16:29:31 +0100 Subject: [PATCH] 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 :-) --- GRDB/Core/DatabaseRegion.swift | 7 +++ GRDB/Core/DatabaseWriter.swift | 7 ++- GRDB/Core/ValueObservation.swift | 10 +++- ...rvationDatabaseValueConvertibleTests.swift | 60 ++++++++++++++++++- 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 6227a23a1..eeaad7a68 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -148,6 +148,13 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { public mutating func formUnion(_ other: DatabaseRegion) { self = union(other) } + + func ignoring(_ tables: Set) -> 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 { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c4b6b3966..08094a82c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -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: TransactionObserver { - private let region: DatabaseRegion +/// Internal for testability +/* private */ class ValueObserver: TransactionObserver { + /* private */ let region: DatabaseRegion // Internal for testability private var reducer: Reducer private let fetch: (Database, Reducer) -> Future private let notificationQueue: DispatchQueue? diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index 5ad671ebe..427dbfe8a 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -484,7 +484,15 @@ public struct ValueObservation { 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 } diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 1f5e11562..50edc1864 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -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("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> + 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"]]) + } }