diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f169304d..1104279ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - The `DatabaseMigrator.eraseDatabaseOnSchemaChange` option no longer fails when migrations depend on database configuration. +**New** + +- [#622](https://github.com/groue/GRDB.swift/pull/622): Allow observation of FTS4 virtual tables + ## 4.4.0 diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 793c82f4b..9a739e2ff 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -184,27 +184,17 @@ extension DatabaseRegion { return true } - if tableRegions.count == 1 { - // Fast path when the region contains a single table. - // - // We can apply the precondition: due to the filtering of events - // performed in observes(eventsOfKind:), the event argument is - // guaranteed to be about the fetched table. We thus only have to - // check for rowIds. - assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check in debug mode - let tableRegion = tableRegions[tableRegions.startIndex].value - return tableRegion.contains(rowID: event.rowID) - } else { - // Slow path when several tables are observed. - guard let tableRegion = tableRegions[event.tableName] else { - // Shouldn't happen if the precondition is met. - fatalError(""" - precondition failure: event was not filtered out in observes(eventsOfKind:) \ - by region.isModified(byEventsOfKind:) - """) - } - return tableRegion.contains(rowID: event.rowID) + guard let tableRegion = tableRegions[event.tableName] else { + // FTS4 (and maybe other virtual tables) perform unadvertised + // changes. For example, an "INSERT INTO document ..." statement + // advertises an insertion in the `document` table, but the + // actual change events happen in the `document_content` shadow + // table. When such a non-advertised event happens, assume that + // the region is modified. + // See https://github.com/groue/GRDB.swift/issues/620 + return true } + return tableRegion.contains(rowID: event.rowID) } } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index ce21a3d5c..f3a72b2a9 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -190,7 +190,7 @@ final class TruncateOptimizationBlocker: StatementAuthorizer { } } -fileprivate struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible { +private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible { let rawValue: Int32 init(rawValue: Int32) { self.rawValue = rawValue diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 13cd61a2e..a2cf3dac3 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -283,7 +283,11 @@ class DatabaseObservationBroker { // observation will only be notified of individual events that // match one of the observed kinds. - return (observation, DatabaseEventPredicate.matching(observedKinds)) + return ( + observation, + DatabaseEventPredicate.matching( + observedKinds: observedKinds, + advertisedKinds: eventKinds)) } } @@ -1312,15 +1316,28 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { enum DatabaseEventPredicate { // Yes filter case `true` - // Only events that match one of those kinds - case matching([DatabaseEventKind]) + // Only events that match observedKinds + case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind]) func evaluate(_ event: DatabaseEventProtocol) -> Bool { switch self { case .true: return true - case .matching(let kinds): - return kinds.contains { event.matchesKind($0) } + case let .matching(observedKinds: observedKinds, advertisedKinds: advertisedKinds): + if observedKinds.contains(where: { event.matchesKind($0) }) { + return true + } + if !advertisedKinds.contains(where: { event.matchesKind($0) }) { + // FTS4 (and maybe other virtual tables) perform unadvertised + // changes. For example, an "INSERT INTO document ..." statement + // advertises an insertion in the `document` table, but the + // actual change events happen in the `document_content` shadow + // table. When such a non-advertised event happens, assume that + // the event has to be notified. + // See https://github.com/groue/GRDB.swift/issues/620 + return true + } + return false } } } diff --git a/Makefile b/Makefile index 2886ba49c..8b6138f85 100644 --- a/Makefile +++ b/Makefile @@ -49,10 +49,17 @@ endif TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with `instruments -s devices` -ifeq ($(XCODEVERSION),11.0) +ifeq ($(XCODEVERSION),11.1) MAX_SWIFT_VERSION = 5.1 MIN_SWIFT_VERSION = 4.2 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone Xs,OS=13.0" + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.1" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.1" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" +else ifeq ($(XCODEVERSION),11.0) + MAX_SWIFT_VERSION = 5.1 + MIN_SWIFT_VERSION = 4.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.0" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.0" MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index be03c5d80..4e3c8dc58 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -154,4 +154,114 @@ class ValueObservationRowTests: GRDBTestCase { ["id":2, "name":"bar"], nil]) } + + func testFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(virtualTable: "ft_documents", using: FTS4()) + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["content":"foo"]]]) + } + } + + func testSynchronizedFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "documents") { t in + t.column("id", .integer).primaryKey() + t.column("content", .text) + } + try db.create(virtualTable: "ft_documents", using: FTS4()) { t in + t.synchronize(withTable: "documents") + t.column("content") + } + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: "SELECT * FROM ft_documents") + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["content":"foo"]]]) + } + } + + func testJoinedFTS4Observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "document") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(virtualTable: "ft_document", using: FTS4()) { t in + t.column("content") + } + } + + var rows: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let request = SQLRequest(sql: """ + SELECT document.* FROM document + JOIN ft_document ON ft_document.rowid = document.id + WHERE ft_document MATCH 'foo' + """) + let observation = ValueObservation.tracking(value: request.fetchAll) + let observer = observation.start( + in: dbQueue, + onError: { error in + XCTFail("unexpected error: \(error)") + }, + onChange: { + rows.append($0) + notificationExpectation.fulfill() + }) + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1]) + try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"]) + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(rows, [[], [["id":1]]]) + } + } }