From 49de0e0f4921a57486a23d8ce145ef8efb27a50c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 16 Nov 2018 08:48:25 +0100 Subject: [PATCH 001/118] Call sqlite3_close() even if opening failed Thanks to https://github.com/feistydog/FeistyDB/commit/6859f622797480656f8897c2db5e620e6a98c858 --- GRDB/Core/Database.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2a2a96714..88316ca5e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -202,6 +202,16 @@ extension Database { var sqliteConnection: SQLiteConnection? = nil let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil) guard code == SQLITE_OK else { + // https://www.sqlite.org/c3ref/open.html + // > Whether or not an error occurs when it is opened, resources + // > associated with the database connection handle should be + // > released by passing it to sqlite3_close() when it is no + // > longer required. + // + // https://www.sqlite.org/c3ref/close.html + // > Calling sqlite3_close() or sqlite3_close_v2() with a NULL + // > pointer argument is a harmless no-op. + sqlite3_close(sqliteConnection) throw DatabaseError(resultCode: code) } if let sqliteConnection = sqliteConnection { From 1108ba4bf2460a221912876d716266a652953401 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 16 Nov 2018 09:07:52 +0100 Subject: [PATCH 002/118] DatabaseError gets a default message, derived from its resultCode --- GRDB/Core/DatabaseError.swift | 20 ++++++++++++++------ Tests/GRDBTests/DatabaseErrorTests.swift | 11 +++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 778e3e8ef..2299c70a7 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -141,20 +141,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible // CustomStringConvertible extension ResultCode { - /// :nodoc: - public var description: String { + var errorString: String? { // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + return String(cString: sqlite3_errstr(rawValue)) #else if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + return String(cString: sqlite3_errstr(rawValue)) } else { - return "\(rawValue)" + return nil } #endif } + + /// :nodoc: + public var description: String { + if let errorString = errorString { + return "\(rawValue) (\(errorString))" + } else { + return "\(rawValue)" + } + } } /// DatabaseError wraps an SQLite error. @@ -199,7 +207,7 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { /// Creates a Database Error public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { self.extendedResultCode = resultCode - self.message = message + self.message = message ?? resultCode.errorString self.sql = sql self.arguments = arguments } diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 986cfa109..82d4139bf 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -9,6 +9,17 @@ import XCTest class DatabaseErrorTests: GRDBTestCase { + func testDatabaseErrorMessage() { + // Error messages are not always available + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { + // We don't test for actual messages, since they may depend on SQLite version + XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR) + XCTAssertNotNil(DatabaseError().message) + XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message) + XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message) + } + } + func testDatabaseErrorInTransaction() throws { let dbQueue = try makeDatabaseQueue() do { From d3fd838c6cc6cbf84ecd478fd3b492ea9835fb81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 12:46:01 +0100 Subject: [PATCH 003/118] DatabaseRegion cleanup and documentation Goal: improve understanding of observation performance. Context: https://github.com/groue/GRDB.swift/issues/441 --- GRDB/Core/DatabaseRegion.swift | 51 +++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 613796e9d..6227a23a1 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -47,7 +47,10 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Returns whether the region is empty. public var isEmpty: Bool { - guard let tableRegions = tableRegions else { return false } + guard let tableRegions = tableRegions else { + // full database + return false + } return tableRegions.isEmpty } @@ -122,7 +125,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { guard let otherTableRegions = other.tableRegions else { return .fullDatabase } var tableRegionsUnion: [String: TableRegion] = [:] - let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key })) + let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys)) for table in tableNames { let tableRegion = tableRegions[table] let otherTableRegion = otherTableRegions[table] @@ -154,7 +157,7 @@ extension DatabaseRegion { /// Returns whether the content in the region would be impacted if the /// database were modified by an event of this kind. public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool { - return !intersection(eventKind.modifiedRegion).isEmpty + return intersection(eventKind.modifiedRegion).isEmpty == false } /// Returns whether the content in the region is impacted by this event. @@ -164,31 +167,27 @@ extension DatabaseRegion { /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { guard let tableRegions = tableRegions else { + // Full database: all changes are impactful return true } - switch tableRegions.count { - case 1: - // The precondition applies here: + if tableRegions.count == 1 { + // Fast path when the region contains a single table. // - // The region contains a single table. 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 - guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else { - return true - } - return rowIds.contains(event.rowID) - default: + // 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:)") } - guard let rowIds = tableRegion.rowIds else { - return true - } - return rowIds.contains(event.rowID) + return tableRegion.contains(rowID: event.rowID) } } } @@ -201,8 +200,8 @@ extension DatabaseRegion { case (nil, nil): return true case (let ltableRegions?, let rtableRegions?): - let ltableNames = Set(ltableRegions.map { $0.key }) - let rtableNames = Set(rtableRegions.map { $0.key }) + let ltableNames = Set(ltableRegions.keys) + let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } @@ -295,6 +294,14 @@ private struct TableRegion: Equatable { return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion) } + + @inline(__always) + func contains(rowID: Int64) -> Bool { + guard let rowIds = rowIds else { + return true + } + return rowIds.contains(rowID) + } } // MARK: - DatabaseRegionConvertible From b9ab74cb1daa6345e819f641246faaec46f95d72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 13:25:55 +0100 Subject: [PATCH 004/118] ValueObservation: support region arrays (address #441) --- GRDB/Core/ValueObservation.swift | 110 +++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index e777c96f6..5ad671ebe 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -526,6 +526,48 @@ public struct ValueObservation { _ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation + { + return ValueObservation.tracking(regions, reducer: reducer) + } + + /// Returs a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count + /// }) + /// let observation = ValueObservation.tracking([Player.all()], reducer: reducer) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + reducer: Reducer) + -> ValueObservation { return ValueObservation(tracking: union(regions), reducer: reducer) } @@ -573,6 +615,39 @@ extension ValueObservation where Reducer == Void { _ regions: DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) -> ValueObservation> + { + return ValueObservation.tracking(regions, fetch: fetch) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// [Player.all()], + /// fetch: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> { return ValueObservation>( tracking: union(regions), @@ -610,6 +685,41 @@ extension ValueObservation where Reducer == Void { fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation> where Value: Equatable + { + return ValueObservation.tracking(regions, fetchDistinct: fetch) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. Consecutive equal values + /// are filtered out. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// [Player.all()], + /// fetchDistinct: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + where Value: Equatable { return ValueObservation>( tracking: union(regions), From b6eb5ab39999a832116701f6aa6134bf4391eae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 13:26:14 +0100 Subject: [PATCH 005/118] ValueObservation: tests for region arrays --- Tests/GRDBTests/ValueObservationFetchTests.swift | 12 ++++++++++++ Tests/GRDBTests/ValueObservationReducerTests.swift | 11 +++++++++++ 2 files changed, 23 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index de6aa1dbe..bd1856eb1 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -13,6 +13,18 @@ import XCTest #endif class ValueObservationFetchTests: GRDBTestCase { + func testRegionsAPI() { + // single region + _ = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + _ = ValueObservation.tracking(DatabaseRegion(), fetchDistinct: { _ in 0 }) + // variadic + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetch: { _ in }) + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetchDistinct: { _ in 0 }) + // array + _ = ValueObservation.tracking([DatabaseRegion()], fetch: { _ in }) + _ = ValueObservation.tracking([DatabaseRegion()], fetchDistinct: { _ in 0 }) + } + func testFetch() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 393da3e7c..3f5e7b32b 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -13,6 +13,17 @@ import XCTest #endif class ValueObservationReducerTests: GRDBTestCase { + func testRegionsAPI() { + let reducer = AnyValueReducer(fetch: { _ in }, value: { }) + + // single region + _ = ValueObservation.tracking(DatabaseRegion(), reducer: reducer) + // variadic + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), reducer: reducer) + // array + _ = ValueObservation.tracking([DatabaseRegion()], reducer: reducer) + } + func testReducer() throws { // We need something to change let dbQueue = try makeDatabaseQueue() From 60358ba0c04ee3f16195c439f93370d5cecdb09c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 13:43:03 +0100 Subject: [PATCH 006/118] CHANGELOG --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d952cd80..d56da1702 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,22 @@ Release Notes ============= +## Next Version + +### New + +- ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (address [#441](https://github.com/groue/GRDB.swift/issues/441)) + + ```swift + let regions: [DatabaseRegionConvertible] = [Player.all(), Team.all()] + ValueObservation.tracking(regions, fetch: { db in ... }) + ValueObservation.tracking(regions, fetchDistinct: { db in ... }) + ValueObservation.tracking(regions, reducer: ...) + ``` + +- ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. + + ## 3.5.0 Released November 2, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.4.0...v3.5.0) From d868b7e1cef3c9477c4fd82ba1a0955dd1ff75e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 14:12:03 +0100 Subject: [PATCH 007/118] Test ValueObservation with database queue and pool --- .../ValueObservationFetchTests.swift | 108 +-- .../ValueObservationReducerTests.swift | 523 +++++++------- .../ValueObservationSchedulingTests.swift | 652 ++++++++++-------- 3 files changed, 672 insertions(+), 611 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index bd1856eb1..e2df19a40 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -26,66 +26,66 @@ class ValueObservationFetchTests: GRDBTestCase { } func testFetch() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 1, 2]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - try dbQueue.write { - try $0.execute("UPDATE t SET id = id") - } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 1, 2]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testFetchWithUniquing() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetchDistinct: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetchDistinct: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 2]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - try dbQueue.write { - try $0.execute("UPDATE t SET id = id") - } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } } diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 3f5e7b32b..ff26d3026 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -25,289 +25,310 @@ class ValueObservationReducerTests: GRDBTestCase { } func testReducer() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var fetchCount = 0 - var reduceCount = 0 - var errors: [Error] = [] - var changes: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - // A reducer which tracks its progress - var dropNext = false // if true, reducer drops next value - let reducer = AnyValueReducer( - fetch: { db -> Int in - fetchCount += 1 - // test for database access - return try Int.fetchOne(db, "SELECT COUNT(*) FROM t")! + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer proceess + var fetchCount = 0 + var reduceCount = 0 + var errors: [Error] = [] + var changes: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // A reducer which tracks its progress + var dropNext = false // if true, reducer drops next value + let reducer = AnyValueReducer( + fetch: { db -> Int in + fetchCount += 1 + // test for database access + return try Int.fetchOne(db, "SELECT COUNT(*) FROM t")! }, - value: { count -> String? in - reduceCount += 1 - if dropNext { - // test that reducer can drop values - dropNext = false - return nil + value: { count -> String? in + reduceCount += 1 + if dropNext { + // test that reducer can drop values + dropNext = false + return nil + } + // test that the fetched type and the notified type can be different + return count.description + }) + + // Create an observation + let request = SQLRequest("SELECT * FROM t") + var observation = ValueObservation.tracking(request, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start( + in: dbWriter, + onError: { + errors.append($0) + notificationExpectation.fulfill() + }, + onChange: { + changes.append($0) + notificationExpectation.fulfill() + }) + + + // Test that default config synchronously notifies initial value + XCTAssertEqual(fetchCount, 1) + XCTAssertEqual(reduceCount, 1) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0"]) + + try dbWriter.writeWithoutTransaction { db in + // Test a 1st notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } + + // Test an untracked transaction + try db.inTransaction { + try db.execute("CREATE TABLE ignored(a)") + return .commit + } + + // Test a dropped transaction + dropNext = true + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } + + // Test a rollbacked transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .rollback + } + + // Test a 2nd notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit } - // test that the fetched type and the notified type can be different - return count.description - }) - - // Create an observation - let request = SQLRequest("SELECT * FROM t") - var observation = ValueObservation.tracking(request, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start( - in: dbQueue, - onError: { - errors.append($0) - notificationExpectation.fulfill() - }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() - }) - - - // Test that default config synchronously notifies initial value - XCTAssertEqual(fetchCount, 1) - XCTAssertEqual(reduceCount, 1) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0"]) - - try dbQueue.inDatabase { db in - // Test a 1st notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit } - // Test an untracked transaction - try db.inTransaction { - try db.execute("CREATE TABLE ignored(a)") - return .commit - } - - // Test a dropped transaction - dropNext = true - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test a rollbacked transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .rollback - } - - // Test a 2nd notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(fetchCount, 4) + XCTAssertEqual(reduceCount, 4) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0", "1", "5"]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(fetchCount, 4) - XCTAssertEqual(reduceCount, 4) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0", "1", "5"]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testInitialError() throws { - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { _ in fatalError() }) - - // Create an observation - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - - // Start observation - do { - let dbQueue = try makeDatabaseQueue() - _ = try observation.start( - in: dbQueue, - onError: { _ in fatalError() }, - onChange: { _ in fatalError() }) - XCTFail("Expected error") - } catch is TestError { + func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { _ in fatalError() }) + + // Create an observation + let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + + // Start observation + do { + _ = try observation.start( + in: dbWriter, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch is TestError { + } } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testSuccessThenErrorThenSuccess() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var errors: [Error] = [] - var changes: [Void] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - // A reducer which throws an error is requested to do so - var nextError: Error? = nil // If not null, reducer throws an error - let reducer = AnyValueReducer( - fetch: { _ -> Void in - if let error = nextError { - nextError = nil - throw error - } + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer proceess + var errors: [Error] = [] + var changes: [Void] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // A reducer which throws an error is requested to do so + var nextError: Error? = nil // If not null, reducer throws an error + let reducer = AnyValueReducer( + fetch: { _ -> Void in + if let error = nextError { + nextError = nil + throw error + } }, - value: { $0 }) - - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start( - in: dbQueue, - onError: { - errors.append($0) - notificationExpectation.fulfill() + value: { $0 }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start( + in: dbWriter, + onError: { + errors.append($0) + notificationExpectation.fulfill() }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() + onChange: { + changes.append($0) + notificationExpectation.fulfill() }) - - struct TestError: Error { } - nextError = TestError() - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") + + struct TestError: Error { } + nextError = TestError() + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errors.count, 1) + XCTAssertEqual(changes.count, 2) } - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errors.count, 1) - XCTAssertEqual(changes.count, 2) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testReadMeReducer() throws { - // Test for the reducer documented in the main README - - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // The reducer - var count = 0 - let reducer = AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - count += 1 - return count - }) - - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // Test for the reducer documented in the main README + + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer proceess + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // The reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1, 2]) } - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1, 2]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testMapValueReducer() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // The base reducer - var count = 0 - let reducer = AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - count += 1 - return count - }) - - // The mapped reducer - let mapReducer = reducer.map { count -> String? in - if count % 2 == 0 { return nil } - return "\(count)" + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer proceess + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // The base reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // The mapped reducer + let mapReducer = reducer.map { count -> String? in + if count % 2 == 0 { return nil } + return "\(count)" + } + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: mapReducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "3"]) } - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: mapReducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.inDatabase { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["1", "3"]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testValueObservationMap() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - struct T: TableRecord { } - var observation = ValueObservation - .trackingCount(T.all()) - .map { "\($0)" } - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + struct T: TableRecord { } + var observation = ValueObservation + .trackingCount(T.all()) + .map { "\($0)" } + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["0", "1", "2"]) } - try dbQueue.inDatabase { - try $0.execute("INSERT INTO t DEFAULT VALUES") - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["0", "1", "2"]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } } diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index 18593a024..03c89f55e 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -14,364 +14,404 @@ import XCTest class ValueObservationSchedulingTests: GRDBTestCase { func testMainQueueObservationStartedFromMainQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - } - // .mainQueue scheduling: initial value MUST be synchronously - // dispatched when observation is started from the main queue - XCTAssertEqual(counts, [0]) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + + _ = try observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + // .mainQueue scheduling: initial value MUST be synchronously + // dispatched when observation is started from the main queue + XCTAssertEqual(counts, [0]) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } @available(OSX 10.10, *) // DispatchQueue qos func testMainQueueObservationStartedFromAnotherQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + + DispatchQueue.global(qos: .default).async { + _ = try! observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + + try! dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testMainQueueError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var nextError: Error? = nil // If not null, reducer throws an error + let reducer = AnyValueReducer( + fetch: { _ -> Void in + if let error = nextError { + nextError = nil + throw error + } + }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + _ = try observation.start( + in: dbWriter, + onError: { error in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + errorCount += 1 + notificationExpectation.fulfill() + }, + onChange: { _ in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + notificationExpectation.fulfill() + }) + + struct TestError: Error { } + nextError = TestError() + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - - DispatchQueue.global(qos: .default).async { - _ = try! observation.start(in: dbQueue) { count in + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testCustomQueueStartImmediately() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: true) + + _ = try observation.start(in: dbWriter) { count in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) counts.append(count) notificationExpectation.fulfill() } - try! dbQueue.write { + try dbWriter.write { try $0.execute("INSERT INTO t DEFAULT VALUES") } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - - func testMainQueueError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var nextError: Error? = nil // If not null, reducer throws an error - let reducer = AnyValueReducer( - fetch: { _ -> Void in - if let error = nextError { - nextError = nil - throw error - } - }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - _ = try observation.start( - in: dbQueue, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - notificationExpectation.fulfill() - }) - - struct TestError: Error { } - nextError = TestError() - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - - func testCustomQueueStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: true) - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testCustomQueueDontStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: false) - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: false) + + _ = try observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testCustomQueueError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: false) - - _ = try observation.start( - in: dbQueue, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: false) + + _ = try observation.start( + in: dbWriter, + onError: { error in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + errorCount += 1 + notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + onChange: { _ in fatalError() }) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeStartImmediatelyFromMainQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: true) - - _ = try observation.start(in: dbQueue) { count in - if counts.isEmpty { - // require main queue on first element - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - } - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - - func testUnsafeStartImmediatelyFromCustomQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: true) - - queue.async { - _ = try! observation.start(in: dbQueue) { count in + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: true) + + _ = try observation.start(in: dbWriter) { count in if counts.isEmpty { - // require custom queue on first notification + // require main queue on first element XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) } counts.append(count) notificationExpectation.fulfill() } - try! dbQueue.write { + try dbWriter.write { try $0.execute("INSERT INTO t DEFAULT VALUES") } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testUnsafeStartImmediatelyFromCustomQueue() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: true) + + queue.async { + _ = try! observation.start(in: dbWriter) { count in + if counts.isEmpty { + // require custom queue on first notification + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + } + counts.append(count) + notificationExpectation.fulfill() + } + + try! dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeDontStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: false) - - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: false) + + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: false) - - _ = try observation.start( - in: dbQueue, - onError: { error in - errorCount += 1 - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: false) + + _ = try observation.start( + in: dbWriter, + onError: { error in + errorCount += 1 + notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + onChange: { _ in fatalError() }) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } } From 5efbbe9f0c59308f7b9a4a1b30a0115ed8c964f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 14:13:15 +0100 Subject: [PATCH 008/118] Typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d56da1702..f57e685e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Release Notes ### New -- ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (address [#441](https://github.com/groue/GRDB.swift/issues/441)) +- ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): ```swift let regions: [DatabaseRegionConvertible] = [Player.all(), Team.all()] From 3b7801efffb251992b5b030ff5e839427fe17627 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 15:38:55 +0100 Subject: [PATCH 009/118] Cache full database schema --- GRDB/Core/Database+Schema.swift | 39 ++++++++++++++++++----- GRDB/Core/DatabaseSchemaCache.swift | 9 ++++++ GRDB/Core/StatementAuthorizer.swift | 7 ++-- Tests/GRDBTests/DatabaseRegionTests.swift | 2 +- 4 files changed, 46 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 1257be73b..3b7597546 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -26,7 +26,7 @@ extension Database { /// Returns whether a table exists. public func tableExists(_ name: String) throws -> Bool { - return try exists(type: "table", name: name) + return try exists(type: .table, name: name) } /// Returns whether a table is an internal SQLite table. @@ -53,26 +53,26 @@ extension Database { /// Returns whether a view exists. public func viewExists(_ name: String) throws -> Bool { - return try exists(type: "view", name: name) + return try exists(type: .view, name: name) } /// Returns whether a trigger exists. public func triggerExists(_ name: String) throws -> Bool { - return try exists(type: "trigger", name: name) + return try exists(type: .trigger, name: name) } - private func exists(type: String, name: String) throws -> Bool { + private func exists(type: SchemaObjectType, name: String) throws -> Bool { // SQlite identifiers are case-insensitive, case-preserving: // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html let name = name.lowercased() if try makeSelectStatement("SELECT 1 FROM sqlite_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type, name]) + .makeCursor(arguments: [type.rawValue, name]) .isEmpty() == false { return true } if try makeSelectStatement("SELECT 1 FROM sqlite_temp_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type, name]) + .makeCursor(arguments: [type.rawValue, name]) .isEmpty() == false { return true } @@ -291,7 +291,12 @@ extension Database { } func schema() throws -> SchemaInfo { - return try SchemaInfo(self) + if let schemaInfo = schemaCache.schemaInfo { + return schemaInfo + } + let schemaInfo = try SchemaInfo(self) + schemaCache.schemaInfo = schemaInfo + return schemaInfo } } @@ -585,15 +590,33 @@ public struct ForeignKeyInfo { } } +enum SchemaObjectType: String { + case view + case table + case trigger +} + struct SchemaInfo: Equatable { var objects: [SchemaKey: String?] init(_ db: Database) throws { objects = try Dictionary(uniqueKeysWithValues: Row - .fetchAll(db, "SELECT type, name, tbl_name, sql FROM sqlite_master") + .fetchAll(db, """ + SELECT type, name, tbl_name, sql FROM sqlite_master + UNION + SELECT type, name, tbl_name, sql FROM sqlite_temp_master + """) .map { row in (SchemaKey(row: row), row["sql"]) }) } + func names(ofType type: SchemaObjectType) -> Set { + return objects.keys.reduce(into: []) { (set, key) in + if key.type == type.rawValue { + set.insert(key.name) + } + } + } + struct SchemaKey: Codable, Hashable, FetchableRecord { var type: String var name: String diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 237db0b97..6ef445ebc 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -2,6 +2,8 @@ protocol DatabaseSchemaCache { mutating func clear() + var schemaInfo: SchemaInfo? { get set } + func canonicalTableName(_ table: String) -> String? mutating func set(canonicalTableName: String, forTable table: String) @@ -20,6 +22,7 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { + var schemaInfo: SchemaInfo? private var canonicalTableNames: [String: String] = [:] private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] @@ -32,6 +35,7 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { columns = [:] indexes = [:] foreignKeys = [:] + schemaInfo = nil } func canonicalTableName(_ table: String) -> String? { @@ -79,6 +83,11 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { func clear() { } + var schemaInfo: SchemaInfo? { + get { return nil } + set { } + } + func canonicalTableName(_ table: String) -> String? { return nil } func set(canonicalTableName: String, forTable table: String) { } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 7a2750e43..ef6064578 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -55,12 +55,15 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { return SQLITE_OK case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, - SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER: + SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER: isDropStatement = true return SQLITE_OK case SQLITE_DETACH, SQLITE_ALTER_TABLE, - SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX: + SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW: invalidatesDatabaseSchemaCache = true return SQLITE_OK diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 47744ced9..80bd6630e 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -606,7 +606,7 @@ class DatabaseRegionTests : GRDBTestCase { try dbQueue.inDatabase { db in do { let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)") - XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) + XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) try statement.execute() } do { From 0ea9a1ce0d206e735bccf668a3be42f1bfcaab05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 15:59:09 +0100 Subject: [PATCH 010/118] Use SchemaInfo more --- GRDB/Core/Database+Schema.swift | 47 +++++++++++------------------ GRDB/Core/DatabaseSchemaCache.swift | 16 ---------- GRDB/Core/StatementAuthorizer.swift | 11 +++---- 3 files changed, 22 insertions(+), 52 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3b7597546..651682b81 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -65,18 +65,9 @@ extension Database { // SQlite identifiers are case-insensitive, case-preserving: // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html let name = name.lowercased() - - if try makeSelectStatement("SELECT 1 FROM sqlite_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type.rawValue, name]) - .isEmpty() == false - { return true } - - if try makeSelectStatement("SELECT 1 FROM sqlite_temp_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type.rawValue, name]) - .isEmpty() == false - { return true } - - return false + return try schema() + .names(ofType: type) + .contains { $0.lowercased() == name } } /// The primary key for table named `tableName`. @@ -271,23 +262,10 @@ extension Database { /// Returns the actual name of the database table func canonicalTableName(_ tableName: String) throws -> String { - if let canonicalTableName = schemaCache.canonicalTableName(tableName) { - return canonicalTableName - } - - guard let canonicalTableName = try String.fetchOne(self, """ - SELECT name FROM ( - SELECT name, type FROM sqlite_master - UNION - SELECT name, type FROM sqlite_temp_master) - WHERE type = 'table' AND LOWER(name) = ? - """, arguments: [tableName.lowercased()]) - else { + guard let name = try schema().canonicalName(tableName, ofType: .table) else { throw DatabaseError(message: "no such table: \(tableName)") } - - schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName) - return canonicalTableName + return name } func schema() throws -> SchemaInfo { @@ -591,13 +569,14 @@ public struct ForeignKeyInfo { } enum SchemaObjectType: String { - case view + case index case table case trigger + case view } struct SchemaInfo: Equatable { - var objects: [SchemaKey: String?] + private var objects: [SchemaKey: String?] init(_ db: Database) throws { objects = try Dictionary(uniqueKeysWithValues: Row @@ -609,6 +588,7 @@ struct SchemaInfo: Equatable { .map { row in (SchemaKey(row: row), row["sql"]) }) } + /// All names for a given type func names(ofType type: SchemaObjectType) -> Set { return objects.keys.reduce(into: []) { (set, key) in if key.type == type.rawValue { @@ -617,6 +597,15 @@ struct SchemaInfo: Equatable { } } + /// Returns the canonical name of the object: + /// + /// try db.execute("CREATE TABLE FooBar (...)") + /// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar" + func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? { + let name = name.lowercased() + return objects.keys.first { $0.name.lowercased() == name }?.name + } + struct SchemaKey: Codable, Hashable, FetchableRecord { var type: String var name: String diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 6ef445ebc..4f29cef90 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -4,9 +4,6 @@ protocol DatabaseSchemaCache { var schemaInfo: SchemaInfo? { get set } - func canonicalTableName(_ table: String) -> String? - mutating func set(canonicalTableName: String, forTable table: String) - func primaryKey(_ table: String) -> PrimaryKeyInfo? mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) @@ -23,14 +20,12 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { var schemaInfo: SchemaInfo? - private var canonicalTableNames: [String: String] = [:] private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] private var foreignKeys: [String: [ForeignKeyInfo]] = [:] mutating func clear() { - canonicalTableNames = [:] primaryKeys = [:] columns = [:] indexes = [:] @@ -38,14 +33,6 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { schemaInfo = nil } - func canonicalTableName(_ table: String) -> String? { - return canonicalTableNames[table] - } - - mutating func set(canonicalTableName: String, forTable table: String) { - canonicalTableNames[table] = table - } - func primaryKey(_ table: String) -> PrimaryKeyInfo? { return primaryKeys[table] } @@ -88,9 +75,6 @@ struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { set { } } - func canonicalTableName(_ table: String) -> String? { return nil } - func set(canonicalTableName: String, forTable table: String) { } - func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index ef6064578..0c9957878 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -49,17 +49,14 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, - SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX: + SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER: isDropStatement = true invalidatesDatabaseSchemaCache = true return SQLITE_OK - case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, - SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER: - isDropStatement = true - return SQLITE_OK - - case SQLITE_DETACH, SQLITE_ALTER_TABLE, + case SQLITE_ALTER_TABLE, SQLITE_DETACH, SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE, SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE, SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW, 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 011/118] 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"]]) + } } From f80f59cc382eb46d00fc6a828b55f16819ee1538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 18:41:46 +0100 Subject: [PATCH 012/118] Tweaks to demo app --- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 15 ++++++--------- .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 2 +- DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift | 8 +++++++- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index dd39c279e..54ebb3e45 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -8,11 +8,10 @@ struct AppDatabase { /// Creates a fully initialized database at path static func openDatabase(atPath path: String) throws -> DatabaseQueue { // Connect to the database - // See https://github.com/groue/GRDB.swift/#database-connections - dbQueue = try DatabaseQueue(path: path) + // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + let dbQueue = try DatabaseQueue(path: path) - // Use DatabaseMigrator to define the database schema - // See https://github.com/groue/GRDB.swift/#migrations + // Define the database schema try migrator.migrate(dbQueue) return dbQueue @@ -20,8 +19,7 @@ struct AppDatabase { /// The DatabaseMigrator that defines the database schema. /// - /// This migrator is exposed so that migrations can be tested. - // See https://github.com/groue/GRDB.swift/#migrations + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations static var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() @@ -29,11 +27,10 @@ struct AppDatabase { // Create a table // See https://github.com/groue/GRDB.swift#create-tables try db.create(table: "player") { t in - // An integer primary key auto-generates unique IDs - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") // Sort player names in a localized case insensitive fashion by default - // See https://github.com/groue/GRDB.swift/#unicode + // See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) t.column("score", .integer).notNull() diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index e88354b7a..672c383c0 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -20,7 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) // Be a nice iOS citizen, and don't consume too much memory - // See https://github.com/groue/GRDB.swift/#memory-management + // See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management dbQueue.setupMemoryManagement(in: application) } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 66094ceab..3d22cef06 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,13 +1,17 @@ import GRDB +// A plain Player struct struct Player { - var id: Int64? // Auto-incremented database ids are Int64 + // Prefer Int64 for auto-incremented database ids + var id: Int64? var name: String var score: Int } // MARK: - Persistence +// Turn Player into a Codable Record. +// See https://github.com/groue/GRDB.swift/blob/master/README.md#records extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Add ColumnExpression to Codable's CodingKeys so that we can use them // as database columns. @@ -26,6 +30,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { // MARK: - Database access +// Define some useful player requests. +// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests extension Player { static func orderedByName() -> QueryInterfaceRequest { return Player.order(CodingKeys.name) From 466a1ad4d5b71dab642e40c1b9c5c8aa8da6d455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 18:56:29 +0100 Subject: [PATCH 013/118] Database.reindex(collation:) --- GRDB/QueryInterface/TableDefinition.swift | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index ca8b231df..41fefb83c 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -216,6 +216,30 @@ extension Database { public func drop(index name: String) throws { try execute("DROP INDEX \(name.quotedDatabaseIdentifier)") } + + /// Delete and recreate from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// See https://www.sqlite.org/lang_reindex.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func reindex(collation: Database.CollationName) throws { + try execute("REINDEX \(collation.rawValue)") + } + + /// Delete and recreate from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// See https://www.sqlite.org/lang_reindex.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func reindex(collation: DatabaseCollation) throws { + try reindex(collation: Database.CollationName(collation.name)) + } } /// The TableDefinition class lets you define table columns and constraints. From 53adad16e50b48575e8292008b7386c582a20aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 18:56:38 +0100 Subject: [PATCH 014/118] Tests for Database.reindex(collation:) --- Tests/GRDBTests/TableDefinitionTests.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index b25ec0aa2..b85dda3f1 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -573,4 +573,15 @@ class TableDefinitionTests: GRDBTestCase { XCTAssertTrue(try db.indexes(on: "test").isEmpty) } } + + func testReindex() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.reindex(collation: .binary) + assertEqualSQL(lastSQLQuery, "REINDEX BINARY") + + try db.reindex(collation: .localizedCompare) + assertEqualSQL(lastSQLQuery, "REINDEX swiftLocalizedCompare") + } + } } From 064f1005e5372ea7989fae70fbdb82ad66cdfdff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 19:12:20 +0100 Subject: [PATCH 015/118] CHANGELOG --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f57e685e3..135c6e435 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ Release Notes ### New +- [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex + + ```swift + // Deletes and recreates from scratch all indices that use this + // locale-dependent collation. + try db.reindex(collation: .localizedCompare) + ``` + - ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): ```swift @@ -16,6 +24,15 @@ Release Notes - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. +### API diff + +```diff + extension Database { ++ func reindex(collation: Database.CollationName) throws ++ func reindex(collation: DatabaseCollation) throws + } +``` + ## 3.5.0 From 55c8d350b83de0bd164f6e35550fbc0792a67b71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Nov 2018 19:17:25 +0100 Subject: [PATCH 016/118] CHANGELOG --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 135c6e435..b3168af77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,25 @@ Release Notes + func reindex(collation: Database.CollationName) throws + func reindex(collation: DatabaseCollation) throws } + + struct ValueObservation { ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ reducer: Reducer) ++ -> ValueObservation + } + + extension ValueObservation where Reducer == Void { ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ fetch: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ fetchDistinct fetch: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ where Value: Equatable + } ``` From 7e548aee134f95019cd0e88aa9d24534b924e55e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Nov 2018 15:47:11 +0100 Subject: [PATCH 017/118] Cleanup SchemaInfo --- GRDB/Core/Database+Schema.swift | 34 ++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 651682b81..71cac5126 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -576,21 +576,19 @@ enum SchemaObjectType: String { } struct SchemaInfo: Equatable { - private var objects: [SchemaKey: String?] + private var objects: Set init(_ db: Database) throws { - objects = try Dictionary(uniqueKeysWithValues: Row - .fetchAll(db, """ - SELECT type, name, tbl_name, sql FROM sqlite_master - UNION - SELECT type, name, tbl_name, sql FROM sqlite_temp_master - """) - .map { row in (SchemaKey(row: row), row["sql"]) }) + objects = try Set(SchemaObject.fetchCursor(db, """ + SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \ + UNION \ + SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master + """)) } /// All names for a given type func names(ofType type: SchemaObjectType) -> Set { - return objects.keys.reduce(into: []) { (set, key) in + return objects.reduce(into: []) { (set, key) in if key.type == type.rawValue { set.insert(key.name) } @@ -603,18 +601,24 @@ struct SchemaInfo: Equatable { /// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar" func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? { let name = name.lowercased() - return objects.keys.first { $0.name.lowercased() == name }?.name + return objects.first { $0.name.lowercased() == name }?.name } - struct SchemaKey: Codable, Hashable, FetchableRecord { + private struct SchemaObject: Codable, Hashable, FetchableRecord { var type: String var name: String var tbl_name: String? - + var sql: String? + var isTemporary: Bool + #if !swift(>=4.2) - var hashValue: Int { - return type.hashValue ^ name.hashValue ^ (tbl_name?.hashValue ?? 0) - } + var hashValue: Int { + return type.hashValue + ^ name.hashValue + ^ (tbl_name?.hashValue ?? 0) + ^ (sql?.hashValue ?? 0) + ^ isTemporary.hashValue + } #endif } } From 65cc0bb2b321a83f59ba3eb80c1e5c7c68b93ddb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Nov 2018 16:49:14 +0100 Subject: [PATCH 018/118] Cache frequently used statements --- GRDB/Core/Database.swift | 4 ++-- GRDB/Core/DatabasePool.swift | 4 ++-- GRDB/Core/DatabaseSnapshot.swift | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 88316ca5e..b4bac1419 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -549,8 +549,8 @@ extension Database { // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) // Assume those pragmas never fail - try! execute("PRAGMA query_only = 1") - defer { try! execute("PRAGMA query_only = 0") } + try! internalCachedUpdateStatement("PRAGMA query_only = 1").execute() + defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() } return try block() } } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2da9e72cc..63b9eebc8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -451,7 +451,7 @@ extension DatabasePool : DatabaseReader { do { try db.beginTransaction(.deferred) assert(db.isInsideTransaction) - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() } catch { readError = error semaphore.signal() // Release the writer queue and rethrow error @@ -545,7 +545,7 @@ extension DatabasePool : DatabaseReader { defer { _ = try? db.commit() } do { try db.beginTransaction(.deferred) - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() } catch { // Snapshot isolation failure futureResult = .failure(error) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 30f60bef2..57acc606c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -37,7 +37,7 @@ public class DatabaseSnapshot : DatabaseReader { // Take snapshot // See DatabasePool.concurrentRead for a complete discussion - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() } } From cbc3467e2de7cf71e42ab908c0863b50d627071a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Nov 2018 16:49:51 +0100 Subject: [PATCH 019/118] Database.beginSnapshotIsolation() --- GRDB/Core/Database.swift | 50 ++++++++++++++++ GRDB/Core/DatabasePool.swift | 97 +------------------------------- GRDB/Core/DatabaseSnapshot.swift | 8 +-- 3 files changed, 53 insertions(+), 102 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b4bac1419..8d50b0dcf 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -714,6 +714,56 @@ extension Database { public func beginTransaction(_ kind: TransactionKind? = nil) throws { let kind = kind ?? configuration.defaultTransactionKind try execute("BEGIN \(kind.rawValue) TRANSACTION") + assert(isInsideTransaction) + } + + /// Begins a database transaction and take a snapshot of the last committed + /// database state. + func beginSnapshotIsolation() throws { + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When a read + // > transaction starts, that reader continues to see an unchanging + // > "snapshot" of the database file as it existed at the moment in time + // > when the read transaction started. Any write transactions that + // > commit while the read transaction is active are still invisible to + // > the read transaction, because the reader is seeing a snapshot of + // > database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read transaction + // starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired on the + // > database until the database is first accessed. [...] Locks are not + // > acquired until the first read or write operation. [...] Because the + // > acquisition of locks is deferred until they are needed, it is + // > possible that another thread or process could create a separate + // > transaction and write to the database after the BEGIN on the + // > current thread has executed. + // + // Now that's precise enough: SQLite defers "snapshot isolation" until + // the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible + // + // We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... + // Here the change is not visible by GRDB user + try beginTransaction(.deferred) + try internalCachedSelectStatement("SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() } /// Rollbacks a database transaction. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 63b9eebc8..5afcee587 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -386,50 +386,6 @@ extension DatabasePool : DatabaseReader { /// happen while establishing the read access to the database. @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // The readFromCurrentState method says that no change should be visible - // at all. We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -449,9 +405,7 @@ extension DatabasePool : DatabaseReader { try readerPool.get { reader in reader.async { db in do { - try db.beginTransaction(.deferred) - assert(db.isInsideTransaction) - try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.beginSnapshotIsolation() } catch { readError = error semaphore.signal() // Release the writer queue and rethrow error @@ -474,50 +428,6 @@ extension DatabasePool : DatabaseReader { } public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // The readFromCurrentState method says that no change should be visible - // at all. We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -540,12 +450,9 @@ extension DatabasePool : DatabaseReader { do { try readerPool.get { reader in reader.async { db in - // Open a deferred transaction and access the database in - // order to establish snapshot isolation. defer { _ = try? db.commit() } do { - try db.beginTransaction(.deferred) - try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.beginSnapshotIsolation() } catch { // Snapshot isolation failure futureResult = .failure(error) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 57acc606c..aa85413ca 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -31,13 +31,7 @@ public class DatabaseSnapshot : DatabaseReader { guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } - - // Establish snapshot isolation (see deinit) - try db.beginTransaction(.deferred) - - // Take snapshot - // See DatabasePool.concurrentRead for a complete discussion - try db.internalCachedSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.beginSnapshotIsolation() } } From f4e77c77000defc5e1dd81524602d0ec6062593c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Nov 2018 17:05:10 +0100 Subject: [PATCH 020/118] Fix Swift 4.1 "expression was too complex to be solved in reasonable time" error --- GRDB/Core/Database+Schema.swift | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 71cac5126..fe07fd0ec 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -613,11 +613,12 @@ struct SchemaInfo: Equatable { #if !swift(>=4.2) var hashValue: Int { - return type.hashValue - ^ name.hashValue - ^ (tbl_name?.hashValue ?? 0) - ^ (sql?.hashValue ?? 0) - ^ isTemporary.hashValue + var hash = type.hashValue + hash ^= name.hashValue + hash ^= (tbl_name?.hashValue ?? 0) + hash ^= (sql?.hashValue ?? 0) + hash ^= isTemporary.hashValue + return hash } #endif } From 59175a6b4d329aee95fe5fa238b43ae67967a4dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Nov 2018 17:18:29 +0100 Subject: [PATCH 021/118] DatabasePool: block reader until concurrent fetch has been executed --- GRDB/Core/DatabasePool.swift | 80 +++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 37 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5afcee587..d691cc5e0 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -402,23 +402,26 @@ extension DatabasePool : DatabaseReader { let semaphore = DispatchSemaphore(value: 0) var readError: Error? = nil - try readerPool.get { reader in - reader.async { db in - do { - try db.beginSnapshotIsolation() - } catch { - readError = error - semaphore.signal() // Release the writer queue and rethrow error - return - } - semaphore.signal() // We can release the writer queue now that we are isolated for good - - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - block(db) - + let (reader, release) = try readerPool.get() + reader.async { db in + defer { _ = try? db.commit() // Ignore commit error + release() } + do { + try db.beginSnapshotIsolation() + } catch { + // Snapshot isolation failure + readError = error + semaphore.signal() // Release the writer queue and rethrow error + return + } + semaphore.signal() // We can release the writer queue now that we are isolated for good + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + block(db) + } _ = semaphore.wait(timeout: .distantFuture) if let readError = readError { @@ -448,29 +451,32 @@ extension DatabasePool : DatabaseReader { var futureResult: Result? = nil do { - try readerPool.get { reader in - reader.async { db in - defer { _ = try? db.commit() } - do { - try db.beginSnapshotIsolation() - } catch { - // Snapshot isolation failure - futureResult = .failure(error) - isolationSemaphore.signal() - futureSemaphore.signal() - return - } - - // Release the writer queue - isolationSemaphore.signal() - - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - - // Fetch and release the future - futureResult = Result { try block(db) } - futureSemaphore.signal() + let (reader, release) = try readerPool.get() + reader.async { db in + defer { + try? db.commit() // Ignore commit error + release() } + do { + try db.beginSnapshotIsolation() + } catch { + // Snapshot isolation failure + futureResult = .failure(error) + isolationSemaphore.signal() + futureSemaphore.signal() + return + } + + // Release the writer queue + isolationSemaphore.signal() + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + + // Fetch and release the future + futureResult = Result { try block(db) } + futureSemaphore.signal() + } } catch { return Future { throw error } From d45ed56b645d3711467d55b790dad6e335e13ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 19 Nov 2018 09:01:26 +0100 Subject: [PATCH 022/118] Fix documentation typo --- GRDB/Core/ValueObservation.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index 427dbfe8a..ede800bd1 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -604,7 +604,7 @@ extension ValueObservation where Reducer == Void { /// Player.all(), /// fetch: { db in return try Player.fetchAll(db) }) /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("Players have changed") /// } /// @@ -637,7 +637,7 @@ extension ValueObservation where Reducer == Void { /// [Player.all()], /// fetch: { db in return try Player.fetchAll(db) }) /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("Players have changed") /// } /// @@ -673,7 +673,7 @@ extension ValueObservation where Reducer == Void { /// Player.all(), /// fetchDistinct: { db in return try Player.fetchAll(db) }) /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("Players have changed") /// } /// @@ -708,7 +708,7 @@ extension ValueObservation where Reducer == Void { /// [Player.all()], /// fetchDistinct: { db in return try Player.fetchAll(db) }) /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in + /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("Players have changed") /// } /// From f5bfb9df95c3a740d2e31577b2de54f03ec9b329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 08:37:51 +0100 Subject: [PATCH 023/118] MutablePersistableRecord.updateChanges(_:with:) --- GRDB/Record/PersistableRecord.swift | 70 ++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 11 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 9c4197a91..c06fb669d 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -521,22 +521,71 @@ extension MutablePersistableRecord { try update(db, columns: Set(columns.map { $0.name })) } - /// If the record has differences from the other record, executes an UPDATE - /// statement so that those changes and only those changes are saved in - /// the database. + /// If the record has any difference from the other record, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. /// - /// This method is guaranteed to have saved the eventual changes in the + /// This method is guaranteed to have saved the eventual differences in the /// database if it returns without error. /// + /// For example: + /// + /// if let oldPlayer = Player.fetchOne(db, key: 42) { + /// var newPlayer = oldPlayer + /// newPlayer.score += 10 + /// newPlayer.hasAward = true + /// try newPlayer.updateChanges(db, from: oldRecord) + /// } + /// /// - parameter db: A database connection. - /// - parameter columns: The columns to update. + /// - parameter record: The comparison record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + /// - SeeAlso: updateChanges(_:with:) + @discardableResult + public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { + let oldContainer = PersistenceContainer(record) + let changes = databaseChangesIterator(from: oldContainer) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return false + } else { + try update(db, columns: changedColumns) + return true + } + } + + /// Mutates the record according to the provided closure, and then, if the + /// record has any difference from its previous version, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. + /// + /// This method is guaranteed to have saved the eventual differences in the + /// database if it returns without error. + /// + /// For example: + /// + /// if var player = Player.fetchOne(db, key: 42) { + /// try player.updateChanges(db) { + /// $0.score += 10 + /// $0.hasAward = true + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter change: A closure that modifise the record. /// - returns: Whether the record had changes. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { - let changedColumns = Set(databaseChanges(from: record).keys) + public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { + let oldContainer = PersistenceContainer(self) + try change(&self) + let changes = databaseChangesIterator(from: oldContainer) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } if changedColumns.isEmpty { return false } else { @@ -574,7 +623,7 @@ extension MutablePersistableRecord { /// Returns a boolean indicating whether this record and the other record /// have the same database representation. public func databaseEquals(_ record: Self) -> Bool { - return databaseChangesIterator(from: record).next() == nil + return databaseChangesIterator(from: PersistenceContainer(record)).next() == nil } /// A dictionary of values changed from the other record. @@ -586,11 +635,10 @@ extension MutablePersistableRecord { /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. public func databaseChanges(from record: MutablePersistableRecord) -> [String: DatabaseValue] { - return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record)) + return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record))) } - fileprivate func databaseChangesIterator(from record: MutablePersistableRecord) -> AnyIterator<(String, DatabaseValue)> { - let oldContainer = PersistenceContainer(record) + fileprivate func databaseChangesIterator(from oldContainer: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: From a3e62d873496f32adf50d8eed4f1b7ce17312b60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 20:28:22 +0100 Subject: [PATCH 024/118] Factor updateChanges --- GRDB/Record/PersistableRecord.swift | 33 +++++++++++++---------------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index c06fb669d..07bfa403c 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -530,7 +530,7 @@ extension MutablePersistableRecord { /// /// For example: /// - /// if let oldPlayer = Player.fetchOne(db, key: 42) { + /// if let oldPlayer = try Player.fetchOne(db, key: 42) { /// var newPlayer = oldPlayer /// newPlayer.score += 10 /// newPlayer.hasAward = true @@ -547,14 +547,7 @@ extension MutablePersistableRecord { @discardableResult public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { let oldContainer = PersistenceContainer(record) - let changes = databaseChangesIterator(from: oldContainer) - let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } - if changedColumns.isEmpty { - return false - } else { - try update(db, columns: changedColumns) - return true - } + return try updateChanges(db, from: oldContainer) } /// Mutates the record according to the provided closure, and then, if the @@ -567,7 +560,7 @@ extension MutablePersistableRecord { /// /// For example: /// - /// if var player = Player.fetchOne(db, key: 42) { + /// if var player = try Player.fetchOne(db, key: 42) { /// try player.updateChanges(db) { /// $0.score += 10 /// $0.hasAward = true @@ -584,14 +577,7 @@ extension MutablePersistableRecord { public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { let oldContainer = PersistenceContainer(self) try change(&self) - let changes = databaseChangesIterator(from: oldContainer) - let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } - if changedColumns.isEmpty { - return false - } else { - try update(db, columns: changedColumns) - return true - } + return try updateChanges(db, from: oldContainer) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -654,6 +640,17 @@ extension MutablePersistableRecord { } } + @discardableResult + fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { + let changes = databaseChangesIterator(from: container) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return false + } + try update(db, columns: changedColumns) + return true + } + // MARK: - CRUD Internals /// Return true if record has a non-null primary key From 3e67a1a021226c4e6c85a4a54f7e254cb835f8b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 20:33:21 +0100 Subject: [PATCH 025/118] Why use fileprivate when private is enough? --- GRDB/Record/PersistableRecord.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 07bfa403c..8c09473df 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -624,7 +624,7 @@ extension MutablePersistableRecord { return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record))) } - fileprivate func databaseChangesIterator(from oldContainer: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { + private func databaseChangesIterator(from oldContainer: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: @@ -641,7 +641,7 @@ extension MutablePersistableRecord { } @discardableResult - fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { + private func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { let changes = databaseChangesIterator(from: container) let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } if changedColumns.isEmpty { From c04e6ad86db5885bc0a58c3e203416f1d47d0213 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 21:48:24 +0100 Subject: [PATCH 026/118] Tests for updateChanges(_:with:) --- ...MutablePersistableRecordChangesTests.swift | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f8b01ebce..322c78c03 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -269,4 +269,236 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } } } + + func testUpdateChangesWithRecord() throws { + class MyRecord: Record { + var id: Int64? + var firstName: String? + var lastName: String? + + init(id: Int64?, firstName: String?, lastName: String?) { + self.id = id + self.firstName = firstName + self.lastName = lastName + super.init() + } + + override class var databaseTableName: String { + return "myRecord" + } + + enum Columns: String, ColumnExpression { + case id, firstName, lastName + } + + required init(row: Row) { + id = row[Columns.id] + firstName = row[Columns.firstName] + lastName = row[Columns.lastName] + super.init(row: row) + } + + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.firstName] = firstName + container[Columns.lastName] = lastName + } + + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } + + func testUpdateChangesWithNonRecordClass() throws { + class MyRecord: Codable, PersistableRecord { + var id: Int64? + var firstName: String? + var lastName: String? + + init(id: Int64?, firstName: String?, lastName: String?) { + self.id = id + self.firstName = firstName + self.lastName = lastName + } + + func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } + + func testUpdateChangesWithStruct() throws { + struct MyRecord: Codable, MutablePersistableRecord { + var id: Int64? + var firstName: String? + var lastName: String? + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } } From 0cd1ca11ef3268db80ab004e9b7780a9b8afad38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 21:48:34 +0100 Subject: [PATCH 027/118] TODO --- Tests/GRDBTests/ValueObservationReducerTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index ff26d3026..aba30c909 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -120,6 +120,7 @@ class ValueObservationReducerTests: GRDBTestCase { XCTAssertEqual(fetchCount, 4) XCTAssertEqual(reduceCount, 4) XCTAssertEqual(errors.count, 0) + // TODO: Fix flacky test https://travis-ci.org/groue/GRDB.swift/jobs/458101713 XCTAssertEqual(changes, ["0", "1", "5"]) } From 72a2408fceb0a6d729500032435587da4f731d34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 22:08:05 +0100 Subject: [PATCH 028/118] CHANGELOG --- CHANGELOG.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3168af77..461ec9c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,13 +6,7 @@ Release Notes ### New - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - - ```swift - // Deletes and recreates from scratch all indices that use this - // locale-dependent collation. - try db.reindex(collation: .localizedCompare) - ``` - +- [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update - ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): ```swift From cc2a2a3545b90e3802bd7af18f22ed6b8a808902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 22:09:41 +0100 Subject: [PATCH 029/118] Non-mutating version of updateChanges --- GRDB/Record/PersistableRecord.swift | 32 ++++++++++++++++++- ...MutablePersistableRecordChangesTests.swift | 6 ++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 8c09473df..eb24cfd83 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -641,7 +641,7 @@ extension MutablePersistableRecord { } @discardableResult - private func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { + fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { let changes = databaseChangesIterator(from: container) let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } if changedColumns.isEmpty { @@ -974,6 +974,36 @@ extension PersistableRecord { try performSave(db) } + /// Mutates the record according to the provided closure, and then, if the + /// record has any difference from its previous version, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. + /// + /// This method is guaranteed to have saved the eventual differences in the + /// database if it returns without error. + /// + /// For example: + /// + /// if let player = try Player.fetchOne(db, key: 42) { + /// try player.updateChanges(db) { + /// $0.score += 10 + /// $0.hasAward = true + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter change: A closure that modifise the record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @discardableResult + public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool { + let oldContainer = PersistenceContainer(self) + try change(self) + return try updateChanges(db, from: oldContainer) + } + // MARK: - Immutable CRUD Internals diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index 322c78c03..a3f7db736 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -317,7 +317,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { t.column("lastName", .text) } - var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + // This `let` is part of the test + let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { @@ -389,7 +390,8 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { t.column("lastName", .text) } - var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + // This `let` is part of the test + let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") try record.insert(db) do { From 1baca23500e14202133eaba3523f28c994f54a92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 22:12:52 +0100 Subject: [PATCH 030/118] CHANGELOG --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 461ec9c3f..e22643889 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,14 @@ Release Notes + func reindex(collation: Database.CollationName) throws + func reindex(collation: DatabaseCollation) throws } + + extension MutablePersistableRecord { ++ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool + } + + extension PersistableRecord { ++ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool + } struct ValueObservation { + static func tracking( From 771c85581c2089c77969ab34c0d498dea3875582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 22:13:07 +0100 Subject: [PATCH 031/118] Fix documentation typo --- GRDB/Record/PersistableRecord.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index eb24cfd83..d78e6011d 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -568,7 +568,7 @@ extension MutablePersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter change: A closure that modifise the record. + /// - parameter change: A closure that modifies the record. /// - returns: Whether the record had changes. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not @@ -992,7 +992,7 @@ extension PersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter change: A closure that modifise the record. + /// - parameter change: A closure that modifies the record. /// - returns: Whether the record had changes. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not From d6e7d74a121b06e2596783f0246367476d124719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 22:27:33 +0100 Subject: [PATCH 032/118] Cleanup --- GRDB/Record/PersistableRecord.swift | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index d78e6011d..47a33a7ff 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -546,8 +546,7 @@ extension MutablePersistableRecord { /// - SeeAlso: updateChanges(_:with:) @discardableResult public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { - let oldContainer = PersistenceContainer(record) - return try updateChanges(db, from: oldContainer) + return try updateChanges(db, from: PersistenceContainer(record)) } /// Mutates the record according to the provided closure, and then, if the @@ -575,9 +574,9 @@ extension MutablePersistableRecord { /// match any row in the database and record could not be updated. @discardableResult public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { - let oldContainer = PersistenceContainer(self) + let container = PersistenceContainer(self) try change(&self) - return try updateChanges(db, from: oldContainer) + return try updateChanges(db, from: container) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -624,12 +623,12 @@ extension MutablePersistableRecord { return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record))) } - private func databaseChangesIterator(from oldContainer: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { + private func databaseChangesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueIterator.next() { - let oldValue = oldContainer[caseInsensitive: column] + let oldValue = container[caseInsensitive: column] let oldDbValue = oldValue?.databaseValue ?? .null let newDbValue = newValue?.databaseValue ?? .null if newDbValue != oldDbValue { @@ -999,9 +998,9 @@ extension PersistableRecord { /// match any row in the database and record could not be updated. @discardableResult public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool { - let oldContainer = PersistenceContainer(self) + let container = PersistenceContainer(self) try change(self) - return try updateChanges(db, from: oldContainer) + return try updateChanges(db, from: container) } From f4c0eaa91268e29892827f3fa3f032b0b0fbafd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 23:03:30 +0100 Subject: [PATCH 033/118] updateChanges(_:with:) documentation --- CHANGELOG.md | 6 +++ README.md | 120 +++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 98 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e22643889..a74299f39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,12 @@ Release Notes - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. + +### Documentation Diff + +- [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. + + ### API diff ```diff diff --git a/README.md b/README.md index ba7ab2927..a91e62203 100644 --- a/README.md +++ b/README.md @@ -2936,53 +2936,115 @@ class Place: Record { ## Record Comparison -**Records can compare against other records, or against previous versions of themselves.** +**Records that adopt a [PersistableRecord] protocol can compare against other records, or against previous versions of themselves.** This helps avoiding costly UPDATE statements when a record has not been edited. -You can use the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): +- The `updateChanges` Methods +- The `databaseEquals` Method +- The `databaseChanges` Methods + + +### The `updateChanges` Methods + +The `updateChanges` methods perform a database update of the changed columns only (and does nothing if record has no change). + +- `updateChanges(_:from:)` + + This method lets you compare two records: + + ```swift + if let oldPlayer = try Player.fetchOne(db, key: 42) { + var newPlayer = oldPlayer + newPlayer.score = 100 + if try newPlayer.updateChanges(db, from: oldPlayer) { + print("player was modified, and updated in the database") + } else { + print("player was not modified") + } + } + ``` + +- `updateChanges(_:with:)` + + This method lets you update a record in place: + + ```swift + if var player = try Player.fetchOne(db, key: 42) { + let modified = player.updateChanges(db) { + $0.score = 100 + } + if modified { + print("player was modified, and updated in the database") + } else { + print("player was not modified") + } + } + ``` + +- `updateChanges(_:)` ([Record](#record-class) class only) + + The Record class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: + + ```swift + // Record class only + if let player = try Player.fetchOne(db, key: 42) { + player.score = 100 + if try player.updateChanges(db) { + print("player was modified, and updated in the database") + } else { + print("player was not modified") + } + } + ``` + + +### The `databaseEquals` Method + +This method returns whether two records have the same database representation: ```swift -let oldPlayer = try Player.fetchOne(db, ...) -var newPlayer = oldPlayer -newPlayer.score = 100 -if try newPlayer.updateChanges(db, from: oldPlayer) { - print("player was modified, and updated in the database") -} else { - print("player was not modified") +let oldPlayer: Player = ... +var newPlayer: Player = ... +if newPlayer.databaseEquals(oldPlayer) { + try newPlayer.save(db) } ``` > :point_up: **Note**: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. -The [Record](#record-class) class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: + +### The `databaseChanges` Methods + +This method lets you iterate the differences between two records: + +```swift +let oldPlayer = Player(id: 1, name: "Arthur", score: 100) +let newPlayer = Player(id: 1, name: "Arthur", score: 1000) +for (column, oldValue) in newPlayer.databaseChanges(from: oldPlayer) { + print("\(column) was \(oldValue)") +} +// prints "score was 100" +``` + +The [Record](#record-class) class is able to compare against itself: ```swift // Record class only -let player = try Player.fetchOne(db, ...) -player.score = 100 -if try player.updateChanges(db) { - print("player was modified, and updated in the database") -} else { - print("player was not modified") +let player = Player(id: 1, name: "Arthur", score: 100) +try player.insert(db) +player.score = 1000 +for (column, oldValue) in player.databaseChanges { + print("\(column) was \(oldValue)") } +// prints "score was 100" ``` -You can also use the `databaseEquals` method, which returns whether two records have the same database representation: - -```swift -let oldPlayer: Player = ... -var newPlayer: Player = ... -if newPlayer.databaseEquals(oldPlayer) == false { - try newPlayer.save(db) -} -``` - -Again, [Record](#record-class) instances can compare against themselves, with the `hasDatabaseChanges` property: +[Record](#record-class) instances also have a `hasDatabaseChanges` property: ```swift // Record class only -player.score = 100 +player.score = 1000 if player.hasDatabaseChanges { try player.save(db) } @@ -3429,6 +3491,7 @@ This is the list of record methods, along with their required protocols. The [Re | `record.update(db)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | +| `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | @@ -3465,6 +3528,7 @@ This is the list of record methods, along with their required protocols. The [Re | `record.databaseEquals(...)` | [PersistableRecord] | | | `record.databaseChanges(from:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | | +| `record.updateChanges(db) { ... }` | [PersistableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | From 9735d8b74e7b56a541f8236bfba16340036a7bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 21 Nov 2018 23:08:53 +0100 Subject: [PATCH 034/118] Record Comparison documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a91e62203..b3bc32935 100644 --- a/README.md +++ b/README.md @@ -2940,9 +2940,9 @@ class Place: Record { This helps avoiding costly UPDATE statements when a record has not been edited. -- The `updateChanges` Methods -- The `databaseEquals` Method -- The `databaseChanges` Methods +- [The `updateChanges` Methods](#the-updatechanges-methods) +- [The `databaseEquals` Method](#the-databaseequals-method) +- [The `databaseChanges` and `hasDatabaseChanges` Methods](#the-databasechanges-and-hasdatabasechanges-methods) ### The `updateChanges` Methods @@ -3006,7 +3006,7 @@ This method returns whether two records have the same database representation: ```swift let oldPlayer: Player = ... var newPlayer: Player = ... -if newPlayer.databaseEquals(oldPlayer) { +if newPlayer.databaseEquals(oldPlayer) == false { try newPlayer.save(db) } ``` @@ -3014,7 +3014,7 @@ if newPlayer.databaseEquals(oldPlayer) { > :point_up: **Note**: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. -### The `databaseChanges` Methods +### The `databaseChanges` and `hasDatabaseChanges` Methods This method lets you iterate the differences between two records: From e95119130cf69195116cf9726014d5e57e81906b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Nov 2018 08:14:00 +0100 Subject: [PATCH 035/118] Documentation tweaks --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b3bc32935..3279733bc 100644 --- a/README.md +++ b/README.md @@ -2982,9 +2982,9 @@ The `updateChanges` methods perform a database update of the changed columns onl } ``` -- `updateChanges(_:)` ([Record](#record-class) class only) +- `updateChanges(_:)` (Record class only) - The Record class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: + Instances of the [Record](#record-class) class are able to compare against themselves, and know if they have changes that have not been saved since the last fetch or saving: ```swift // Record class only @@ -3016,7 +3016,7 @@ if newPlayer.databaseEquals(oldPlayer) == false { ### The `databaseChanges` and `hasDatabaseChanges` Methods -This method lets you iterate the differences between two records: +`databaseChanges(from:)` returns a dictionary of differences between two records: ```swift let oldPlayer = Player(id: 1, name: "Arthur", score: 100) From 03b51ee899fecd18cb439661c0fe510ac90b238f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Nov 2018 09:34:10 +0100 Subject: [PATCH 036/118] Second failed test :-( --- Tests/GRDBTests/ValueObservationReducerTests.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index aba30c909..cce9c0062 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -120,7 +120,10 @@ class ValueObservationReducerTests: GRDBTestCase { XCTAssertEqual(fetchCount, 4) XCTAssertEqual(reduceCount, 4) XCTAssertEqual(errors.count, 0) - // TODO: Fix flacky test https://travis-ci.org/groue/GRDB.swift/jobs/458101713 + // TODO: Fix flacky test: + // XCTAssertEqual failed: ("["0", "3", "5"]") is not equal to ("["0", "1", "5"]") + // - https://travis-ci.org/groue/GRDB.swift/jobs/458101713 + // - https://travis-ci.org/groue/GRDB.swift/jobs/458283461 XCTAssertEqual(changes, ["0", "1", "5"]) } From 796644edda3eabf2ef23fd41475f9ba5ad0b27ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 23 Nov 2018 07:41:31 +0100 Subject: [PATCH 037/118] Fix test Concurrency is hard --- Tests/GRDBTests/ValueObservationReducerTests.swift | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index cce9c0062..5c8974c64 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -39,7 +39,6 @@ class ValueObservationReducerTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 3 // A reducer which tracks its progress - var dropNext = false // if true, reducer drops next value let reducer = AnyValueReducer( fetch: { db -> Int in fetchCount += 1 @@ -48,9 +47,8 @@ class ValueObservationReducerTests: GRDBTestCase { }, value: { count -> String? in reduceCount += 1 - if dropNext { + if count == 3 { // test that reducer can drop values - dropNext = false return nil } // test that the fetched type and the notified type can be different @@ -95,7 +93,6 @@ class ValueObservationReducerTests: GRDBTestCase { } // Test a dropped transaction - dropNext = true try db.inTransaction { try db.execute("INSERT INTO t DEFAULT VALUES") try db.execute("INSERT INTO t DEFAULT VALUES") @@ -120,10 +117,6 @@ class ValueObservationReducerTests: GRDBTestCase { XCTAssertEqual(fetchCount, 4) XCTAssertEqual(reduceCount, 4) XCTAssertEqual(errors.count, 0) - // TODO: Fix flacky test: - // XCTAssertEqual failed: ("["0", "3", "5"]") is not equal to ("["0", "1", "5"]") - // - https://travis-ci.org/groue/GRDB.swift/jobs/458101713 - // - https://travis-ci.org/groue/GRDB.swift/jobs/458283461 XCTAssertEqual(changes, ["0", "1", "5"]) } From 326ef19fe9e1be5c8f0c5b8b4a1b797a64f35ff9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 11:38:47 +0100 Subject: [PATCH 038/118] ValueObservation combination --- GRDB.xcodeproj/project.pbxproj | 66 +- GRDB/Core/ValueObservation.swift | 1037 ----------------- GRDB/Utils/Utils.swift | 12 + .../ValueObservation+Combine.swift | 275 +++++ .../ValueObservation+Count.swift | 41 + ...Observation+DatabaseValueConvertible.swift | 207 ++++ .../ValueObservation+FetchableRecord.swift | 131 +++ .../ValueObservation+Map.swift | 51 + .../ValueObservation+Row.swift | 72 ++ GRDB/ValueObservation/ValueObservation.swift | 453 +++++++ GRDB/ValueObservation/ValueReducer.swift | 126 ++ GRDBCipher.xcodeproj/project.pbxproj | 62 +- GRDBCustom.xcodeproj/project.pbxproj | 62 +- 13 files changed, 1545 insertions(+), 1050 deletions(-) delete mode 100644 GRDB/Core/ValueObservation.swift create mode 100644 GRDB/ValueObservation/ValueObservation+Combine.swift create mode 100644 GRDB/ValueObservation/ValueObservation+Count.swift create mode 100644 GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift create mode 100644 GRDB/ValueObservation/ValueObservation+FetchableRecord.swift create mode 100644 GRDB/ValueObservation/ValueObservation+Map.swift create mode 100644 GRDB/ValueObservation/ValueObservation+Row.swift create mode 100644 GRDB/ValueObservation/ValueObservation.swift create mode 100644 GRDB/ValueObservation/ValueReducer.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b42142903..53c6b455f 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -49,6 +49,27 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; + 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; @@ -881,6 +902,13 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1348,6 +1376,21 @@ name = PersistableRecord; sourceTree = ""; }; + 5613ED4221A95AFB00DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, + 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */, + 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */, + 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */, + 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */, + 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( @@ -1762,7 +1805,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1966,6 +2008,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED4221A95AFB00DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -2408,15 +2451,18 @@ 565490E21D5AE252005622CB /* Record.swift in Sources */, 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, + 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, 566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, + 5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, @@ -2430,9 +2476,11 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, + 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -2442,6 +2490,8 @@ 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, + 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, @@ -2549,6 +2599,7 @@ 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, + 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, @@ -2600,6 +2651,7 @@ 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, + 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 563EF44B2161F179007DAACD /* Inflections.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -2622,15 +2674,20 @@ 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, + 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, + 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, + 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, + 5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, + 5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, 56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -3001,13 +3058,16 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, + 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 563EF44A2161F179007DAACD /* Inflections.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, @@ -3016,6 +3076,7 @@ 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, + 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215A1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -3061,13 +3122,16 @@ 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, + 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, + 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift deleted file mode 100644 index ede800bd1..000000000 --- a/GRDB/Core/ValueObservation.swift +++ /dev/null @@ -1,1037 +0,0 @@ -// -// ValueObservation.swift -// GRDB -// -// Created by Gwendal RouĂ© on 23/10/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - -import Dispatch - -// MARK: - ValueScheduling - -/// ValueScheduling controls how ValueObservation schedules the notifications -/// of fresh values to your application. -public enum ValueScheduling { - /// All values are notified on the main queue. - /// - /// If the observation starts on the main queue, an initial value is - /// notified right upon subscription, synchronously: - /// - /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, an initial value - /// is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// - /// When the database changes, fresh values are asynchronously notified on - /// the main queue: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - case mainQueue - - /// All values are asychronously notified on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - case onQueue(DispatchQueue, startImmediately: Bool) - - /// Values are not all notified on the same dispatch queue. - /// - /// If `startImmediately` is true, an initial value is notified right upon - /// subscription, synchronously, on the dispatch queue which starts - /// the observation. - /// - /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) - /// observation.scheduling = .unsafe(startImmediately: true) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - case unsafe(startImmediately: Bool) -} - -extension DispatchQueue { - private static var mainKey: DispatchSpecificKey<()> = { - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - return key - }() - - static var isMain: Bool { - return DispatchQueue.getSpecific(key: mainKey) != nil - } -} - -// MARK: - ValueReducer - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// The ValueReducer protocol supports ValueObservation. -public protocol ValueReducer { - /// The type of fetched database values - associatedtype Fetched - - /// The type of observed values - associatedtype Value - - /// Feches database values upon changes in an observed database region. - func fetch(_ db: Database) throws -> Fetched - - /// Transforms a fetched value into an eventual observed value. Returns nil - /// when observer should not be notified. - /// - /// This method runs inside a private dispatch queue. - mutating func value(_ fetched: Fetched) -> Value? -} - -extension ValueReducer { - /// Returns a reducer which transforms the values returned by this reducer. - public func map(_ transform: @escaping (Value) -> T?) -> MapValueReducer { - return MapValueReducer(self, transform) - } -} - -/// A ValueReducer whose values consist of those in a Base ValueReducer passed -/// through a transform function. -/// -/// See ValueReducer.map(_:) -/// -/// :nodoc: -public struct MapValueReducer: ValueReducer { - private var base: Base - private let transform: (Base.Value) -> T? - - init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { - self.base = base - self.transform = transform - } - - public func fetch(_ db: Database) throws -> Base.Fetched { - return try base.fetch(db) - } - - public mutating func value(_ fetched: Base.Fetched) -> T? { - guard let value = base.value(fetched) else { return nil } - return transform(value) - } -} - -/// A type-erased ValueReducer. -/// -/// An AnyValueReducer forwards its operations to an underlying reducer, -/// hiding its specifics. -public struct AnyValueReducer: ValueReducer { - private var _fetch: (Database) throws -> Fetched - private var _value: (Fetched) -> Value? - - /// Creates a reducer whose `fetch(_:)` and `value(_:)` methods wrap and - /// forward operations the argument closures. - /// - /// For example, this reducer counts the number of a times the player table - /// is modified: - /// - /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count - /// }) - /// let observer = ValueObservation - /// .tracking(Player.all(), reducer: reducer) - /// .start(in: dbQueue) { count: Int in - /// print("Players have been modified \(count) times.") - /// } - public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { - self._fetch = fetch - self._value = value - } - - /// Creates a reducer that wraps and forwards operations to `reducer`. - public init(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value { - var reducer = reducer - self._fetch = { try reducer.fetch($0) } - self._value = { reducer.value($0) } - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Fetched { - return try _fetch(db) - } - - /// :nodoc: - public func value(_ fetched: Fetched) -> Value? { - return _value(fetched) - } -} - -public enum ValueReducers { - /// A reducer which outputs raw database values, without any processing. - public struct Raw: ValueReducer { - private let _fetch: (Database) throws -> Value - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public func value(_ fetched: Value) -> Value? { - return fetched - } - } - - /// A reducer which outputs raw database values, filtering out consecutive - /// values that are equal. - public struct Distinct: ValueReducer { - private let _fetch: (Database) throws -> Value - private var previousValue: Value?? - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ value: Value) -> Value? { - if let previousValue = previousValue, previousValue == value { - // Don't notify consecutive identical values - return nil - } - self.previousValue = value - return value - } - } - - /// A reducer which outputs arrays of records, filtering out consecutive - /// identical database rows. - public struct Records: ValueReducer { - private let _fetch: (Database) throws -> [Row] - private var previousRows: [Row]? - - init(_ fetch: @escaping (Database) throws -> [Row]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [Row] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ rows: [Row]) -> [Record]? { - if let previousRows = previousRows, previousRows == rows { - // Don't notify consecutive identical row arrays - return nil - } - self.previousRows = rows - return rows.map(Record.init(row:)) - } - } - - /// A reducer which outputs optional records, filtering out consecutive - /// identical database rows. - public struct Record: ValueReducer { - private let _fetch: (Database) throws -> Row? - private var previousRow: Row?? - - init(_ fetch: @escaping (Database) throws -> Row?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Row? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ row: Row?) -> Record?? { - if let previousRow = previousRow, previousRow == row { - // Don't notify consecutive identical rows - return nil - } - self.previousRow = row - return .some(row.map(Record.init(row:))) - } - } - - /// A reducer which outputs arrays of values, filtering out consecutive - /// identical database values. - public struct Values: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decode(from: $0, conversionContext: nil) - } - } - } - - /// A reducer which outputs optional values, filtering out consecutive - /// identical database values. - public struct Value: ValueReducer { - private let _fetch: (Database) throws -> DatabaseValue? - private var previousDbValue: DatabaseValue?? - private var previousValueWasNil = false - - init(_ fetch: @escaping (Database) throws -> DatabaseValue?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> DatabaseValue? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValue: DatabaseValue?) -> T?? { - if let previousDbValue = previousDbValue, previousDbValue == dbValue { - // Don't notify consecutive identical dbValue - return nil - } - self.previousDbValue = dbValue - if let dbValue = dbValue, - let value = T.decodeIfPresent(from: dbValue, conversionContext: nil) - { - previousValueWasNil = false - return .some(value) - } else if previousValueWasNil { - // Don't notify consecutive nil values - return nil - } else { - previousValueWasNil = true - return .some(nil) - } - } - } - - /// A reducer which outputs arrays of optional values, filtering out consecutive - /// identical database values. - public struct OptionalValues: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T?]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decodeIfPresent(from: $0, conversionContext: nil) - } - } - } -} - -// MARK: - ValueObservation - -/// ValueObservation tracks changes in the results of database requests, and -/// notifies fresh values whenever the database changes. -/// -/// For example: -/// -/// let observation = ValueObservation.trackingAll(Player.all) -/// let observer = try observation.start(in: dbQueue) { players: [Player] in -/// print("Players have changed.") -/// } -public struct ValueObservation { - /// A closure that is evaluated when the observation starts, and returns - /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion - - /// The reducer is triggered upon each database change in *observedRegion*. - var reducer: Reducer - - /// Default is false. Set this property to true when the observation - /// requires write access in order to fetch fresh values. Fetches are then - /// wrapped inside a savepoint. - /// - /// Don't set this flag to true unless you really need it. A read/write - /// observation is less efficient than a read-only observation. - public var requiresWriteAccess: Bool = false - - /// The extent of the database observation. The default is - /// `.observerLifetime`: the observation lasts until the - /// observer returned by the `start(in:onError:onChange:)` method - /// is deallocated. - public var extent = Database.TransactionObservationExtent.observerLifetime - - /// `scheduling` controls how fresh values are notified. Default - /// is `.mainQueue`. - /// - /// - `.mainQueue`: all values are notified on the main queue. - /// - /// If the observation starts on the main queue, an initial value is - /// notified right upon subscription, synchronously:: - /// - /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, an initial - /// value is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// - /// When the database changes, fresh values are asynchronously notified: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - /// - /// - `.onQueue(_:startImmediately:)`: all values are asychronously notified - /// on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - /// - /// - `unsafe(startImmediately:)`: values are not all notified on the same - /// dispatch queue. - /// - /// If `startImmediately` is true, an initial value is notified right - /// upon subscription, synchronously, on the dispatch queue which starts - /// the observation. - /// - /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) - /// observation.scheduling = .unsafe(startImmediately: true) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - public var scheduling: ValueScheduling = .mainQueue - - /// The dispatch queue where change callbacks are called. - var notificationQueue: DispatchQueue? { - switch scheduling { - case .mainQueue: - return DispatchQueue.main - case .onQueue(let queue, startImmediately: _): - return queue - case .unsafe: - return nil - } - } - - // Not public. See ValueObservation.tracking(_:reducer:) - init( - tracking region: @escaping (Database) throws -> DatabaseRegion, - reducer: Reducer) - { - 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 - } - - /// Returs a ValueObservation which observes *regions*, and notifies the - /// values returned by the *reducer* whenever one of the observed - /// regions is modified by a database transaction. - /// - /// This method is the most fundamental way to create a ValueObservation. - /// - /// For example, this observation counts the number of a times the player - /// table is modified: - /// - /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count - /// }) - /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) - /// let observer = observation.start(in: dbQueue) { count: Int in - /// print("Players have been modified \(count) times.") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter reducer: A reducer that turns database changes in the - /// modified regions into fresh values. Currently only reducers that adopt - /// the ValueReducer protocol are supported. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - reducer: Reducer) - -> ValueObservation - { - return ValueObservation.tracking(regions, reducer: reducer) - } - - /// Returs a ValueObservation which observes *regions*, and notifies the - /// values returned by the *reducer* whenever one of the observed - /// regions is modified by a database transaction. - /// - /// This method is the most fundamental way to create a ValueObservation. - /// - /// For example, this observation counts the number of a times the player - /// table is modified: - /// - /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count - /// }) - /// let observation = ValueObservation.tracking([Player.all()], reducer: reducer) - /// let observer = observation.start(in: dbQueue) { count: Int in - /// print("Players have been modified \(count) times.") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter reducer: A reducer that turns database changes in the - /// modified regions into fresh values. Currently only reducers that adopt - /// the ValueReducer protocol are supported. - public static func tracking( - _ regions: [DatabaseRegionConvertible], - reducer: Reducer) - -> ValueObservation - { - return ValueObservation(tracking: union(regions), reducer: reducer) - } -} - -extension ValueObservation where Reducer: ValueReducer { - /// Returns a ValueObservation which transforms the values returned by - /// this ValueObservation. - public func map(_ transform: @escaping (Reducer.Value) -> T) - -> ValueObservation> - { - return ValueObservation>( - tracking: observedRegion, - reducer: reducer.map(transform)) - } -} - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// Player.all(), - /// fetch: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { - return ValueObservation.tracking(regions, fetch: fetch) - } - - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// [Player.all()], - /// fetch: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: [DatabaseRegionConvertible], - fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { - return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Raw(fetch)) - } - - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. Consecutive equal values - /// are filtered out. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// Player.all(), - /// fetchDistinct: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - where Value: Equatable - { - return ValueObservation.tracking(regions, fetchDistinct: fetch) - } - - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. Consecutive equal values - /// are filtered out. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// [Player.all()], - /// fetchDistinct: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: [DatabaseRegionConvertible], - fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - where Value: Equatable - { - return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Distinct(fetch)) - } -} - -private func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { - return { db in - try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } -} - -// MARK: - Starting Observation - -extension ValueObservation where Reducer: ValueReducer { - /// Starts the value observation in the provided database reader (such as - /// a database queue or database pool), and returns a transaction observer. - /// - /// - parameter reader: A DatabaseReader. - /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation - /// - parameter onChange: A closure that is provided fresh values - /// - returns: a TransactionObserver - public func start( - in reader: DatabaseReader, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver - { - return try reader.add(observation: self, onError: onError, onChange: onChange) - } -} - -// MARK: - Count Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies its - /// count whenever it is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingCount(request) - /// - /// let observer = try observation.start(in: dbQueue) { count: Int in - /// print("Number of players has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingCount(_ request: Request) - -> ValueObservation> - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchCount) - } -} - -// MARK: - Row Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh rows whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest("SELECT * FROM player") - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { rows: [Row] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchAll) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh row whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { row: Row? in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchOne) - } -} - -// MARK: - FetchableRecord Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh records whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Records { try Row.fetchAll($0, request) }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh record whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.filter(key: 1) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { player: Player? in - /// print("Player has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) -> - ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Record { try Row.fetchOne($0, request) }) - } -} - -// MARK: - DatabaseValueConvertible Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: String.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Values { try DatabaseValue.fetchAll($0, request) }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh value whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.select(max(Column("score")), as: Int.self) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { maxScore: Int? in - /// print("Maximum score has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Value { try DatabaseValue.fetchOne($0, request) }) - } -} - -// MARK: - Optional DatabaseValueConvertible Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: Optional.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String?] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder._Wrapped: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) }) - } -} diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index fa808dca4..484dab35c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -69,3 +69,15 @@ extension Array { } } } + +extension DispatchQueue { + private static var mainKey: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + return DispatchQueue.getSpecific(key: mainKey) != nil + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift new file mode 100644 index 000000000..118094756 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -0,0 +1,275 @@ +// +// ValueObservation+Combine.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +public func combine( + _ o1: ValueObservation, + _ o2: ValueObservation) + -> ValueObservation> +{ + return ValueObservation.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion]), + reducer: combine( + o1.reducer, + o2.reducer)) +} + +public func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation) + -> ValueObservation> +{ + return ValueObservation.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion]), + reducer: combine( + o1.reducer, + o2.reducer, + o3.reducer)) +} + +public func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation) + -> ValueObservation> +{ + return ValueObservation.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion, + o4.observedRegion]), + reducer: combine( + o1.reducer, + o2.reducer, + o3.reducer, + o4.reducer)) +} + +public func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation, + _ o5: ValueObservation) + -> ValueObservation> +{ + return ValueObservation.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion, + o4.observedRegion, + o5.observedRegion]), + reducer: combine( + o1.reducer, + o2.reducer, + o3.reducer, + o4.reducer, + o5.reducer)) +} + +func combine( + _ r1: R1, + _ r2: R2) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched), + (R1.Value, R2.Value)> +{ + var r1 = r1 + var r2 = r2 + var prev1: R1.Value? + var prev2: R2.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + } + if let r1 = v1 ?? prev1, + let r2 = v2 ?? prev2 + { + return (r1, r2) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched), + (R1.Value, R2.Value, R3.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + } + if let r1 = v1 ?? prev1, + let r2 = v2 ?? prev2, + let r3 = v3 ?? prev3 + { + return (r1, r2, r3) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + } + if let r1 = v1 ?? prev1, + let r2 = v2 ?? prev2, + let r3 = v3 ?? prev3, + let r4 = v4 ?? prev4 + { + return (r1, r2, r3, r4) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4, + _ r5: R5) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var r5 = r5 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + var prev5: R5.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db), + r5.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + let v5 = r5.value(tuple.4) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + if let v5 = v5 { prev5 = v5 } + } + if let r1 = v1 ?? prev1, + let r2 = v2 ?? prev2, + let r3 = v3 ?? prev3, + let r4 = v4 ?? prev4, + let r5 = v5 ?? prev5 + { + return (r1, r2, r3, r4, r5) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func union(_ regions: [(Database) throws -> DatabaseRegion]) -> (Database) throws -> DatabaseRegion { + return { db in + try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region(db)) + } + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift new file mode 100644 index 000000000..cdde780cc --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -0,0 +1,41 @@ +// +// ValueObservation+Count.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +extension ValueObservation where Reducer == Void { + + // MARK: - Count Observation + + /// Creates a ValueObservation which observes *request*, and notifies its + /// count whenever it is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = ValueObservation.trackingCount(request) + /// + /// let observer = try observation.start(in: dbQueue) { count: Int in + /// print("Number of players has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingCount(_ request: Request) + -> ValueObservation> + { + return ValueObservation.tracking(request, fetchDistinct: request.fetchCount) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift new file mode 100644 index 000000000..c440567e6 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -0,0 +1,207 @@ +// +// ValueObservation+DatabaseValueConvertible.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +extension ValueObservation where Reducer == Void { + + // MARK: - DatabaseValueConvertible Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh values whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.select(Column("name"), as: String.self) + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { names: [String] in + /// print("Player names have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { + return ValueObservation>.tracking( + request, + reducer: ValueReducers.Values { try DatabaseValue.fetchAll($0, request) }) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh value whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.select(max(Column("score")), as: Int.self) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { maxScore: Int? in + /// print("Maximum score has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { + return ValueObservation>.tracking( + request, + reducer: ValueReducers.Value { try DatabaseValue.fetchOne($0, request) }) + } + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh values whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.select(Column("name"), as: Optional.self) + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { names: [String?] in + /// print("Player names have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder._Wrapped: DatabaseValueConvertible + { + return ValueObservation>.tracking( + request, + reducer: ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) }) + } +} + +extension ValueReducers { + /// A reducer which outputs arrays of values, filtering out consecutive + /// identical database values. + public struct Values: ValueReducer { + private let _fetch: (Database) throws -> [DatabaseValue] + private var previousDbValues: [DatabaseValue]? + + init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ dbValues: [DatabaseValue]) -> [T]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + return nil + } + self.previousDbValues = dbValues + return dbValues.map { + T.decode(from: $0, conversionContext: nil) + } + } + } + + /// A reducer which outputs optional values, filtering out consecutive + /// identical database values. + public struct Value: ValueReducer { + private let _fetch: (Database) throws -> DatabaseValue? + private var previousDbValue: DatabaseValue?? + private var previousValueWasNil = false + + init(_ fetch: @escaping (Database) throws -> DatabaseValue?) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> DatabaseValue? { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ dbValue: DatabaseValue?) -> T?? { + if let previousDbValue = previousDbValue, previousDbValue == dbValue { + // Don't notify consecutive identical dbValue + return nil + } + self.previousDbValue = dbValue + if let dbValue = dbValue, + let value = T.decodeIfPresent(from: dbValue, conversionContext: nil) + { + previousValueWasNil = false + return .some(value) + } else if previousValueWasNil { + // Don't notify consecutive nil values + return nil + } else { + previousValueWasNil = true + return .some(nil) + } + } + } + + /// A reducer which outputs arrays of optional values, filtering out consecutive + /// identical database values. + public struct OptionalValues: ValueReducer { + private let _fetch: (Database) throws -> [DatabaseValue] + private var previousDbValues: [DatabaseValue]? + + init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ dbValues: [DatabaseValue]) -> [T?]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + return nil + } + self.previousDbValues = dbValues + return dbValues.map { + T.decodeIfPresent(from: $0, conversionContext: nil) + } + } + } +} diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift new file mode 100644 index 000000000..6ca6ca16f --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -0,0 +1,131 @@ +// +// ValueObservation+FetchableRecord.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +extension ValueObservation where Reducer == Void { + + // MARK: - FetchableRecord Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh records whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: FetchableRecord + { + return ValueObservation>.tracking( + request, + reducer: ValueReducers.Records { try Row.fetchAll($0, request) }) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh record whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.filter(key: 1) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { player: Player? in + /// print("Player has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) -> + ValueObservation> + where Request.RowDecoder: FetchableRecord + { + return ValueObservation>.tracking( + request, + reducer: ValueReducers.Record { try Row.fetchOne($0, request) }) + } +} + +extension ValueReducers { + /// A reducer which outputs arrays of records, filtering out consecutive + /// identical database rows. + public struct Records: ValueReducer { + private let _fetch: (Database) throws -> [Row] + private var previousRows: [Row]? + + init(_ fetch: @escaping (Database) throws -> [Row]) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> [Row] { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ rows: [Row]) -> [Record]? { + if let previousRows = previousRows, previousRows == rows { + // Don't notify consecutive identical row arrays + return nil + } + self.previousRows = rows + return rows.map(Record.init(row:)) + } + } + + /// A reducer which outputs optional records, filtering out consecutive + /// identical database rows. + public struct Record: ValueReducer { + private let _fetch: (Database) throws -> Row? + private var previousRow: Row?? + + init(_ fetch: @escaping (Database) throws -> Row?) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> Row? { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ row: Row?) -> Record?? { + if let previousRow = previousRow, previousRow == row { + // Don't notify consecutive identical rows + return nil + } + self.previousRow = row + return .some(row.map(Record.init(row:))) + } + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift new file mode 100644 index 000000000..24cde5bcd --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -0,0 +1,51 @@ +// +// ValueObservation+Map.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +extension ValueObservation where Reducer: ValueReducer { + /// Returns a ValueObservation which transforms the values returned by + /// this ValueObservation. + public func map(_ transform: @escaping (Reducer.Value) -> T) + -> ValueObservation> + { + return ValueObservation>( + tracking: observedRegion, + reducer: reducer.map(transform)) + } +} + +extension ValueReducer { + /// Returns a reducer which transforms the values returned by this reducer. + public func map(_ transform: @escaping (Value) -> T?) -> MapValueReducer { + return MapValueReducer(self, transform) + } +} + +/// A ValueReducer whose values consist of those in a Base ValueReducer passed +/// through a transform function. +/// +/// See ValueReducer.map(_:) +/// +/// :nodoc: +public struct MapValueReducer: ValueReducer { + private var base: Base + private let transform: (Base.Value) -> T? + + init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { + self.base = base + self.transform = transform + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> T? { + guard let value = base.value(fetched) else { return nil } + return transform(value) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift new file mode 100644 index 000000000..1b3cc0300 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -0,0 +1,72 @@ +// +// ValueObservation+Row.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +extension ValueObservation where Reducer == Void { + + // MARK: - Row Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh rows whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { rows: [Row] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder == Row + { + return ValueObservation.tracking(request, fetchDistinct: request.fetchAll) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh row whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { row: Row? in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) + -> ValueObservation> + where Request.RowDecoder == Row + { + return ValueObservation.tracking(request, fetchDistinct: request.fetchOne) + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift new file mode 100644 index 000000000..22da33b42 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -0,0 +1,453 @@ +// +// ValueObservation.swift +// GRDB +// +// Created by Gwendal RouĂ© on 23/10/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +import Dispatch + +// MARK: - ValueScheduling + +/// ValueScheduling controls how ValueObservation schedules the notifications +/// of fresh values to your application. +public enum ValueScheduling { + /// All values are notified on the main queue. + /// + /// If the observation starts on the main queue, an initial value is + /// notified right upon subscription, synchronously: + /// + /// // On main queue + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// If the observation does not start on the main queue, an initial value + /// is also notified on the main queue, but asynchronously: + /// + /// // Not on the main queue: "fresh players" is eventually printed + /// // on the main queue. + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// + /// When the database changes, fresh values are asynchronously notified on + /// the main queue: + /// + /// // Eventually prints "fresh players" on the main queue + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + case mainQueue + + /// All values are asychronously notified on the specified queue. + /// + /// An initial value is fetched and notified if `startImmediately` + /// is true. + case onQueue(DispatchQueue, startImmediately: Bool) + + /// Values are not all notified on the same dispatch queue. + /// + /// If `startImmediately` is true, an initial value is notified right upon + /// subscription, synchronously, on the dispatch queue which starts + /// the observation. + /// + /// // On any queue + /// var observation = ValueObservation.trackingAll(Player.all()) + /// observation.scheduling = .unsafe(startImmediately: true) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// When the database changes, other values are notified on + /// unspecified queues. + case unsafe(startImmediately: Bool) +} + +// MARK: - ValueObservation + +/// ValueObservation tracks changes in the results of database requests, and +/// notifies fresh values whenever the database changes. +/// +/// For example: +/// +/// let observation = ValueObservation.trackingAll(Player.all) +/// let observer = try observation.start(in: dbQueue) { players: [Player] in +/// print("Players have changed.") +/// } +public struct ValueObservation { + /// A closure that is evaluated when the observation starts, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + /// The reducer is triggered upon each database change in *observedRegion*. + var reducer: Reducer + + /// Default is false. Set this property to true when the observation + /// requires write access in order to fetch fresh values. Fetches are then + /// wrapped inside a savepoint. + /// + /// Don't set this flag to true unless you really need it. A read/write + /// observation is less efficient than a read-only observation. + public var requiresWriteAccess: Bool = false + + /// The extent of the database observation. The default is + /// `.observerLifetime`: the observation lasts until the + /// observer returned by the `start(in:onError:onChange:)` method + /// is deallocated. + public var extent = Database.TransactionObservationExtent.observerLifetime + + /// `scheduling` controls how fresh values are notified. Default + /// is `.mainQueue`. + /// + /// - `.mainQueue`: all values are notified on the main queue. + /// + /// If the observation starts on the main queue, an initial value is + /// notified right upon subscription, synchronously:: + /// + /// // On main queue + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// If the observation does not start on the main queue, an initial + /// value is also notified on the main queue, but asynchronously: + /// + /// // Not on the main queue: "fresh players" is eventually printed + /// // on the main queue. + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// + /// When the database changes, fresh values are asynchronously notified: + /// + /// // Eventually prints "fresh players" on the main queue + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + /// + /// - `.onQueue(_:startImmediately:)`: all values are asychronously notified + /// on the specified queue. + /// + /// An initial value is fetched and notified if `startImmediately` + /// is true. + /// + /// - `unsafe(startImmediately:)`: values are not all notified on the same + /// dispatch queue. + /// + /// If `startImmediately` is true, an initial value is notified right + /// upon subscription, synchronously, on the dispatch queue which starts + /// the observation. + /// + /// // On any queue + /// var observation = ValueObservation.trackingAll(Player.all()) + /// observation.scheduling = .unsafe(startImmediately: true) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// When the database changes, other values are notified on + /// unspecified queues. + public var scheduling: ValueScheduling = .mainQueue + + /// The dispatch queue where change callbacks are called. + var notificationQueue: DispatchQueue? { + switch scheduling { + case .mainQueue: + return DispatchQueue.main + case .onQueue(let queue, startImmediately: _): + return queue + case .unsafe: + return nil + } + } + + // Not public. See ValueObservation.tracking(_:reducer:) + init( + tracking region: @escaping (Database) throws -> DatabaseRegion, + reducer: Reducer) + { + 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 + } +} + +extension ValueObservation where Reducer: ValueReducer { + + // MARK: - Starting Observation + + /// Starts the value observation in the provided database reader (such as + /// a database queue or database pool), and returns a transaction observer. + /// + /// - parameter reader: A DatabaseReader. + /// - parameter onError: A closure that is provided eventual errors that + /// happen during observation + /// - parameter onChange: A closure that is provided fresh values + /// - returns: a TransactionObserver + public func start( + in reader: DatabaseReader, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver + { + return try reader.add(observation: self, onError: onError, onChange: onChange) + } +} + +extension ValueObservation { + + // MARK: - Creating ValueObservation from ValueReducer + + /// Returs a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count + /// }) + /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + public static func tracking( + _ regions: DatabaseRegionConvertible..., + reducer: Reducer) + -> ValueObservation + { + return ValueObservation.tracking(regions, reducer: reducer) + } + + /// Returs a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count + /// }) + /// let observation = ValueObservation.tracking([Player.all()], reducer: reducer) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + reducer: Reducer) + -> ValueObservation + { + return ValueObservation(tracking: union(regions), reducer: reducer) + } +} + +extension ValueObservation where Reducer == Void { + + // MARK: - Creating ValueObservation from Fetch Closures + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// Player.all(), + /// fetch: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation.tracking(regions, fetch: fetch) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// [Player.all()], + /// fetch: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation>( + tracking: union(regions), + reducer: ValueReducers.Raw(fetch)) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. Consecutive equal values + /// are filtered out. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// Player.all(), + /// fetchDistinct: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + where Value: Equatable + { + return ValueObservation.tracking(regions, fetchDistinct: fetch) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. Consecutive equal values + /// are filtered out. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// [Player.all()], + /// fetchDistinct: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + where Value: Equatable + { + return ValueObservation>( + tracking: union(regions), + reducer: ValueReducers.Distinct(fetch)) + } +} + +private func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + return { db in + try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region.databaseRegion(db)) + } + } +} diff --git a/GRDB/ValueObservation/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer.swift new file mode 100644 index 000000000..91bcd05a0 --- /dev/null +++ b/GRDB/ValueObservation/ValueReducer.swift @@ -0,0 +1,126 @@ +// +// ValueReducer.swift +// GRDB +// +// Created by Gwendal RouĂ© on 24/11/2018. +// Copyright © 2018 Gwendal RouĂ©. All rights reserved. +// + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The ValueReducer protocol supports ValueObservation. +public protocol ValueReducer { + /// The type of fetched database values + associatedtype Fetched + + /// The type of observed values + associatedtype Value + + /// Feches database values upon changes in an observed database region. + func fetch(_ db: Database) throws -> Fetched + + /// Transforms a fetched value into an eventual observed value. Returns nil + /// when observer should not be notified. + /// + /// This method runs inside a private dispatch queue. + mutating func value(_ fetched: Fetched) -> Value? +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A type-erased ValueReducer. +/// +/// An AnyValueReducer forwards its operations to an underlying reducer, +/// hiding its specifics. +public struct AnyValueReducer: ValueReducer { + private var _fetch: (Database) throws -> Fetched + private var _value: (Fetched) -> Value? + + /// Creates a reducer whose `fetch(_:)` and `value(_:)` methods wrap and + /// forward operations the argument closures. + /// + /// For example, this reducer counts the number of a times the player table + /// is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count + /// }) + /// let observer = ValueObservation + /// .tracking(Player.all(), reducer: reducer) + /// .start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { + self._fetch = fetch + self._value = value + } + + /// Creates a reducer that wraps and forwards operations to `reducer`. + public init(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value { + var reducer = reducer + self._fetch = { try reducer.fetch($0) } + self._value = { reducer.value($0) } + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> Fetched { + return try _fetch(db) + } + + /// :nodoc: + public func value(_ fetched: Fetched) -> Value? { + return _value(fetched) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +public enum ValueReducers { + /// A reducer which outputs raw database values, without any processing. + public struct Raw: ValueReducer { + private let _fetch: (Database) throws -> Value + + init(_ fetch: @escaping (Database) throws -> Value) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> Value { + return try _fetch(db) + } + + /// :nodoc: + public func value(_ fetched: Value) -> Value? { + return fetched + } + } + + /// A reducer which outputs raw database values, filtering out consecutive + /// values that are equal. + public struct Distinct: ValueReducer { + private let _fetch: (Database) throws -> Value + private var previousValue: Value?? + + init(_ fetch: @escaping (Database) throws -> Value) { + self._fetch = fetch + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> Value { + return try _fetch(db) + } + + /// :nodoc: + public mutating func value(_ value: Value) -> Value? { + if let previousValue = previousValue, previousValue == value { + // Don't notify consecutive identical values + return nil + } + self.previousValue = value + return value + } + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index f6541248d..f43d4cf2a 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -89,6 +89,22 @@ 560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; }; 560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; + 5613ED7B21A95E8400DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */; }; + 5613ED7C21A95E8400DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */; }; + 5613ED7D21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED7E21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED8521A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED8621A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */; }; + 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */; }; + 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */; }; 561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; @@ -180,8 +196,6 @@ 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; - 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.swift */; }; - 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.swift */; }; 563B06E12185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; 563B06E22185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; 563B06E32185E07300B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; @@ -998,6 +1012,14 @@ 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; 560FC5B01CB00B880014AA8E /* GRDBCipherOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; + 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1026,7 +1048,6 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 563B06B4217F3C5900B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; @@ -1434,6 +1455,21 @@ name = Products; sourceTree = ""; }; + 5613ED7221A95E8400DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */, + 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */, + 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */, + 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */, + 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */, + 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( @@ -1833,7 +1869,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06B4217F3C5900B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1971,6 +2006,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED7221A95E8400DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -2256,8 +2292,10 @@ 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -2299,6 +2337,7 @@ 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, @@ -2307,10 +2346,10 @@ 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */, 56DAA2DC1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7C20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, @@ -2330,15 +2369,19 @@ 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED8521A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, + 5613ED7B21A95E8400DC7A68 /* ValueObservation.swift in Sources */, 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, + 5613ED7D21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -2724,8 +2767,10 @@ 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -2767,6 +2812,7 @@ 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */, @@ -2775,10 +2821,10 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */, 56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7D20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, @@ -2798,15 +2844,19 @@ 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED8621A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, + 5613ED7C21A95E8400DC7A68 /* ValueObservation.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, + 5613ED7E21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7b4462c5f..0233d10a6 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -8,6 +8,22 @@ /* Begin PBXBuildFile section */ 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; + 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; + 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; + 5613ED6321A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED6421A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED6721A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED6821A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */; }; + 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */; }; + 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; @@ -43,8 +59,6 @@ 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; - 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */; }; - 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */; }; 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; @@ -641,6 +655,14 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; + 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; + 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -669,7 +691,6 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; @@ -1043,6 +1064,21 @@ name = PersistableRecord; sourceTree = ""; }; + 5613ED5821A95E6100DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, + 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */, + 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */, + 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */, + 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */, + 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -1449,7 +1485,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1586,6 +1621,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED5821A95E6100DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -1901,8 +1937,10 @@ 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED6821A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -1944,6 +1982,7 @@ 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, + 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -1952,10 +1991,10 @@ F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, + 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, - 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, @@ -1975,15 +2014,19 @@ F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, + 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5613ED6421A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, @@ -2193,8 +2236,10 @@ 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED6721A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -2236,6 +2281,7 @@ 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, + 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2244,10 +2290,10 @@ F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, + 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, - 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, @@ -2267,15 +2313,19 @@ F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, + 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5613ED6321A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, From 41d814b540de53a65c9056948e7fe9230aa9b637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 12:57:24 +0100 Subject: [PATCH 039/118] Tests for ValueObservation combine --- GRDB.xcodeproj/project.pbxproj | 8 +- .../ValueObservation+Combine.swift | 40 +- GRDBCipher.xcodeproj/project.pbxproj | 12 +- GRDBCustom.xcodeproj/project.pbxproj | 8 +- .../ValueObservationCombineTests.swift | 383 ++++++++++++++++++ 5 files changed, 430 insertions(+), 21 deletions(-) create mode 100644 Tests/GRDBTests/ValueObservationCombineTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 53c6b455f..860edfe48 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -70,6 +70,8 @@ 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; @@ -909,6 +911,7 @@ 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; + 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1404,6 +1407,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */, 56A238251B9C74A90082EB20 /* Record */, 56176C9F1EACEE15000F3F2B /* Support */, + 563B06BF2185CD1700B38F35 /* ValueObservation */, ); path = GRDBTests; sourceTree = ""; @@ -1527,6 +1531,7 @@ 563B06BF2185CD1700B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */, @@ -1711,7 +1716,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 563B06BF2185CD1700B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -2796,6 +2800,7 @@ 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, @@ -2972,6 +2977,7 @@ 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, + 5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */, 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift index 118094756..a4cafafcc 100644 --- a/GRDB/ValueObservation/ValueObservation+Combine.swift +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -111,10 +111,11 @@ func combine( if let v1 = v1 { prev1 = v1 } if let v2 = v2 { prev2 = v2 } } - if let r1 = v1 ?? prev1, - let r2 = v2 ?? prev2 + if v1 != nil || v2 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2 { - return (r1, r2) + return (c1, c2) } else { return nil } @@ -151,11 +152,12 @@ func combine( if let v2 = v2 { prev2 = v2 } if let v3 = v3 { prev3 = v3 } } - if let r1 = v1 ?? prev1, - let r2 = v2 ?? prev2, - let r3 = v3 ?? prev3 + if v1 != nil || v2 != nil || v3 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3 { - return (r1, r2, r3) + return (c1, c2, c3) } else { return nil } @@ -198,12 +200,13 @@ func combine Date: Sat, 24 Nov 2018 13:50:36 +0100 Subject: [PATCH 040/118] Documentation --- README.md | 181 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 122 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 3279733bc..898020308 100644 --- a/README.md +++ b/README.md @@ -6301,6 +6301,7 @@ The observer returned by the `start` method is stored in a property of the view > :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) +- [Combining Value Observations](#combining-value-observations) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) - [ValueObservation.tracking(_:reducer:)](#valueobservationtracking_reducer) - [ValueObservation Options](#valueobservation-options) @@ -6367,77 +6368,133 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me } ``` - -### ValueObservation.tracking(_:fetch:) +### Combining Value Observations Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. -When this happens, you create a ValueObservation with the `ValueObservation.tracking(_:fetch:)` method, which accepts two parameters: - -1. The list of observed requests. -2. A closure that fetches a fresh value whenever one of the observed requests are modified. - -The fetch closure is granted an immutable view of the last committed state of the database: this means that fetched values are guaranteed to be **consistent**. - -For example: +When this happens, **combine** several observations together: ```swift // The two observed requests (the team and its players) let teamRequest = Team.filter(key: 1) let playersRequest = Player.filter(Column("teamId") == 1) -// The fetched value +// Two observations +let teamObservation = ValueObservation.trackingOne(teamRequest) +let playersObservation = ValueObservation.trackingAll(playersRequest) + +// The combined observation +let observation = combine(teamObservation, playersObservation) + +// Start tracking players and teams +let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] in + print("Team or players have changed.") +} +``` + +Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). + +> :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. + + +### ValueObservation.tracking(_:fetch:) + +Sometimes you need to observe the database in a way that is uneasy to express with simple requests, or the combination of several observations we have seen above. + +Let's say that we have a struct that defines a "Hall of Fame": + +```swift +struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] + + /// Fetch a HallOfFame + static fetch(_ db: Database) throws -> HallOfFame { + let totalPlayerCount = try Player.fetchCount(db) + let bestPlayers = try Player + .order(Column("score").desc) + .limit(10) + .fetchAll(db) + return HallOfFame( + totalPlayerCount: totalPlayerCount, + bestPlayers: bestPlayers) + } +} + +let hallOfFame = try dbQueue.read { try HallOfFame.fetch($0) } +print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +``` + +In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(_:fetch:)` method. It accepts two parameters: + +1. A list of observed requests. +2. A closure that fetches a fresh value whenever one of the observed requests are modified. + +In our case, any change to the `player` table can impact the Hall of Fame. We thus track the `Player.all()` request for all players, and fetch the Hall of Fame whenever players change: + +```swift +let observation = ValueObservation.tracking( + Player.all(), + fetch: { db -> HallOfFame in + return HallOfFame.fetch(db) + }) + +let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in + print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +} +``` + + +#### Filtering out Consecutive Identical Values + +It may happen that a database change does not modify the fetched values. In your Hall of Fame example, changes to the worst players do not modify the count of players, or the best players. + +In this case, you'll be notified with consecutive identical values. + +You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the fetched value to adopt the Equatable protocol: + +```swift +extension HallOfFame: Equatable { ... } + +let observation = ValueObservation.tracking( + Player.all(), + fetchDistinct: { db -> HallOfFame in + return HallOfFame.fetch(db) + }) + +let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in + print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +} +``` + + +#### The DatabaseRegionConvertible Protocol + +The initial parameter of the `ValueObservation.tracking(_:fetch:)` and `ValueObservation.tracking(_:fetchDistinct:)` methods can be fed with requests, and generally speaking, values that adopt the **DatabaseRegionConvertible** protocol. + +```swift +protocol DatabaseRegionConvertible { + func databaseRegion(_ db: Database) throws -> DatabaseRegion +} +``` + +Use this protocol when you want to encapsulate your complex requests in a dedicated type. In the sample code below, `TeamInfoRequest` is not only able to fetch a team and its players, but also to be observed. + +```swift struct TeamInfo { var team: Team var players: [Player] } -let observation = ValueObservation.tracking( - teamRequest, playersRequest, - fetch: { db -> TeamInfo? in - guard let team = try teamRequest.fetchOne(db) else { - return nil - } - let players = try playersRequest.fetchAll(db) - return TeamInfo(team: team, players: players) - }) - -let observer = observation.start(in: dbQueue) { teamInfo: TeamInfo? in - print("Team and players have changed.") -} -``` - -It may happen that a database change does not modify the fetched values. In this case, you'll be notified with consecutive identical values. You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the fetched value to adopt the Equatable protocol: - -```swift -// When the `player` table is changed, fetch the total number of players, and -// the ten best ones: -struct HallOfFame: Equatable { - var count: Int - var players: [Player] -} - -let observation = ValueObservation.tracking( - Player.all(), - fetchDistinct: { db -> HallOfFame in - let count = try Player.fetchCount(db) - let players = try Player - .order(Column("score").desc) - .limit(10) - .fetchAll(db) - return HallOfFame(count: count, players: players) - }) - -let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in - print("Best players out of \(hallOfFame.count): \(hallOfFame.players)") -} -``` - -The initial parameter of the `ValueObservation.tracking(_:fetch:)` and `ValueObservation.tracking(_:fetchDistinct:)` methods can be fed with requests, and generally speaking, values that adopt the **DatabaseRegionConvertible** protocol. - -Use this protocol when you want to encapsulate your complex requests in a dedicated type. Our example above can be rewritten as below: - -```swift struct TeamInfoRequest: DatabaseRegionConvertible { var teamId: Int64 @@ -6449,13 +6506,14 @@ struct TeamInfoRequest: DatabaseRegionConvertible { return Player.filter(Column("teamId") == teamId) } - // DatabaseRegionConvertible adoption + /// DatabaseRegionConvertible adoption func databaseRegion(_ db: Database) throws -> DatabaseRegion { let teamRegion = try teamRequest.databaseRegion(db) let playersRegion = try playersRequest.databaseRegion(db) return teamRegion.union(playersRegion) } + /// Fetch a TeamInfo func fetch(_ db: Database) throws -> TeamInfo? { guard let team = try teamRequest.fetchOne(db) else { return nil @@ -6466,10 +6524,15 @@ struct TeamInfoRequest: DatabaseRegionConvertible { } let request = TeamInfoRequest(teamId: 1) + +// Simple fetch +let teamInfo: TeamInfo? = try dbQueue.read(request.fetch) + +// Observatin let observer = ValueObservation .tracking(request, fetch: request.fetch) .start(in: dbQueue) { teamInfo: TeamInfo? in - print("Team and players have hanged.") + print("Team and its players have hanged.") } ``` From 3f1db5aa102456e0982337ea57aaca36c531066b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:22:04 +0100 Subject: [PATCH 041/118] Cleanup --- .../ValueObservation+Combine.swift | 508 +++++++++--------- README.md | 6 +- .../ValueObservationCombineTests.swift | 16 +- 3 files changed, 272 insertions(+), 258 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift index a4cafafcc..988c6f1d9 100644 --- a/GRDB/ValueObservation/ValueObservation+Combine.swift +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -6,268 +6,280 @@ // Copyright © 2018 Gwendal RouĂ©. All rights reserved. // -public func combine( - _ o1: ValueObservation, - _ o2: ValueObservation) - -> ValueObservation> -{ - return ValueObservation.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion]), - reducer: combine( - o1.reducer, - o2.reducer)) +extension ValueObservation where Reducer == Void { + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation) + -> ValueObservation> + { + return ValueObservation>.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion]), + reducer: ValueReducers.combine( + o1.reducer, + o2.reducer)) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation) + -> ValueObservation> + { + return ValueObservation>.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion]), + reducer: ValueReducers.combine( + o1.reducer, + o2.reducer, + o3.reducer)) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation) + -> ValueObservation> + { + return ValueObservation>.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion, + o4.observedRegion]), + reducer: ValueReducers.combine( + o1.reducer, + o2.reducer, + o3.reducer, + o4.reducer)) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation, + _ o5: ValueObservation) + -> ValueObservation> + { + return ValueObservation>.init( + tracking: union([ + o1.observedRegion, + o2.observedRegion, + o3.observedRegion, + o4.observedRegion, + o5.observedRegion]), + reducer: ValueReducers.combine( + o1.reducer, + o2.reducer, + o3.reducer, + o4.reducer, + o5.reducer)) + } } -public func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation) - -> ValueObservation> -{ - return ValueObservation.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion]), - reducer: combine( - o1.reducer, - o2.reducer, - o3.reducer)) -} - -public func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation) - -> ValueObservation> -{ - return ValueObservation.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion, - o4.observedRegion]), - reducer: combine( - o1.reducer, - o2.reducer, - o3.reducer, - o4.reducer)) -} - -public func combine( - _ o1: ValueObservation, - _ o2: ValueObservation, - _ o3: ValueObservation, - _ o4: ValueObservation, - _ o5: ValueObservation) - -> ValueObservation> -{ - return ValueObservation.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion, - o4.observedRegion, - o5.observedRegion]), - reducer: combine( - o1.reducer, - o2.reducer, - o3.reducer, - o4.reducer, - o5.reducer)) -} - -func combine( - _ r1: R1, - _ r2: R2) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched), - (R1.Value, R2.Value)> -{ - var r1 = r1 - var r2 = r2 - var prev1: R1.Value? - var prev2: R2.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } +extension ValueReducers { + static func combine( + _ r1: R1, + _ r2: R2) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched), + (R1.Value, R2.Value)> + { + var r1 = r1 + var r2 = r2 + var prev1: R1.Value? + var prev2: R2.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db)) } - if v1 != nil || v2 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2 - { - return (c1, c2) - } else { - return nil + func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + } + if v1 != nil || v2 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2 + { + return (c1, c2) + } else { + return nil + } } + return AnyValueReducer(fetch: fetch, value: value) } - return AnyValueReducer(fetch: fetch, value: value) -} - -func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched), - (R1.Value, R2.Value, R3.Value)> -{ - var r1 = r1 - var r2 = r2 - var r3 = r3 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } + + static func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched), + (R1.Value, R2.Value, R3.Value)> + { + var r1 = r1 + var r2 = r2 + var r3 = r3 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db)) } - if v1 != nil || v2 != nil || v3 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3 - { - return (c1, c2, c3) - } else { - return nil + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + } + if v1 != nil || v2 != nil || v3 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3 + { + return (c1, c2, c3) + } else { + return nil + } } + return AnyValueReducer(fetch: fetch, value: value) } - return AnyValueReducer(fetch: fetch, value: value) -} - -func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3, - _ r4: R4) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), - (R1.Value, R2.Value, R3.Value, R4.Value)> -{ - var r1 = r1 - var r2 = r2 - var r3 = r3 - var r4 = r4 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - var prev4: R4.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db), - r4.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - let v4 = r4.value(tuple.3) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } - if let v4 = v4 { prev4 = v4 } + + static func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value)> + { + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db)) } - if v1 != nil || v2 != nil || v3 != nil || v4 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3, - let c4 = v4 ?? prev4 - { - return (c1, c2, c3, c4) - } else { - return nil + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4 + { + return (c1, c2, c3, c4) + } else { + return nil + } } + return AnyValueReducer(fetch: fetch, value: value) } - return AnyValueReducer(fetch: fetch, value: value) -} - -func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3, - _ r4: R4, - _ r5: R5) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), - (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> -{ - var r1 = r1 - var r2 = r2 - var r3 = r3 - var r4 = r4 - var r5 = r5 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - var prev4: R4.Value? - var prev5: R5.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db), - r4.fetch(db), - r5.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - let v4 = r4.value(tuple.3) - let v5 = r5.value(tuple.4) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } - if let v4 = v4 { prev4 = v4 } - if let v5 = v5 { prev5 = v5 } + + static func combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4, + _ r5: R5) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> + { + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var r5 = r5 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + var prev5: R5.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db), + r5.fetch(db)) } - if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3, - let c4 = v4 ?? prev4, - let c5 = v5 ?? prev5 - { - return (c1, c2, c3, c4, c5) - } else { - return nil + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + let v5 = r5.value(tuple.4) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + if let v5 = v5 { prev5 = v5 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4, + let c5 = v5 ?? prev5 + { + return (c1, c2, c3, c4, c5) + } else { + return nil + } } + return AnyValueReducer(fetch: fetch, value: value) } - return AnyValueReducer(fetch: fetch, value: value) } private func union(_ regions: [(Database) throws -> DatabaseRegion]) -> (Database) throws -> DatabaseRegion { diff --git a/README.md b/README.md index 898020308..deb398631 100644 --- a/README.md +++ b/README.md @@ -6372,7 +6372,7 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. -When this happens, **combine** several observations together: +When this happens, **combine** several observations together with the `ValueObservation.combine` method: ```swift // The two observed requests (the team and its players) @@ -6384,7 +6384,7 @@ let teamObservation = ValueObservation.trackingOne(teamRequest) let playersObservation = ValueObservation.trackingAll(playersRequest) // The combined observation -let observation = combine(teamObservation, playersObservation) +let observation = ValueObservation.combine(teamObservation, playersObservation) // Start tracking players and teams let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] in @@ -6395,6 +6395,8 @@ let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] i Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). > :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. +> +> :point_up: **Note**: users who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about consistency, though. ### ValueObservation.tracking(_:fetch:) diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index a06a46395..32b89c860 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -31,7 +31,7 @@ class ValueObservationCombineTests: GRDBTestCase { struct T2: TableRecord { } let observation1 = ValueObservation.trackingCount(T1.all()) let observation2 = ValueObservation.trackingCount(T2.all()) - var observation = combine(observation1, observation2) + var observation = ValueObservation.combine(observation1, observation2) observation.extent = .databaseLifetime _ = try observation.start(in: dbQueue) { value in values.append(value) @@ -91,7 +91,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation1 = ValueObservation.trackingCount(T1.all()) let observation2 = ValueObservation.trackingCount(T2.all()) let observation3 = ValueObservation.trackingCount(T3.all()) - var observation = combine(observation1, observation2, observation3) + var observation = ValueObservation.combine(observation1, observation2, observation3) observation.extent = .databaseLifetime _ = try observation.start(in: dbQueue) { value in values.append(value) @@ -165,7 +165,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation2 = ValueObservation.trackingCount(T2.all()) let observation3 = ValueObservation.trackingCount(T3.all()) let observation4 = ValueObservation.trackingCount(T4.all()) - var observation = combine(observation1, observation2, observation3, observation4) + var observation = ValueObservation.combine(observation1, observation2, observation3, observation4) observation.extent = .databaseLifetime _ = try observation.start(in: dbQueue) { value in values.append(value) @@ -253,7 +253,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation3 = ValueObservation.trackingCount(T3.all()) let observation4 = ValueObservation.trackingCount(T4.all()) let observation5 = ValueObservation.trackingCount(T5.all()) - var observation = combine(observation1, observation2, observation3, observation4, observation5) + var observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) observation.extent = .databaseLifetime _ = try observation.start(in: dbQueue) { value in values.append(value) @@ -330,7 +330,7 @@ class ValueObservationCombineTests: GRDBTestCase { struct V2 { } let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) - let observation = combine(observation1, observation2) + let observation = ValueObservation.combine(observation1, observation2) var value: (V1, V2)? _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } XCTAssertNotNil(value) @@ -343,7 +343,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) - let observation = combine(observation1, observation2, observation3) + let observation = ValueObservation.combine(observation1, observation2, observation3) var value: (V1, V2, V3)? _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } XCTAssertNotNil(value) @@ -358,7 +358,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) - let observation = combine(observation1, observation2, observation3, observation4) + let observation = ValueObservation.combine(observation1, observation2, observation3, observation4) var value: (V1, V2, V3, V4)? _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } XCTAssertNotNil(value) @@ -375,7 +375,7 @@ class ValueObservationCombineTests: GRDBTestCase { let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) let observation5 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V5() }) - let observation = combine(observation1, observation2, observation3, observation4, observation5) + let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) var value: (V1, V2, V3, V4, V5)? _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } XCTAssertNotNil(value) From 71b75ee265eef3344546254495b445f3d106ee92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:27:41 +0100 Subject: [PATCH 042/118] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index deb398631..d680ab3db 100644 --- a/README.md +++ b/README.md @@ -6396,7 +6396,7 @@ Combining observations provides the guarantee that notified values are [**consis > :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. > -> :point_up: **Note**: users who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about consistency, though. +> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. ### ValueObservation.tracking(_:fetch:) From a5c291e7a8ffa13beae29e840baf3e0843c0d0bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:35:27 +0100 Subject: [PATCH 043/118] CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a74299f39..1c0021b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Release Notes - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update +- [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): ```swift @@ -22,6 +23,7 @@ Release Notes ### Documentation Diff - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. +- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine(...)` method. ### API diff @@ -57,6 +59,8 @@ Release Notes + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + where Value: Equatable ++ static func combine(_ o1: ValueObservation, ...) ++ -> ValueObservation<...> } ``` From e3a8bfda6ffbcf8cd2f00b51b0689040ce958be7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:37:36 +0100 Subject: [PATCH 044/118] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d680ab3db..3bde97e50 100644 --- a/README.md +++ b/README.md @@ -6301,7 +6301,7 @@ The observer returned by the `start` method is stored in a property of the view > :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) -- [Combining Value Observations](#combining-value-observations) +- [ValueObservation.combine(...)](#valueobservationcombine) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) - [ValueObservation.tracking(_:reducer:)](#valueobservationtracking_reducer) - [ValueObservation Options](#valueobservation-options) @@ -6368,7 +6368,7 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me } ``` -### Combining Value Observations +### ValueObservation.combine(...) Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. From 8a9ccccf9399308a39bdd58727d971e9314d3150 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:47:34 +0100 Subject: [PATCH 045/118] Documentation --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3bde97e50..6a7aebd44 100644 --- a/README.md +++ b/README.md @@ -6435,7 +6435,7 @@ In order to track changes in the Hall of Fame, we'll use the `ValueObservation.t 1. A list of observed requests. 2. A closure that fetches a fresh value whenever one of the observed requests are modified. -In our case, any change to the `player` table can impact the Hall of Fame. We thus track the `Player.all()` request for all players, and fetch the Hall of Fame whenever players change: +In our case, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: ```swift let observation = ValueObservation.tracking( @@ -6455,11 +6455,11 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in #### Filtering out Consecutive Identical Values -It may happen that a database change does not modify the fetched values. In your Hall of Fame example, changes to the worst players do not modify the count of players, or the best players. +It may happen that a database change does not modify the fetched values. The Hall of Fame, for example, is not modified by changes that happen to the worst players. -In this case, you'll be notified with consecutive identical values. +When this happen, `ValueObservation.tracking(_:fetch:)` will notify identical consecutive values. -You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the fetched value to adopt the Equatable protocol: +In order to filter out those duplicates, use `ValueObservation.tracking(_:fetchDistinct:)` instead. It requires the observed value to adopt the Equatable protocol: ```swift extension HallOfFame: Equatable { ... } @@ -6489,6 +6489,8 @@ protocol DatabaseRegionConvertible { } ``` +[DatabaseRegion](#databaseregion) is a type that helps observing the database. + Use this protocol when you want to encapsulate your complex requests in a dedicated type. In the sample code below, `TeamInfoRequest` is not only able to fetch a team and its players, but also to be observed. ```swift @@ -6538,8 +6540,6 @@ let observer = ValueObservation } ``` -See [DatabaseRegion](#databaseregion) for more information. - ### ValueObservation.tracking(_:reducer:) From 42f13a621aa45f41b4a56c728bf0a96ab300c294 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:53:23 +0100 Subject: [PATCH 046/118] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6a7aebd44..5e23b8725 100644 --- a/README.md +++ b/README.md @@ -6401,9 +6401,9 @@ Combining observations provides the guarantee that notified values are [**consis ### ValueObservation.tracking(_:fetch:) -Sometimes you need to observe the database in a way that is uneasy to express with simple requests, or the combination of several observations we have seen above. +Observing the database is not always eaasy to express with simple requests, or the combination of several observations, as we have seen above. -Let's say that we have a struct that defines a "Hall of Fame": +For example, let's say that we have a struct that defines a "Hall of Fame": ```swift struct HallOfFame { From 4376e7519f437aa1489265191a5c57aa7d164234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 14:55:15 +0100 Subject: [PATCH 047/118] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e23b8725..c6beccbd8 100644 --- a/README.md +++ b/README.md @@ -6401,7 +6401,7 @@ Combining observations provides the guarantee that notified values are [**consis ### ValueObservation.tracking(_:fetch:) -Observing the database is not always eaasy to express with simple requests, or the combination of several observations, as we have seen above. +Observing the database is not always easy to express with simple requests, or the combination of several observations, as we have seen above. For example, let's say that we have a struct that defines a "Hall of Fame": From b155ab742a606d53dea98858d8837721b74b1461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 19:38:24 +0100 Subject: [PATCH 048/118] Documentation --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c6beccbd8..766f26ae5 100644 --- a/README.md +++ b/README.md @@ -6455,11 +6455,11 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in #### Filtering out Consecutive Identical Values -It may happen that a database change does not modify the fetched values. The Hall of Fame, for example, is not modified by changes that happen to the worst players. +It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. -When this happen, `ValueObservation.tracking(_:fetch:)` will notify identical consecutive values. +When such a database change happens, `ValueObservation.tracking(_:fetch:)` notifies identical consecutive values. -In order to filter out those duplicates, use `ValueObservation.tracking(_:fetchDistinct:)` instead. It requires the observed value to adopt the Equatable protocol: +You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the observed value to adopt the Equatable protocol: ```swift extension HallOfFame: Equatable { ... } From a521c899621e84dc5cb50be557f49cd939382b89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 19:39:15 +0100 Subject: [PATCH 049/118] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 766f26ae5..12d17bdb7 100644 --- a/README.md +++ b/README.md @@ -6372,7 +6372,7 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. -When this happens, **combine** several observations together with the `ValueObservation.combine` method: +When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: ```swift // The two observed requests (the team and its players) From 736db6a546465d0ed12c7d30bbbf8f1a0eb38236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 20:48:17 +0100 Subject: [PATCH 050/118] Confiiguration.qos and targetQueue --- GRDB/Core/Configuration.swift | 20 +++++++++++++- GRDB/Core/DatabaseWriter.swift | 13 +++------- GRDB/Core/SchedulingWatchdog.swift | 15 +++++++++-- GRDB/Core/SerializedDatabase.swift | 6 ++++- .../DatabasePoolConcurrencyTests.swift | 25 ++++++++++++++++++ Tests/GRDBTests/DatabaseQueueTests.swift | 26 +++++++++++++++++++ 6 files changed, 91 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index b07c02286..cbd979143 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,4 +1,5 @@ import Foundation +import Dispatch #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER @@ -136,11 +137,28 @@ public struct Configuration { /// Default: 5 public var maximumReaderCount: Int = 5 + /// The quality of service class for the work performed by the database. + /// + /// The quality of service is ignored if you supply a target queue. + /// + /// Default: .default (.unspecified on macOS < 10.10) + public var qos: DispatchQoS + + /// The target queue for the work performed by the database. + /// + /// Default: nil + public var targetQueue: DispatchQueue? = nil // MARK: - Factory Configuration /// Creates a factory configuration - public init() { } + public init() { + if #available(OSX 10.10, *) { + qos = .default + } else { + qos = .unspecified + } + } // MARK: - Not Public diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 08094a82c..bbf25c575 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -243,6 +243,7 @@ extension DatabaseWriter { let valueObserver = try ValueObserver( region: observation.observedRegion(db), reducer: reducer, + reducerQoS: db.configuration.qos, fetch: observation.fetchAfterChange(in: self), notificationQueue: observation.notificationQueue, onError: onError, @@ -311,6 +312,7 @@ extension ValueObservation where Reducer: ValueReducer { init( region: DatabaseRegion, reducer: Reducer, + reducerQoS: DispatchQoS, fetch: @escaping (Database, Reducer) -> Future, notificationQueue: DispatchQueue?, onError: ((Error) -> Void)?, @@ -322,16 +324,7 @@ extension ValueObservation where Reducer: ValueReducer { self.notificationQueue = notificationQueue self.onChange = onChange self.onError = onError - if #available(OSX 10.10, *) { - if let queue = notificationQueue { - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation", qos: queue.qos) - } else { - // Assume UI purpose - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation", qos: .userInitiated) - } - } else { - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation") - } + self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation.Reducer", qos: reducerQoS) } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index f7e83e13f..ca06d027b 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -30,8 +30,19 @@ final class SchedulingWatchdog { allowedDatabases = [database] } - static func makeSerializedQueue(allowingDatabase database: Database, label: String) -> DispatchQueue { - let queue = DispatchQueue(label: label) + static func makeSerializedQueue( + allowingDatabase database: Database, + label: String, + qos: DispatchQoS, + targetQueue: DispatchQueue?) + -> DispatchQueue + { + let queue: DispatchQueue + if let targetQueue = targetQueue { + queue = DispatchQueue(label: label, target: targetQueue) + } else { + queue = DispatchQueue(label: label, qos: qos) + } let watchdog = SchedulingWatchdog(allowedDatabase: database) queue.setSpecific(key: specificKey, value: watchdog) return queue diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 9efa3762f..730bb7d56 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -38,7 +38,11 @@ final class SerializedDatabase { config.threadingMode = .multiThread db = try Database(path: path, configuration: config, schemaCache: schemaCache) - queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db, label: label) + queue = SchedulingWatchdog.makeSerializedQueue( + allowingDatabase: db, + label: label, + qos: configuration.qos, + targetQueue: configuration.targetQueue) self.path = path try queue.sync { try db.setup() diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index a28376b07..fce95848e 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1097,4 +1097,29 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { blocks[index]() } } + + @available(OSX 10.12, *) + func testTargetQueue() throws { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() + } + waitForExpectations(timeout: 1, handler: nil) + } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2c3b84dbf..c1d3b23af 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -8,6 +8,7 @@ import Dispatch import GRDB #endif +@available(OSX 10.12, *) class DatabaseQueueTests: GRDBTestCase { // Until SPM tests can load resources, disable this test for SPM. @@ -131,4 +132,29 @@ class DatabaseQueueTests: GRDBTestCase { XCTAssertEqual(label, "Toreador") } } + + @available(OSX 10.12, *) + func testTargetQueue() throws { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() + } + waitForExpectations(timeout: 1, handler: nil) + } } From bf6a1013385bad5b532074ec1b836a9b5a8db044 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 20:56:36 +0100 Subject: [PATCH 051/118] dispatchPrecondition(condition:) iOS availability --- Tests/GRDBTests/DatabasePoolConcurrencyTests.swift | 2 +- Tests/GRDBTests/DatabaseQueueTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index fce95848e..c848bd9f9 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1098,7 +1098,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } - @available(OSX 10.12, *) + @available(OSX 10.12, iOS 10.0, *) func testTargetQueue() throws { func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index c1d3b23af..b58b14fa5 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -133,7 +133,7 @@ class DatabaseQueueTests: GRDBTestCase { } } - @available(OSX 10.12, *) + @available(OSX 10.12, iOS 10.0, *) func testTargetQueue() throws { func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue From 40ba0a7e8f124557e8af9adb740442858c4d8006 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 20:57:43 +0100 Subject: [PATCH 052/118] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c0021b91..510ec42cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Release Notes - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations +- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): ```swift From 9c71061629d5eed5153d9595543ff584e548f88a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 21:14:35 +0100 Subject: [PATCH 053/118] Tests for QoS --- .../DatabasePoolConcurrencyTests.swift | 40 +++++++++++++++++++ Tests/GRDBTests/DatabaseQueueTests.swift | 39 ++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index c848bd9f9..b340a3175 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1,4 +1,5 @@ import XCTest +import Dispatch #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE @@ -1122,4 +1123,43 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) } + + @available(OSX 10.12, iOS 10.0, *) + func testQoS() throws { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + try test(qos: .background) + try test(qos: .userInitiated) + } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index b58b14fa5..4960c9602 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -157,4 +157,43 @@ class DatabaseQueueTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) } + + @available(OSX 10.12, iOS 10.0, *) + func testQoS() throws { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + try test(qos: .background) + try test(qos: .userInitiated) + } } From 267b4f958d95f211d68510f4d8c05214a5118700 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 21:22:47 +0100 Subject: [PATCH 054/118] Remove useless availability check --- Tests/GRDBTests/DatabaseQueueTests.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 4960c9602..d3148de4a 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -8,7 +8,6 @@ import Dispatch import GRDB #endif -@available(OSX 10.12, *) class DatabaseQueueTests: GRDBTestCase { // Until SPM tests can load resources, disable this test for SPM. From 4e1eea5743cdfbfbe68ecd5e0d909056316d103b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 21:46:50 +0100 Subject: [PATCH 055/118] Run run qos and targetQueue tests on Xcode 9.3, iOS 9.0 We lack dispatchPrecondition(condition:) --- .../DatabasePoolConcurrencyTests.swift | 110 +++++++++--------- Tests/GRDBTests/DatabaseQueueTests.swift | 110 +++++++++--------- 2 files changed, 114 insertions(+), 106 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index b340a3175..44ef15faa 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1099,67 +1099,71 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } - @available(OSX 10.12, iOS 10.0, *) func testTargetQueue() throws { - func test(targetQueue: DispatchQueue) throws { - dbConfiguration.targetQueue = targetQueue - let dbPool = try makeDatabasePool() - try dbPool.write { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } } - try dbPool.read { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() } + waitForExpectations(timeout: 1, handler: nil) } - - // background queue - try test(targetQueue: .global(qos: .background)) - - // main queue - let expectation = self.expectation(description: "main") - DispatchQueue.global(qos: .default).async { - try! test(targetQueue: .main) - expectation.fulfill() - } - waitForExpectations(timeout: 1, handler: nil) } - @available(OSX 10.12, iOS 10.0, *) func testQoS() throws { - func test(qos: DispatchQoS) throws { - // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 - // - // > [...] the default target queue [for a serial queue] is the - // > [default] overcommit [global concurrent] queue. - // - // We want this default target queue in order to test database QoS - // with dispatchPrecondition(condition:). - // - // > [...] You can get a reference to the overcommit queue by - // > dropping down to the C function dispatch_get_global_queue - // > (available in Swift with a __ prefix) and passing the private - // > value of DISPATCH_QUEUE_OVERCOMMIT. - // > - // > [...] Of course you should not do this in production code, - // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't - // > know of a way to get a reference to the overcommit queue using - // > only public APIs. - let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 - let targetQueue = __dispatch_get_global_queue( - Int(qos.qosClass.rawValue.rawValue), - DISPATCH_QUEUE_OVERCOMMIT) + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } - dbConfiguration.qos = qos - let dbPool = try makeDatabasePool() - try dbPool.write { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) - } - try dbPool.read { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) - } + try test(qos: .background) + try test(qos: .userInitiated) } - - try test(qos: .background) - try test(qos: .userInitiated) } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index d3148de4a..e2014d9dd 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -132,67 +132,71 @@ class DatabaseQueueTests: GRDBTestCase { } } - @available(OSX 10.12, iOS 10.0, *) func testTargetQueue() throws { - func test(targetQueue: DispatchQueue) throws { - dbConfiguration.targetQueue = targetQueue - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } } - dbQueue.read { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() } + waitForExpectations(timeout: 1, handler: nil) } - - // background queue - try test(targetQueue: .global(qos: .background)) - - // main queue - let expectation = self.expectation(description: "main") - DispatchQueue.global(qos: .default).async { - try! test(targetQueue: .main) - expectation.fulfill() - } - waitForExpectations(timeout: 1, handler: nil) } - @available(OSX 10.12, iOS 10.0, *) func testQoS() throws { - func test(qos: DispatchQoS) throws { - // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 - // - // > [...] the default target queue [for a serial queue] is the - // > [default] overcommit [global concurrent] queue. - // - // We want this default target queue in order to test database QoS - // with dispatchPrecondition(condition:). - // - // > [...] You can get a reference to the overcommit queue by - // > dropping down to the C function dispatch_get_global_queue - // > (available in Swift with a __ prefix) and passing the private - // > value of DISPATCH_QUEUE_OVERCOMMIT. - // > - // > [...] Of course you should not do this in production code, - // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't - // > know of a way to get a reference to the overcommit queue using - // > only public APIs. - let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 - let targetQueue = __dispatch_get_global_queue( - Int(qos.qosClass.rawValue.rawValue), - DISPATCH_QUEUE_OVERCOMMIT) + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } - dbConfiguration.qos = qos - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) - } - dbQueue.read { _ in - dispatchPrecondition(condition: .onQueue(targetQueue)) - } + try test(qos: .background) + try test(qos: .userInitiated) } - - try test(qos: .background) - try test(qos: .userInitiated) } } From 6b78be51e2c787c4ec54c9e2e9acfa7f128ad81b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 24 Nov 2018 23:22:12 +0100 Subject: [PATCH 056/118] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 510ec42cd..b52d397c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,11 @@ Release Notes + static func combine(_ o1: ValueObservation, ...) + -> ValueObservation<...> } + + struct Configuration { ++ var qos: DispatchQoS ++ var targetQueue: DispatchQueue? + } ``` From b757a44a772b88151c830492c8126104fc573658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 07:47:57 +0100 Subject: [PATCH 057/118] CHANGELOG menu --- CHANGELOG.md | 57 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b52d397c9..ae891ea56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,45 @@ Release Notes ============= +All notable changes to this project will be documented in this file. + +GRDB adheres to [Semantic Versioning](https://semver.org/). + +#### 3.x Releases + +- `3.5.x` Releases - [3.5.0](#350) +- `3.4.x` Releases - [3.4.0](#340) +- `3.3.x` Releases - [3.3.1](#331) | [3.3.0](#330) | [3.3.0-beta1](#330-beta1) +- `3.2.x` Releases - [3.2.0](#320) +- `3.1.x` Releases - [3.1.0](#310) +- `3.0.x` Releases - [3.0.0](#300) + +#### 2.x Releases + +- `2.10.x` Releases - [2.10.0](#2100) +- `2.9.x` Releases - [2.9.0](#290) +- `2.8.x` Releases - [2.8.0](#280) +- `2.7.x` Releases - [2.7.0](#270) +- `2.6.x` Releases - [2.6.1](#261) | [2.6.0](#260) +- `2.5.x` Releases - [2.5.0](#250) +- `2.4.x` Releases - [2.4.2](#242) | [2.4.1](#241) | [2.4.0](#240) +- `2.3.x` Releases - [2.3.1](#231) | [2.3.0](#230) +- `2.2.x` Releases - [2.2.0](#220) +- `2.1.x` Releases - [2.1.0](#210) +- `2.0.x` Releases - [2.0.3](#203) | [2.0.2](#202) | [2.0.1](#201) | [2.0.0](#200) + +#### 1.x Releases + +- `1.3.x` Releases - [1.3.0](#130) +- `1.2.x` Releases - [1.2.2](#122) | [1.2.1](#121) | [1.2.0](#120) +- `1.1.x` Releases - [1.1.0](#110) +- `1.0.x` Releases - [1.0.0](#100) + +#### 0.x Releases + +- [0.110.0](#01100), ... + + ## Next Version ### New @@ -9,15 +48,7 @@ Release Notes - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue -- ValueObservation has three new factory methods that accept an array of database regions, and complete the existing variadic methods (addresses [#441](https://github.com/groue/GRDB.swift/issues/441)): - - ```swift - let regions: [DatabaseRegionConvertible] = [Player.all(), Team.all()] - ValueObservation.tracking(regions, fetch: { db in ... }) - ValueObservation.tracking(regions, fetchDistinct: { db in ... }) - ValueObservation.tracking(regions, reducer: ...) - ``` - +- ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. @@ -1378,7 +1409,7 @@ Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare It used to generate `= NULL` which would not behave as expected. -## 1.2 +## 1.2.0 Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2) @@ -1477,7 +1508,7 @@ Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare ``` -## 1.1 +## 1.1.0 Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1) @@ -1539,9 +1570,9 @@ Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/ ``` -## 1.0 :tada: +## 1.0.0 -Released June 20, 2017 +Released June 20, 2017 :tada: **GRDB 1.0 comes with enhancements, and API stability.** From 417b830b6113e77ce7315c90f767da1959ad2b40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 07:51:08 +0100 Subject: [PATCH 058/118] CHANGELOG menu --- CHANGELOG.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae891ea56..09a43039b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - `3.5.x` Releases - [3.5.0](#350) - `3.4.x` Releases - [3.4.0](#340) -- `3.3.x` Releases - [3.3.1](#331) | [3.3.0](#330) | [3.3.0-beta1](#330-beta1) +- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331) +- `3.3.0` Betas - [3.3.0-beta1](#330-beta1) - `3.2.x` Releases - [3.2.0](#320) - `3.1.x` Releases - [3.1.0](#310) - `3.0.x` Releases - [3.0.0](#300) @@ -20,18 +21,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - `2.9.x` Releases - [2.9.0](#290) - `2.8.x` Releases - [2.8.0](#280) - `2.7.x` Releases - [2.7.0](#270) -- `2.6.x` Releases - [2.6.1](#261) | [2.6.0](#260) +- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261) - `2.5.x` Releases - [2.5.0](#250) -- `2.4.x` Releases - [2.4.2](#242) | [2.4.1](#241) | [2.4.0](#240) -- `2.3.x` Releases - [2.3.1](#231) | [2.3.0](#230) +- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242) +- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231) - `2.2.x` Releases - [2.2.0](#220) - `2.1.x` Releases - [2.1.0](#210) -- `2.0.x` Releases - [2.0.3](#203) | [2.0.2](#202) | [2.0.1](#201) | [2.0.0](#200) +- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203) #### 1.x Releases - `1.3.x` Releases - [1.3.0](#130) -- `1.2.x` Releases - [1.2.2](#122) | [1.2.1](#121) | [1.2.0](#120) +- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122) - `1.1.x` Releases - [1.1.0](#110) - `1.0.x` Releases - [1.0.0](#100) From 54361617fe702b965e97013ecbf9d10677cfdb87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 09:33:55 +0100 Subject: [PATCH 059/118] Remove headers --- .../QueryInterface/Association/AssociationAggregate.swift | 8 -------- GRDB/Utils/Inflections.swift | 8 -------- GRDB/Utils/OrderedDictionary.swift | 8 -------- GRDB/ValueObservation/ValueObservation+Combine.swift | 8 -------- GRDB/ValueObservation/ValueObservation+Count.swift | 8 -------- .../ValueObservation+DatabaseValueConvertible.swift | 8 -------- .../ValueObservation+FetchableRecord.swift | 8 -------- GRDB/ValueObservation/ValueObservation+Map.swift | 8 -------- GRDB/ValueObservation/ValueObservation+Row.swift | 8 -------- GRDB/ValueObservation/ValueObservation.swift | 8 -------- GRDB/ValueObservation/ValueReducer.swift | 8 -------- .../GRDBProfiling/GRDBProfiling/AppDelegate.swift | 8 -------- .../GRDBProfiling/GRDBProfiling/ViewController.swift | 8 -------- 13 files changed, 104 deletions(-) diff --git a/GRDB/QueryInterface/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Association/AssociationAggregate.swift index 6b4ce2bc7..faeb31476 100644 --- a/GRDB/QueryInterface/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Association/AssociationAggregate.swift @@ -1,11 +1,3 @@ -// -// AssociationAggregate.swift -// GRDB -// -// Created by Gwendal RouĂ© on 30/09/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - import Foundation /// An AssociationAggregate is able to compute aggregated values from a diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index fc19958ec..d5f1f8637 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -1,11 +1,3 @@ -// -// Inflections.swift -// GRDB -// -// Created by Gwendal RouĂ© on 01/10/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - import Foundation extension String { diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index bf00bb3d5..6fc1cfc4b 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -1,11 +1,3 @@ -// -// OrderedDictionary.swift -// GRDB -// -// Created by Gwendal RouĂ© on 29/09/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - struct OrderedDictionary { private var keys: [Key] private var values: [Key: Value] diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift index 988c6f1d9..070506973 100644 --- a/GRDB/ValueObservation/ValueObservation+Combine.swift +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+Combine.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer == Void { public static func combine( _ o1: ValueObservation, diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift index cdde780cc..f455db68f 100644 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+Count.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer == Void { // MARK: - Count Observation diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index c440567e6..95df5707c 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+DatabaseValueConvertible.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer == Void { // MARK: - DatabaseValueConvertible Observation diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index 6ca6ca16f..3d3999861 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+FetchableRecord.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer == Void { // MARK: - FetchableRecord Observation diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift index 24cde5bcd..39983568c 100644 --- a/GRDB/ValueObservation/ValueObservation+Map.swift +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+Map.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer: ValueReducer { /// Returns a ValueObservation which transforms the values returned by /// this ValueObservation. diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 1b3cc0300..35dee402f 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -1,11 +1,3 @@ -// -// ValueObservation+Row.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - extension ValueObservation where Reducer == Void { // MARK: - Row Observation diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 22da33b42..1f4f7289b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -1,11 +1,3 @@ -// -// ValueObservation.swift -// GRDB -// -// Created by Gwendal RouĂ© on 23/10/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - import Dispatch // MARK: - ValueScheduling diff --git a/GRDB/ValueObservation/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer.swift index 91bcd05a0..b2fcc9b12 100644 --- a/GRDB/ValueObservation/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer.swift @@ -1,11 +1,3 @@ -// -// ValueReducer.swift -// GRDB -// -// Created by Gwendal RouĂ© on 24/11/2018. -// Copyright © 2018 Gwendal RouĂ©. All rights reserved. -// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The ValueReducer protocol supports ValueObservation. diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index 44eecc8a3..d28fcb6f4 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -1,11 +1,3 @@ -// -// AppDelegate.swift -// GRDBProfiling -// -// Created by Gwendal RouĂ© on 15/09/2015. -// Copyright © 2015 Gwendal RouĂ©. All rights reserved. -// - import Cocoa import GRDB diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift index 7bf4397e5..fed4f07a5 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift @@ -1,11 +1,3 @@ -// -// ViewController.swift -// GRDBProfiling -// -// Created by Gwendal RouĂ© on 15/09/2015. -// Copyright © 2015 Gwendal RouĂ©. All rights reserved. -// - import Cocoa class ViewController: NSViewController { From 798b727d7fba9b889f8500107f2ff7ed5408e6d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 09:35:04 +0100 Subject: [PATCH 060/118] Reducer queue honors qos and targetQueue configuration --- GRDB.xcodeproj/project.pbxproj | 8 ++ GRDB/Core/DatabaseWriter.swift | 92 +--------------------- GRDB/ValueObservation/ValueObserver.swift | 94 +++++++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 12 ++- GRDBCustom.xcodeproj/project.pbxproj | 12 ++- 5 files changed, 121 insertions(+), 97 deletions(-) create mode 100644 GRDB/ValueObservation/ValueObserver.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 860edfe48..fe150f1e2 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -201,6 +201,9 @@ 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; }; + 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -960,6 +963,7 @@ 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1389,6 +1393,7 @@ 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */, 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */, + 564CE43021AA901800652B19 /* ValueObserver.swift */, 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, ); path = ValueObservation; @@ -2468,6 +2473,7 @@ 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, + 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, @@ -2605,6 +2611,7 @@ 5605F1641C672E4000235C62 /* Date.swift in Sources */, 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -3152,6 +3159,7 @@ 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, + 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */, diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bbf25c575..f63a2be80 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -243,7 +243,7 @@ extension DatabaseWriter { let valueObserver = try ValueObserver( region: observation.observedRegion(db), reducer: reducer, - reducerQoS: db.configuration.qos, + configuration: db.configuration, fetch: observation.fetchAfterChange(in: self), notificationQueue: observation.notificationQueue, onError: onError, @@ -295,96 +295,6 @@ extension ValueObservation where Reducer: ValueReducer { } } - -/// Support for ValueObservation. -/// See DatabaseWriter.add(observation:onError:onChange:) -/// 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? - private let onError: ((Error) -> Void)? - private let onChange: (Reducer.Value) -> Void - private let reduceQueue: DispatchQueue - private var isChanged = false - - init( - region: DatabaseRegion, - reducer: Reducer, - reducerQoS: DispatchQoS, - fetch: @escaping (Database, Reducer) -> Future, - notificationQueue: DispatchQueue?, - onError: ((Error) -> Void)?, - onChange: @escaping (Reducer.Value) -> Void) - { - self.region = region - self.reducer = reducer - self.fetch = fetch - self.notificationQueue = notificationQueue - self.onChange = onChange - self.onError = onError - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation.Reducer", qos: reducerQoS) - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - isChanged = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidCommit(_ db: Database) { - guard isChanged else { return } - isChanged = false - - // Grab future fetched values from the database writer queue - let future = fetch(db, reducer) - - // Wait for future fetched values in reduceQueue. This guarantees: - // - that notifications have the same ordering as transactions. - // - that expensive reduce operations are computed without blocking - // any database dispatch queue. - reduceQueue.async { [weak self] in - guard let strongSelf = self else { return } - - do { - if let value = try strongSelf.reducer.value(future.wait()) { - if let queue = strongSelf.notificationQueue { - queue.async { - guard let strongSelf = self else { return } - strongSelf.onChange(value) - } - } else { - strongSelf.onChange(value) - } - } - } catch { - guard strongSelf.onError != nil else { - // TODO: how can we let the user know about the error? - return - } - if let queue = strongSelf.notificationQueue { - queue.async { - guard let strongSelf = self else { return } - strongSelf.onError?(error) - } - } else { - strongSelf.onError?(error) - } - } - } - } - - func databaseDidRollback(_ db: Database) { - isChanged = false - } -} - /// A future value. public class Future { private var consumed = false diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift new file mode 100644 index 000000000..e0392bd78 --- /dev/null +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -0,0 +1,94 @@ +import Foundation + +/// Support for ValueObservation. +/// See DatabaseWriter.add(observation:onError:onChange:) +class ValueObserver: TransactionObserver { + /* private */ let region: DatabaseRegion // Internal for testability + private var reducer: Reducer + private let fetch: (Database, Reducer) -> Future + private let notificationQueue: DispatchQueue? + private let onError: ((Error) -> Void)? + private let onChange: (Reducer.Value) -> Void + private let reduceQueue: DispatchQueue + private var isChanged = false + + init( + region: DatabaseRegion, + reducer: Reducer, + configuration: Configuration, + fetch: @escaping (Database, Reducer) -> Future, + notificationQueue: DispatchQueue?, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + { + self.region = region + self.reducer = reducer + self.fetch = fetch + self.notificationQueue = notificationQueue + self.onChange = onChange + self.onError = onError + let reduceQueueLabel = (configuration.label ?? "GRDB") + ".ValueObservation.reducer" + if let targetQueue = configuration.targetQueue { + self.reduceQueue = DispatchQueue(label: reduceQueueLabel, target: targetQueue) + } else { + self.reduceQueue = DispatchQueue(label: reduceQueueLabel, qos: configuration.qos) + } + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + isChanged = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidCommit(_ db: Database) { + guard isChanged else { return } + isChanged = false + + // Grab future fetched values from the database writer queue + let future = fetch(db, reducer) + + // Wait for future fetched values in reduceQueue. This guarantees: + // - that notifications have the same ordering as transactions. + // - that expensive reduce operations are computed without blocking + // any database dispatch queue. + reduceQueue.async { [weak self] in + guard let strongSelf = self else { return } + + do { + if let value = try strongSelf.reducer.value(future.wait()) { + if let queue = strongSelf.notificationQueue { + queue.async { + guard let strongSelf = self else { return } + strongSelf.onChange(value) + } + } else { + strongSelf.onChange(value) + } + } + } catch { + guard strongSelf.onError != nil else { + // TODO: how can we let the user know about the error? + return + } + if let queue = strongSelf.notificationQueue { + queue.async { + guard let strongSelf = self else { return } + strongSelf.onError?(error) + } + } else { + strongSelf.onError?(error) + } + } + } + } + + func databaseDidRollback(_ db: Database) { + isChanged = false + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index d0d429670..575827a73 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -260,6 +260,8 @@ 5644DE8320F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8420F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; + 564CE44021AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; + 564CE44121AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1071,6 +1073,7 @@ 5644DE7A20F8C903001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43F21AA957000652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1465,12 +1468,13 @@ children = ( 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */, 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */, + 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, + 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */, 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */, - 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, - 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE43F21AA957000652B19 /* ValueObserver.swift */, 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */, - 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, ); path = ValueObservation; sourceTree = ""; @@ -2371,6 +2375,7 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE44021AA957000652B19 /* ValueObserver.swift in Sources */, 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, @@ -2848,6 +2853,7 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE44121AA957000652B19 /* ValueObserver.swift in Sources */, 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index c2bdf9df6..757d6c871 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -95,6 +95,8 @@ 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; }; 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; + 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; + 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -712,6 +714,7 @@ 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1072,12 +1075,13 @@ children = ( 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */, + 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, + 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */, 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */, - 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, - 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE43B21AA955B00652B19 /* ValueObserver.swift */, 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */, - 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, ); path = ValueObservation; sourceTree = ""; @@ -2014,6 +2018,7 @@ 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */, 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, @@ -2314,6 +2319,7 @@ 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, From 2e3f2f9d611f9f32acaf02390c5ef164192fd525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 09:35:17 +0100 Subject: [PATCH 061/118] Tests for reducer queue labels --- .../ValueObservationReducerTests.swift | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 5c8974c64..df6b74007 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -1,4 +1,5 @@ import XCTest +import Dispatch #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE @@ -328,4 +329,58 @@ class ValueObservationReducerTests: GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + + func testReducerQueueLabel() throws { + func test(_ dbWriter: DatabaseWriter, expectedLabels: [String]) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let reduceExpectation = expectation(description: "notification") + reduceExpectation.assertForOverFulfill = true + reduceExpectation.expectedFulfillmentCount = expectedLabels.count + + var labels: [String] = [] + let reducer = AnyValueReducer(fetch: { _ in }, value: { _ in + // This test CAN break in future releases: the dispatch queue labels + // are documented to be a debug-only tool. + if let label = String(utf8String: __dispatch_queue_get_label(nil)) { + labels.append(label) + } + reduceExpectation.fulfill() + }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter, onChange: { _ in }) + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(labels, expectedLabels) + } + do { + // dbQueue with default label + dbConfiguration.label = nil + let dbQueue = try makeDatabaseQueue() + try test(dbQueue, expectedLabels: ["GRDB.DatabaseQueue", "GRDB.ValueObservation.reducer"]) + } + do { + // dbQueue with custom label + dbConfiguration.label = "Custom" + let dbQueue = try makeDatabaseQueue() + try test(dbQueue, expectedLabels: ["Custom", "Custom.ValueObservation.reducer"]) + } + do { + // dbPool with default label + dbConfiguration.label = nil + let dbPool = try makeDatabasePool() + try test(dbPool, expectedLabels: ["GRDB.DatabasePool.writer", "GRDB.ValueObservation.reducer"]) + } + do { + // dbPool with custom label + dbConfiguration.label = "Custom" + let dbPool = try makeDatabasePool() + try test(dbPool, expectedLabels: ["Custom.writer", "Custom.ValueObservation.reducer"]) + } + } } From 87c47754210f2536899c588464848fb7491563fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 14:26:04 +0100 Subject: [PATCH 062/118] ValueObservation creates a reducer when its starts --- GRDB/Core/DatabaseRegion.swift | 18 ++++ GRDB/Core/DatabaseSnapshot.swift | 18 ++-- GRDB/Core/DatabaseWriter.swift | 26 +++--- .../ValueObservation+Combine.swift | 88 +++++++++---------- .../ValueObservation+Map.swift | 3 +- GRDB/ValueObservation/ValueObservation.swift | 29 +++--- 6 files changed, 99 insertions(+), 83 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index eeaad7a68..737cfd8fc 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -344,3 +344,21 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { return try _region(db) } } + +// MARK: - Utils + +extension DatabaseRegion { + static func union(_ regions: DatabaseRegion...) -> DatabaseRegion { + return regions.reduce(into: DatabaseRegion()) { union, region in + union.formUnion(region) + } + } + + static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + return { db in + try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region.databaseRegion(db)) + } + } + } +} diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index aa85413ca..305738bb8 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -106,8 +106,7 @@ extension DatabaseSnapshot { // Deal with initial value switch observation.scheduling { case .mainQueue: - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { if DispatchQueue.isMain { onChange(value) } else { @@ -118,8 +117,7 @@ extension DatabaseSnapshot { } case let .onQueue(queue, startImmediately: startImmediately): if startImmediately { - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { queue.async { onChange(value) } @@ -127,8 +125,7 @@ extension DatabaseSnapshot { } case let .unsafe(startImmediately: startImmediately): if startImmediately { - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { onChange(value) } } @@ -143,6 +140,15 @@ extension DatabaseSnapshot { } } +extension ValueObservation where Reducer: ValueReducer { + /// Helper method for DatabaseSnapshot.add(observation:onError:onChange:) + fileprivate func initialValue(_ db: Database) throws -> Reducer.Value? { + var reducer = try makeReducer(db) + let fetched = try reducer.fetch(db) + return reducer.value(fetched) + } +} + /// An observer that does nothing, support for /// `DatabaseSnapshot.add(observation:onError:onChange:)`. private class SnapshotValueObserver: TransactionObserver { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index f63a2be80..b1e531940 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -215,12 +215,14 @@ extension DatabaseWriter { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try unsafeReentrantWrite { db in + // Create the reducer + var reducer = try observation.makeReducer(db) + // Take care of initial value. Make sure it is dispatched before // any future transaction can trigger a change. - var reducer = observation.reducer switch observation.scheduling { case .mainQueue: - if let value = try reducer.value(observation.fetchInitial(db)) { + if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) { if calledOnMainQueue { startValue = value } else { @@ -229,13 +231,13 @@ extension DatabaseWriter { } case let .onQueue(queue, startImmediately: startImmediately): if startImmediately { - if let value = try reducer.value(observation.fetchInitial(db)) { + if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) { queue.async { onChange(value) } } } case let .unsafe(startImmediately: startImmediately): if startImmediately { - startValue = try reducer.value(observation.fetchInitial(db)) + startValue = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) } } @@ -255,21 +257,23 @@ extension DatabaseWriter { } } -extension ValueObservation where Reducer: ValueReducer { +extension ValueReducer { /// Helper method for DatabaseWriter.add(observation:onError:onChange:) - fileprivate func fetchInitial(_ db: Database) throws -> Reducer.Fetched { + fileprivate mutating func initialValue(_ db: Database, requiresWriteAccess: Bool) throws -> Value? { if requiresWriteAccess { - var fetchedValue: Reducer.Fetched! + var fetchedValue: Fetched! try db.inSavepoint { - fetchedValue = try reducer.fetch(db) + fetchedValue = try fetch(db) return .commit } - return fetchedValue + return value(fetchedValue) } else { - return try db.readOnly { try reducer.fetch(db) } + return try value(db.readOnly { try fetch(db) }) } } - +} + +extension ValueObservation where Reducer: ValueReducer { /// Helper method for DatabaseWriter.add(observation:onError:onChange:) fileprivate func fetchAfterChange(in writer: DatabaseWriter) -> (Database, Reducer) -> Future { // The technique to return a future value after database has changed diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift index 070506973..64979a307 100644 --- a/GRDB/ValueObservation/ValueObservation+Combine.swift +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -8,13 +8,13 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion]), - reducer: ValueReducers.combine( - o1.reducer, - o2.reducer)) + (R1.Value, R2.Value)>>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0)) }, + reducer: { try ValueReducers.combine( + o1.makeReducer($0), + o2.makeReducer($0)) }) } public static func combine( @@ -27,15 +27,15 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion]), - reducer: ValueReducers.combine( - o1.reducer, - o2.reducer, - o3.reducer)) + (R1.Value, R2.Value, R3.Value)>>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0)) }, + reducer: { try ValueReducers.combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0)) }) } public static func combine( @@ -49,17 +49,17 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion, - o4.observedRegion]), - reducer: ValueReducers.combine( - o1.reducer, - o2.reducer, - o3.reducer, - o4.reducer)) + (R1.Value, R2.Value, R3.Value, R4.Value)>>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0), + o4.observedRegion($0)) }, + reducer: { try ValueReducers.combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0), + o4.makeReducer($0)) }) } public static func combine( @@ -74,19 +74,19 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.init( - tracking: union([ - o1.observedRegion, - o2.observedRegion, - o3.observedRegion, - o4.observedRegion, - o5.observedRegion]), - reducer: ValueReducers.combine( - o1.reducer, - o2.reducer, - o3.reducer, - o4.reducer, - o5.reducer)) + (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)>>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0), + o4.observedRegion($0), + o5.observedRegion($0)) }, + reducer: { try ValueReducers.combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0), + o4.makeReducer($0), + o5.makeReducer($0)) }) } } @@ -273,11 +273,3 @@ extension ValueReducers { return AnyValueReducer(fetch: fetch, value: value) } } - -private func union(_ regions: [(Database) throws -> DatabaseRegion]) -> (Database) throws -> DatabaseRegion { - return { db in - try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region(db)) - } - } -} diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift index 39983568c..ba2834598 100644 --- a/GRDB/ValueObservation/ValueObservation+Map.swift +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -4,9 +4,10 @@ extension ValueObservation where Reducer: ValueReducer { public func map(_ transform: @escaping (Reducer.Value) -> T) -> ValueObservation> { + let makeReducer = self.makeReducer return ValueObservation>( tracking: observedRegion, - reducer: reducer.map(transform)) + reducer: { db in try makeReducer(db).map(transform) }) } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 1f4f7289b..477082c3b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -77,8 +77,9 @@ public struct ValueObservation { /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion - /// The reducer is triggered upon each database change in *observedRegion*. - var reducer: Reducer + /// The reducer is created when observation starts, and is triggered upon + /// each database change in *observedRegion*. + var makeReducer: (Database) throws -> Reducer /// Default is false. Set this property to true when the observation /// requires write access in order to fetch fresh values. Fetches are then @@ -166,7 +167,7 @@ public struct ValueObservation { // Not public. See ValueObservation.tracking(_:reducer:) init( tracking region: @escaping (Database) throws -> DatabaseRegion, - reducer: Reducer) + reducer: @escaping (Database) throws -> Reducer) { self.observedRegion = { db in // Remove views from the observed region. @@ -177,7 +178,7 @@ public struct ValueObservation { let views = try db.schema().names(ofType: .view) return try region(db).ignoring(views) } - self.reducer = reducer + self.makeReducer = reducer } } @@ -287,7 +288,9 @@ extension ValueObservation { reducer: Reducer) -> ValueObservation { - return ValueObservation(tracking: union(regions), reducer: reducer) + return ValueObservation( + tracking: DatabaseRegion.union(regions), + reducer: { _ in reducer }) } } @@ -359,8 +362,8 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Raw(fetch)) + tracking: DatabaseRegion.union(regions), + reducer: { _ in ValueReducers.Raw(fetch) }) } /// Creates a ValueObservation which observes *regions*, and notifies the @@ -431,15 +434,7 @@ extension ValueObservation where Reducer == Void { where Value: Equatable { return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Distinct(fetch)) - } -} - -private func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { - return { db in - try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } + tracking: DatabaseRegion.union(regions), + reducer: { _ in ValueReducers.Distinct(fetch) }) } } From 3f001ba04de1e04d7a62ec43e4b6675e4be5ae2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 15:18:03 +0100 Subject: [PATCH 063/118] ValueObservation now accept a reducer factory --- ...Observation+DatabaseValueConvertible.swift | 6 +-- .../ValueObservation+FetchableRecord.swift | 4 +- GRDB/ValueObservation/ValueObservation.swift | 6 +-- README.md | 27 ++++++++----- .../ValueObservationExtentTests.swift | 6 +-- .../ValueObservationReducerTests.swift | 40 +++++++++---------- .../ValueObservationSchedulingTests.swift | 6 +-- 7 files changed, 49 insertions(+), 46 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 95df5707c..f92572f05 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -32,7 +32,7 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.tracking( request, - reducer: ValueReducers.Values { try DatabaseValue.fetchAll($0, request) }) + reducer: { _ in ValueReducers.Values { try DatabaseValue.fetchAll($0, request) } }) } /// Creates a ValueObservation which observes *request*, and notifies a @@ -64,7 +64,7 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.tracking( request, - reducer: ValueReducers.Value { try DatabaseValue.fetchOne($0, request) }) + reducer: { _ in ValueReducers.Value { try DatabaseValue.fetchOne($0, request) } }) } /// Creates a ValueObservation which observes *request*, and notifies @@ -98,7 +98,7 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.tracking( request, - reducer: ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) }) + reducer: { _ in ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) } }) } } diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index 3d3999861..6b30f1ce1 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -32,7 +32,7 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.tracking( request, - reducer: ValueReducers.Records { try Row.fetchAll($0, request) }) + reducer: { _ in ValueReducers.Records { try Row.fetchAll($0, request) } }) } /// Creates a ValueObservation which observes *request*, and notifies a @@ -64,7 +64,7 @@ extension ValueObservation where Reducer == Void { { return ValueObservation>.tracking( request, - reducer: ValueReducers.Record { try Row.fetchOne($0, request) }) + reducer: { _ in ValueReducers.Record { try Row.fetchOne($0, request) } }) } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 477082c3b..a2ac29c9c 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -243,7 +243,7 @@ extension ValueObservation { /// the ValueReducer protocol are supported. public static func tracking( _ regions: DatabaseRegionConvertible..., - reducer: Reducer) + reducer: @escaping (Database) -> Reducer) -> ValueObservation { return ValueObservation.tracking(regions, reducer: reducer) @@ -285,12 +285,12 @@ extension ValueObservation { /// the ValueReducer protocol are supported. public static func tracking( _ regions: [DatabaseRegionConvertible], - reducer: Reducer) + reducer: @escaping (Database) -> Reducer) -> ValueObservation { return ValueObservation( tracking: DatabaseRegion.union(regions), - reducer: { _ in reducer }) + reducer: reducer) } } diff --git a/README.md b/README.md index 12d17bdb7..a418cbefa 100644 --- a/README.md +++ b/README.md @@ -6566,17 +6566,22 @@ The sample code below counts the number of times the player table is modified: ```swift var count = 0 -let reducer = AnyValueReducer( - fetch: { _ in }, - value: { _ -> Int? in - count += 1 - return count - }) -let observer = ValueObservation - .tracking(Player.all(), reducer: reducer) - .start(in: dbQueue) { count: Int in - print("Players have been modified \(count) times.") - } +let observation = ValueObservation.tracking(Player.all(), reducer: { _ in + AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) +}) +let observer = observation.start(in: dbQueue) { count: Int in + print("\(count) transaction(s) have modified the players.") +} +// Prints "0 transaction(s) have modified the players." + +try dbQueue.write { db in + try Player(...).insert(db) +} +// Prints "1 transaction(s) have modified the players." ``` diff --git a/Tests/GRDBTests/ValueObservationExtentTests.swift b/Tests/GRDBTests/ValueObservationExtentTests.swift index 253507f6f..5060c9fc4 100644 --- a/Tests/GRDBTests/ValueObservationExtentTests.swift +++ b/Tests/GRDBTests/ValueObservationExtentTests.swift @@ -34,7 +34,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime // Start observation @@ -72,7 +72,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .observerLifetime // Start observation and deallocate observer after second change @@ -118,7 +118,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .nextTransaction // Start observation diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index df6b74007..001e850ff 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -18,11 +18,11 @@ class ValueObservationReducerTests: GRDBTestCase { let reducer = AnyValueReducer(fetch: { _ in }, value: { }) // single region - _ = ValueObservation.tracking(DatabaseRegion(), reducer: reducer) + _ = ValueObservation.tracking(DatabaseRegion(), reducer: { _ in reducer }) // variadic - _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), reducer: reducer) + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), reducer: { _ in reducer }) // array - _ = ValueObservation.tracking([DatabaseRegion()], reducer: reducer) + _ = ValueObservation.tracking([DatabaseRegion()], reducer: { _ in reducer }) } func testReducer() throws { @@ -58,7 +58,7 @@ class ValueObservationReducerTests: GRDBTestCase { // Create an observation let request = SQLRequest("SELECT * FROM t") - var observation = ValueObservation.tracking(request, reducer: reducer) + var observation = ValueObservation.tracking(request, reducer: { _ in reducer }) observation.extent = .databaseLifetime // Start observation @@ -133,7 +133,7 @@ class ValueObservationReducerTests: GRDBTestCase { value: { _ in fatalError() }) // Create an observation - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) // Start observation do { @@ -174,7 +174,7 @@ class ValueObservationReducerTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime // Start observation @@ -218,17 +218,15 @@ class ValueObservationReducerTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 - // The reducer - var count = 0 - let reducer = AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - count += 1 - return count - }) - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var count = 0 + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in + AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) + }) observation.extent = .databaseLifetime // Start observation @@ -242,7 +240,7 @@ class ValueObservationReducerTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1, 2]) + XCTAssertEqual(counts, [0, 1]) } try test(makeDatabaseQueue()) @@ -262,7 +260,7 @@ class ValueObservationReducerTests: GRDBTestCase { // The base reducer var count = 0 - let reducer = AnyValueReducer( + let baseReducer = AnyValueReducer( fetch: { _ in /* don't fetch anything */ }, value: { _ -> Int? in count += 1 @@ -270,13 +268,13 @@ class ValueObservationReducerTests: GRDBTestCase { }) // The mapped reducer - let mapReducer = reducer.map { count -> String? in + let reducer = baseReducer.map { count -> String? in if count % 2 == 0 { return nil } return "\(count)" } // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: mapReducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime // Start observation @@ -347,7 +345,7 @@ class ValueObservationReducerTests: GRDBTestCase { } reduceExpectation.fulfill() }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime _ = try observation.start(in: dbWriter, onChange: { _ in }) diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index 03c89f55e..fe1251eba 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -113,7 +113,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { } }, value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime _ = try observation.start( @@ -236,7 +236,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { let reducer = AnyValueReducer( fetch: { _ in throw TestError() }, value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime observation.scheduling = .onQueue(queue, startImmediately: false) @@ -391,7 +391,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { let reducer = AnyValueReducer( fetch: { _ in throw TestError() }, value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime observation.scheduling = .unsafe(startImmediately: false) From 1b53bf9ea200f39fac9cd104aa084203ae12a3ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 15:27:26 +0100 Subject: [PATCH 064/118] Documentation --- GRDB/ValueObservation/ValueObservation.swift | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index a2ac29c9c..dc5ae3d68 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -217,13 +217,13 @@ extension ValueObservation { /// table is modified: /// /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count + /// let observation = ValueObservation.tracking(Player.all(), reducer: ( db in + /// AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count }) /// }) - /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) /// let observer = observation.start(in: dbQueue) { count: Int in /// print("Players have been modified \(count) times.") /// } @@ -259,13 +259,13 @@ extension ValueObservation { /// table is modified: /// /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count + /// let observation = ValueObservation.tracking([Player.all()], reducer: ( db in + /// AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count }) /// }) - /// let observation = ValueObservation.tracking([Player.all()], reducer: reducer) /// let observer = observation.start(in: dbQueue) { count: Int in /// print("Players have been modified \(count) times.") /// } From e092e8b3ec2444fc74d125f9d5cea1fdf7bda43a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 15:42:34 +0100 Subject: [PATCH 065/118] CHANGELOG --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09a43039b..f20501bd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. +### Breaking Change + +- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation + + ### Documentation Diff - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. @@ -78,7 +83,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). struct ValueObservation { + static func tracking( + _ regions: [DatabaseRegionConvertible], -+ reducer: Reducer) ++ reducer: @escaping (Database) -> Reducer) + -> ValueObservation } From 3dcae6d4099e358d2c4587b59db12ba7b41f309a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Nov 2018 18:35:05 +0100 Subject: [PATCH 066/118] Forgot that reducer factory closure throws --- CHANGELOG.md | 2 +- GRDB/ValueObservation/ValueObservation.swift | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f20501bd4..9da5d953c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,7 +83,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). struct ValueObservation { + static func tracking( + _ regions: [DatabaseRegionConvertible], -+ reducer: @escaping (Database) -> Reducer) ++ reducer: @escaping (Database) throws -> Reducer) + -> ValueObservation } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index dc5ae3d68..e6727c8a9 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -243,7 +243,7 @@ extension ValueObservation { /// the ValueReducer protocol are supported. public static func tracking( _ regions: DatabaseRegionConvertible..., - reducer: @escaping (Database) -> Reducer) + reducer: @escaping (Database) throws -> Reducer) -> ValueObservation { return ValueObservation.tracking(regions, reducer: reducer) @@ -285,7 +285,7 @@ extension ValueObservation { /// the ValueReducer protocol are supported. public static func tracking( _ regions: [DatabaseRegionConvertible], - reducer: @escaping (Database) -> Reducer) + reducer: @escaping (Database) throws -> Reducer) -> ValueObservation { return ValueObservation( From 32f1a7ae0f641cedcf028a8608e33058435055c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Nov 2018 08:34:32 +0100 Subject: [PATCH 067/118] Fix JSON encoding of empty arrays and dictionaries --- GRDB/Record/PersistableRecord+Encodable.swift | 19 +++- .../FetchableRecordDecodableTests.swift | 38 ++++++-- ...tablePersistableRecordEncodableTests.swift | 96 +++++++++++++++++++ 3 files changed, 143 insertions(+), 10 deletions(-) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 7533695dc..9c9cbcc63 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -140,6 +140,16 @@ private class RecordEncoder: Encoder { // error happens, we'll switch to JSON encoding. let encoder = ColumnEncoder(recordEncoder: self, key: key) try value.encode(to: encoder) + if let jsonContainer = encoder.requestedJSONContainer { + switch jsonContainer { + case .keyed: + // Empty dictionary + persist("{}", forKey: key) + case .unkeyed: + // Empty array + persist("[]", forKey: key) + } + } } catch is JSONRequiredError { // Encode to JSON let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) @@ -159,11 +169,16 @@ private class RecordEncoder: Encoder { // MARK: - ColumnEncoder /// The encoder that encodes into a database column -private struct ColumnEncoder: Encoder { +private class ColumnEncoder: Encoder { + enum RequestedJSONContainer { + case keyed + case unkeyed + } var recordEncoder: RecordEncoder var key: CodingKey var codingPath: [CodingKey] { return [key] } var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var requestedJSONContainer: RequestedJSONContainer? init(recordEncoder: RecordEncoder, key: CodingKey) { self.recordEncoder = recordEncoder @@ -174,6 +189,7 @@ private struct ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. + requestedJSONContainer = .keyed let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -182,6 +198,7 @@ private struct ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. + requestedJSONContainer = .unkeyed return JSONRequiredEncoder(codingPath: codingPath) } diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index fcfdc109f..1722d5eb4 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -477,24 +477,44 @@ extension FetchableRecordDecodableTests { try db.create(table: "t1") { t in t.column("nested", .text) } - - let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") - let value = StructWithNestedType(nested: [nested, nested]) + } + + try dbQueue.inTransaction { db in + let value = StructWithNestedType(nested: [ + NestedStruct(firstName: "Bob", lastName: "Dylan"), + NestedStruct(firstName: "Bob", lastName: "Dylan")]) try value.insert(db) - let parentModel = try StructWithNestedType.fetchAll(db) + let parentModel = try StructWithNestedType.fetchOne(db) - guard let arrayOfNestedModel = parentModel.first?.nested, let firstNestedModelInArray = arrayOfNestedModel.first else { + guard let nested = parentModel?.nested else { XCTFail() - return + return .rollback } // Check there are two models in array - XCTAssertTrue(arrayOfNestedModel.count == 2) + XCTAssertEqual(nested.count, 2) // Check the nested model contains the expected values of first and last name - XCTAssertEqual(firstNestedModelInArray.firstName, "Bob") - XCTAssertEqual(firstNestedModelInArray.lastName, "Dylan") + XCTAssertEqual(nested[0].firstName, "Bob") + XCTAssertEqual(nested[0].lastName, "Dylan") + + return .rollback + } + + try dbQueue.inTransaction { db in + let value = StructWithNestedType(nested: []) + try value.insert(db) + + let parentModel = try StructWithNestedType.fetchOne(db) + + guard let nested = parentModel?.nested else { + XCTFail() + return .rollback + } + + XCTAssertTrue(nested.isEmpty) + return .rollback } } diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 65ac337a6..6d166a88e 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -416,6 +416,102 @@ extension MutablePersistableRecordEncodableTests { } } + func testArrayJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let array: [String] + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("array", .text) + } + + try Record(array: []).insert(db) + try Record(array: ["foo"]).insert(db) + try Record(array: ["foo", "bar"]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 3) + XCTAssertEqual(rows[0]["array"], "[]") + XCTAssertEqual(rows[1]["array"], "[\"foo\"]") + XCTAssertEqual(rows[2]["array"], "[\"foo\",\"bar\"]") + } + } + + func testOptionalArrayJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let array: [String]? + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("array", .text) + } + + try Record(array: nil).insert(db) + try Record(array: []).insert(db) + try Record(array: ["foo"]).insert(db) + try Record(array: ["foo", "bar"]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 4) + XCTAssertTrue(rows[0]["array"] == nil) + XCTAssertEqual(rows[1]["array"], "[]") + XCTAssertEqual(rows[2]["array"], "[\"foo\"]") + XCTAssertEqual(rows[3]["array"], "[\"foo\",\"bar\"]") + } + } + + func testDictionaryJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let dictionary: [String: Int] + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("dictionary", .text) + } + + try Record(dictionary: [:]).insert(db) + try Record(dictionary: ["foo": 1]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["dictionary"], "{}") + XCTAssertEqual(rows[1]["dictionary"], "{\"foo\":1}") + } + } + + func testOptionalDictionaryJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let dictionary: [String: Int]? + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("dictionary", .text) + } + + try Record(dictionary: nil).insert(db) + try Record(dictionary: [:]).insert(db) + try Record(dictionary: ["foo": 1]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 3) + XCTAssertTrue(rows[0]["dictionary"] == nil) + XCTAssertEqual(rows[1]["dictionary"], "{}") + XCTAssertEqual(rows[2]["dictionary"], "{\"foo\":1}") + } + } + func testJSONDataEncodingStrategy() throws { struct Record: PersistableRecord, Encodable { let data: Data From e8ad816de56e0c3daf16785f6d5a3614f98014e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Nov 2018 08:41:30 +0100 Subject: [PATCH 068/118] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9da5d953c..c4f01e5b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). ## Next Version +### Fixed + +- [#449](https://github.com/groue/GRDB.swift/pull/449): Fix JSON encoding of empty containers + + ### New - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex From f41112c07144d67d2bd9ef3b364a741a6d57557b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Nov 2018 08:46:48 +0100 Subject: [PATCH 069/118] Documentation --- GRDB/Record/PersistableRecord+Encodable.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 9c9cbcc63..200fe4292 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -141,6 +141,9 @@ private class RecordEncoder: Encoder { let encoder = ColumnEncoder(recordEncoder: self, key: key) try value.encode(to: encoder) if let jsonContainer = encoder.requestedJSONContainer { + // No JSONRequiredError was thrown, but the encoder was + // asked a json container. This means that value is an + // empty container. Let's encode it: switch jsonContainer { case .keyed: // Empty dictionary From ef54efcb75685447168f86dcd593d4d7cd0157ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Nov 2018 09:11:36 +0100 Subject: [PATCH 070/118] Cleanup --- GRDB/Record/PersistableRecord+Encodable.swift | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 200fe4292..b3abf3782 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -140,18 +140,9 @@ private class RecordEncoder: Encoder { // error happens, we'll switch to JSON encoding. let encoder = ColumnEncoder(recordEncoder: self, key: key) try value.encode(to: encoder) - if let jsonContainer = encoder.requestedJSONContainer { - // No JSONRequiredError was thrown, but the encoder was - // asked a json container. This means that value is an - // empty container. Let's encode it: - switch jsonContainer { - case .keyed: - // Empty dictionary - persist("{}", forKey: key) - case .unkeyed: - // Empty array - persist("[]", forKey: key) - } + if encoder.requiresJSON { + // Here we handle empty arrays and dictionaries. + throw JSONRequiredError() } } catch is JSONRequiredError { // Encode to JSON @@ -173,15 +164,11 @@ private class RecordEncoder: Encoder { /// The encoder that encodes into a database column private class ColumnEncoder: Encoder { - enum RequestedJSONContainer { - case keyed - case unkeyed - } var recordEncoder: RecordEncoder var key: CodingKey var codingPath: [CodingKey] { return [key] } var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } - var requestedJSONContainer: RequestedJSONContainer? + var requiresJSON = false init(recordEncoder: RecordEncoder, key: CodingKey) { self.recordEncoder = recordEncoder @@ -192,7 +179,7 @@ private class ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. - requestedJSONContainer = .keyed + requiresJSON = true let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -201,7 +188,7 @@ private class ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. - requestedJSONContainer = .unkeyed + requiresJSON = true return JSONRequiredEncoder(codingPath: codingPath) } From f07eee3ca7fd95dbb8634bfcbaf6cd2afa1f167c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 16:22:05 +0100 Subject: [PATCH 071/118] DispatchQueue creation cleanup --- GRDB/Core/Configuration.swift | 9 +++++++++ GRDB/Core/DatabasePool.swift | 9 ++++++--- GRDB/Core/DatabaseQueue.swift | 4 ++-- GRDB/Core/DatabaseSnapshot.swift | 5 +++-- GRDB/Core/SchedulingWatchdog.swift | 22 +++++----------------- GRDB/Core/SerializedDatabase.swift | 11 ++++------- GRDB/ValueObservation/ValueObserver.swift | 7 +------ 7 files changed, 30 insertions(+), 37 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index cbd979143..fac576893 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -171,6 +171,15 @@ public struct Configuration { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags } + + func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue { + let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "") + if let targetQueue = targetQueue { + return DispatchQueue(label: label, target: targetQueue) + } else { + return DispatchQueue(label: label, qos: qos) + } + } } /// A tracing function that takes an SQL string. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index d691cc5e0..621915f87 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -52,7 +52,8 @@ public final class DatabasePool: DatabaseWriter { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: (configuration.label ?? "GRDB.DatabasePool") + ".writer") + defaultLabel: "GRDB.DatabasePool", + purpose: "writer") // Activate WAL Mode unless readonly if !configuration.readonly { @@ -89,7 +90,8 @@ public final class DatabasePool: DatabaseWriter { path: path, configuration: self.readerConfig, schemaCache: SimpleDatabaseSchemaCache(), - label: (self.readerConfig.label ?? "GRDB.DatabasePool") + ".reader.\(readerCount)") + defaultLabel: "GRDB.DatabasePool", + purpose: "reader.\(readerCount)") reader.sync { self.setupDatabase($0) } return reader }) @@ -757,7 +759,8 @@ extension DatabasePool { let snapshot = try DatabaseSnapshot( path: path, configuration: writer.configuration, - labelSuffix: ".snapshot.\(snapshotCount.increment())") + defaultLabel: "GRDB.DatabasePool", + purpose: "snapshot.\(snapshotCount.increment())") snapshot.read { setupDatabase($0) } return snapshot } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 0814bb11c..60df0bfe8 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -40,7 +40,7 @@ public final class DatabaseQueue: DatabaseWriter { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: configuration.label ?? "GRDB.DatabaseQueue") + defaultLabel: "GRDB.DatabaseQueue") } /// Opens an in-memory SQLite database. @@ -56,7 +56,7 @@ public final class DatabaseQueue: DatabaseWriter { path: ":memory:", configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: configuration.label ?? "GRDB.DatabaseQueue") + defaultLabel: "GRDB.DatabaseQueue") } #if os(iOS) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 305738bb8..5ea57064c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -14,7 +14,7 @@ public class DatabaseSnapshot : DatabaseReader { return serializedDatabase.configuration } - init(path: String, configuration: Configuration = Configuration(), labelSuffix: String) throws { + init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = configuration configuration.readonly = true configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction @@ -23,7 +23,8 @@ public class DatabaseSnapshot : DatabaseReader { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: (configuration.label ?? "GRDB.DatabasePool") + labelSuffix) + defaultLabel: defaultLabel, + purpose: purpose) try serializedDatabase.sync { db in // Assert WAL mode diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index ca06d027b..165abfb05 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -22,7 +22,7 @@ import Dispatch /// - preconditionValidQueue() crashes whenever a database is used in an invalid /// dispatch queue. final class SchedulingWatchdog { - private static let specificKey = DispatchSpecificKey() + private static let watchDogKey = DispatchSpecificKey() private(set) var allowedDatabases: [Database] var databaseObservationBroker: DatabaseObservationBroker? @@ -30,22 +30,10 @@ final class SchedulingWatchdog { allowedDatabases = [database] } - static func makeSerializedQueue( - allowingDatabase database: Database, - label: String, - qos: DispatchQoS, - targetQueue: DispatchQueue?) - -> DispatchQueue - { - let queue: DispatchQueue - if let targetQueue = targetQueue { - queue = DispatchQueue(label: label, target: targetQueue) - } else { - queue = DispatchQueue(label: label, qos: qos) - } + static func allowDatabase(_ database: Database, onQueue queue: DispatchQueue) { + precondition(queue.getSpecific(key: watchDogKey) == nil) let watchdog = SchedulingWatchdog(allowedDatabase: database) - queue.setSpecific(key: specificKey, value: watchdog) - return queue + queue.setSpecific(key: watchDogKey, value: watchdog) } func inheritingAllowedDatabases(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T { @@ -60,7 +48,7 @@ final class SchedulingWatchdog { } static var current: SchedulingWatchdog? { - return DispatchQueue.getSpecific(key: specificKey) + return DispatchQueue.getSpecific(key: watchDogKey) } func allows(_ db: Database) -> Bool { diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 730bb7d56..2a804e965 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -16,7 +16,7 @@ final class SerializedDatabase { /// The dispatch queue private let queue: DispatchQueue - init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, label: String) throws { + init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws { // According to https://www.sqlite.org/threadsafe.html // // > SQLite support three different threading modes: @@ -37,13 +37,10 @@ final class SerializedDatabase { var config = configuration config.threadingMode = .multiThread - db = try Database(path: path, configuration: config, schemaCache: schemaCache) - queue = SchedulingWatchdog.makeSerializedQueue( - allowingDatabase: db, - label: label, - qos: configuration.qos, - targetQueue: configuration.targetQueue) self.path = path + self.db = try Database(path: path, configuration: config, schemaCache: schemaCache) + self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose) + SchedulingWatchdog.allowDatabase(db, onQueue: queue) try queue.sync { try db.setup() } diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index e0392bd78..b261383a8 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -27,12 +27,7 @@ class ValueObserver: TransactionObserver { self.notificationQueue = notificationQueue self.onChange = onChange self.onError = onError - let reduceQueueLabel = (configuration.label ?? "GRDB") + ".ValueObservation.reducer" - if let targetQueue = configuration.targetQueue { - self.reduceQueue = DispatchQueue(label: reduceQueueLabel, target: targetQueue) - } else { - self.reduceQueue = DispatchQueue(label: reduceQueueLabel, qos: configuration.qos) - } + self.reduceQueue = configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer") } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { From 5b3412e9f732f7b1499e7bc9f119ffbac3b4509b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 16:35:19 +0100 Subject: [PATCH 072/118] ValueObservation.compactMap --- GRDB.xcodeproj/project.pbxproj | 20 ++++++ .../ValueObservation+CompactMap.swift | 43 +++++++++++++ .../ValueObservation+Map.swift | 14 +++-- GRDBCipher.xcodeproj/project.pbxproj | 26 ++++++++ GRDBCustom.xcodeproj/project.pbxproj | 18 ++++++ .../ValueObservationCompactMapTests.swift | 62 +++++++++++++++++++ .../ValueObservationExtentTests.swift | 6 +- .../GRDBTests/ValueObservationMapTests.swift | 59 ++++++++++++++++++ .../ValueObservationReducerTests.swift | 60 ++++++++++++++++-- 9 files changed, 293 insertions(+), 15 deletions(-) create mode 100644 GRDB/ValueObservation/ValueObservation+CompactMap.swift create mode 100644 Tests/GRDBTests/ValueObservationCompactMapTests.swift create mode 100644 Tests/GRDBTests/ValueObservationMapTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fe150f1e2..64db67dbc 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -204,6 +204,13 @@ 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -964,6 +971,9 @@ 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1388,6 +1398,7 @@ children = ( 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */, + 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */, 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */, 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, @@ -1537,10 +1548,12 @@ isa = PBXGroup; children = ( 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, + 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */, 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, @@ -2559,6 +2572,7 @@ 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, + 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, @@ -2663,6 +2677,7 @@ 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 563EF44B2161F179007DAACD /* Inflections.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -2844,6 +2859,7 @@ 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, + 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2869,6 +2885,7 @@ 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */, @@ -3021,6 +3038,7 @@ 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + 564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, @@ -3046,6 +3064,7 @@ 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, + 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */, 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, @@ -3122,6 +3141,7 @@ 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, + 564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, diff --git a/GRDB/ValueObservation/ValueObservation+CompactMap.swift b/GRDB/ValueObservation/ValueObservation+CompactMap.swift new file mode 100644 index 000000000..bb1fde1ca --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+CompactMap.swift @@ -0,0 +1,43 @@ +extension ValueObservation where Reducer: ValueReducer { + /// Returns a ValueObservation which notifies the non-nil results of calling + /// the given transformation which each element notified by this + /// value observation. + public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) + -> ValueObservation> + { + let makeReducer = self.makeReducer + return ValueObservation>( + tracking: observedRegion, + reducer: { db in try makeReducer(db).compactMap(transform) }) + } +} + +extension ValueReducer { + /// Returns a reducer which outputs the non-nil results of calling the given + /// transformation which each element emitted by this reducer. + public func compactMap(_ transform: @escaping (Value) -> T?) -> CompactMapValueReducer { + return CompactMapValueReducer(self, transform) + } +} + +/// See ValueReducer.compactMap(_:) +/// +/// :nodoc: +public struct CompactMapValueReducer: ValueReducer { + private var base: Base + private let transform: (Base.Value) -> T? + + init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { + self.base = base + self.transform = transform + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> T? { + guard let value = base.value(fetched) else { return nil } + return transform(value) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift index ba2834598..3ed5a9532 100644 --- a/GRDB/ValueObservation/ValueObservation+Map.swift +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -1,6 +1,7 @@ extension ValueObservation where Reducer: ValueReducer { - /// Returns a ValueObservation which transforms the values returned by - /// this ValueObservation. + /// Returns a ValueObservation which notifies the results of calling the + /// given transformation which each element notified by this + /// value observation. public func map(_ transform: @escaping (Reducer.Value) -> T) -> ValueObservation> { @@ -12,8 +13,9 @@ extension ValueObservation where Reducer: ValueReducer { } extension ValueReducer { - /// Returns a reducer which transforms the values returned by this reducer. - public func map(_ transform: @escaping (Value) -> T?) -> MapValueReducer { + /// Returns a reducer which outputs the results of calling the given + /// transformation which each element emitted by this reducer. + public func map(_ transform: @escaping (Value) -> T) -> MapValueReducer { return MapValueReducer(self, transform) } } @@ -26,9 +28,9 @@ extension ValueReducer { /// :nodoc: public struct MapValueReducer: ValueReducer { private var base: Base - private let transform: (Base.Value) -> T? + private let transform: (Base.Value) -> T - init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { + init(_ base: Base, _ transform: @escaping (Base.Value) -> T) { self.base = base self.transform = transform } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 575827a73..a1843a183 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -262,6 +262,16 @@ 5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 564CE44021AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; 564CE44121AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; + 564CE4DD21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4DE21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4F121B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F221B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F321B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1074,6 +1084,9 @@ 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43F21AA957000652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1468,6 +1481,7 @@ children = ( 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */, 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */, + 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */, 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, @@ -1617,10 +1631,12 @@ isa = PBXGroup; children = ( 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */, 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */, 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */, 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */, + 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */, 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */, 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */, 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */, @@ -2338,6 +2354,7 @@ 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560FC5261CB003810014AA8E /* SerializedDatabase.swift in Sources */, 560FC5271CB003810014AA8E /* NSString.swift in Sources */, + 564CE4DD21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */, 560FC5291CB003810014AA8E /* DatabaseValueConvertible.swift in Sources */, 56A8C2311D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5021EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2538,6 +2555,7 @@ 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, + 564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 562393731DEE104400A6B01F /* MapCursorTests.swift in Sources */, @@ -2563,6 +2581,7 @@ 560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */, 560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */, 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F121B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */, 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2715,6 +2734,7 @@ 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, 564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 562393741DEE104400A6B01F /* MapCursorTests.swift in Sources */, @@ -2740,6 +2760,7 @@ 5698ACD01DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F221B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */, 567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -2816,6 +2837,7 @@ 56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 56AFC9FB1CB1A8BB00F48B96 /* SerializedDatabase.swift in Sources */, 56AFC9FC1CB1A8BB00F48B96 /* DatabaseMigrator.swift in Sources */, + 564CE4DE21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */, 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */, 56A8C2341D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5051EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -3016,6 +3038,7 @@ 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, 56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */, 564F9C231F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -3041,6 +3064,7 @@ 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F321B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, @@ -3193,6 +3217,7 @@ 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, + 564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, 56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -3218,6 +3243,7 @@ 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5691784B1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 56AFCACB1CB1ABC800F48B96 /* DatabaseFunctionTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 757d6c871..9bfc3b181 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -97,6 +97,12 @@ 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; + 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; + 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -715,6 +721,9 @@ 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1075,6 +1084,7 @@ children = ( 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */, + 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */, 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, @@ -1231,10 +1241,12 @@ isa = PBXGroup; children = ( 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, + 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */, 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, @@ -1981,6 +1993,7 @@ F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, + 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -2181,6 +2194,7 @@ 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, + 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 5657AB3D1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2206,6 +2220,7 @@ 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */, 562393671DEE06D300A6B01F /* CursorTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2282,6 +2297,7 @@ F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, + 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -2482,6 +2498,7 @@ 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, + 564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */, @@ -2507,6 +2524,7 @@ 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationCompactMapTests.swift b/Tests/GRDBTests/ValueObservationCompactMapTests.swift new file mode 100644 index 000000000..354437cc9 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationCompactMapTests.swift @@ -0,0 +1,62 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationCompactMapTests: GRDBTestCase { + func testCompactMap() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // The base reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // Create an observation + var observation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + .compactMap { count -> String? in + if count % 2 == 0 { return nil } + return "\(count)" + } + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } +} diff --git a/Tests/GRDBTests/ValueObservationExtentTests.swift b/Tests/GRDBTests/ValueObservationExtentTests.swift index 5060c9fc4..47fef4251 100644 --- a/Tests/GRDBTests/ValueObservationExtentTests.swift +++ b/Tests/GRDBTests/ValueObservationExtentTests.swift @@ -23,7 +23,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 3 @@ -60,7 +60,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process var changesCount = 0 let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true @@ -107,7 +107,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift new file mode 100644 index 000000000..6b15756b6 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -0,0 +1,59 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationMapTests: GRDBTestCase { + func testMap() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // The base reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // Create an observation + var observation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + .map { count -> String in return "\(count)" } + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "2", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } +} diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 001e850ff..ca6ca4f40 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -30,7 +30,7 @@ class ValueObservationReducerTests: GRDBTestCase { // We need something to change try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process var fetchCount = 0 var reduceCount = 0 var errors: [Error] = [] @@ -155,7 +155,7 @@ class ValueObservationReducerTests: GRDBTestCase { // We need something to change try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process var errors: [Error] = [] var changes: [Void] = [] let notificationExpectation = expectation(description: "notification") @@ -212,7 +212,7 @@ class ValueObservationReducerTests: GRDBTestCase { // We need something to change try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process var counts: [Int] = [] let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true @@ -252,7 +252,55 @@ class ValueObservationReducerTests: GRDBTestCase { // We need something to change try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // The base reducer + var count = 0 + let baseReducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // The mapped reducer + let reducer = baseReducer.map { count -> String in + return "\(count)" + } + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "2", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testCompactMapValueReducer() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process var counts: [String] = [] let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true @@ -268,7 +316,7 @@ class ValueObservationReducerTests: GRDBTestCase { }) // The mapped reducer - let reducer = baseReducer.map { count -> String? in + let reducer = baseReducer.compactMap { count -> String? in if count % 2 == 0 { return nil } return "\(count)" } @@ -295,7 +343,7 @@ class ValueObservationReducerTests: GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } - + func testValueObservationMap() throws { func test(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } From 2488007b9c253328af169ddeee21a5c02a82431f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:02:25 +0100 Subject: [PATCH 073/118] README --- README.md | 194 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 114 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index a418cbefa..af5d82aa7 100644 --- a/README.md +++ b/README.md @@ -6301,10 +6301,13 @@ The observer returned by the `start` method is stored in a property of the view > :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) -- [ValueObservation.combine(...)](#valueobservationcombine) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [ValueObservation.tracking(_:reducer:)](#valueobservationtracking_reducer) +- [ValueObservation Transformations](#valueobservation-transformations) + - [ValueObservation.map](#valueobservationmap): Transform notified values. + - [ValueObservation.compactMap](#valueobservationcompactmap): Transform and filter notified values. + - [ValueObservation.combine(...)](#valueobservationcombine) - [ValueObservation Options](#valueobservation-options) +- [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) ### ValueObservation.trackingCount, trackingOne, trackingAll @@ -6368,40 +6371,10 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me } ``` -### ValueObservation.combine(...) - -Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. - -When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: - -```swift -// The two observed requests (the team and its players) -let teamRequest = Team.filter(key: 1) -let playersRequest = Player.filter(Column("teamId") == 1) - -// Two observations -let teamObservation = ValueObservation.trackingOne(teamRequest) -let playersObservation = ValueObservation.trackingAll(playersRequest) - -// The combined observation -let observation = ValueObservation.combine(teamObservation, playersObservation) - -// Start tracking players and teams -let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] in - print("Team or players have changed.") -} -``` - -Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). - -> :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. -> -> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. - ### ValueObservation.tracking(_:fetch:) -Observing the database is not always easy to express with simple requests, or the combination of several observations, as we have seen above. +Observing the database is not always easy to express with simple requests, as above. For example, let's say that we have a struct that defines a "Hall of Fame": @@ -6541,49 +6514,83 @@ let observer = ValueObservation ``` -### ValueObservation.tracking(_:reducer:) +### ValueObservation Transformations -The most general way to define a ValueObservation is to create one from an observed database region (see above), and a **reducer** that adopts the **ValueReducer** protocol ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)): +- [ValueObservation.map](#valueobservationmap): Transform notified values. +- [ValueObservation.compactMap](#valueobservationcompactmap): Transform and filter notified values. +- [ValueObservation.combine(...)](#valueobservationcombine) + + +#### ValueObservation.map + +The `map` method lets you transform the values notified by a ValueObservation. + +For example: ```swift -protocol ValueReducer { - associatedtype Fetched - associatedtype Value - - /// Fetches a database value - func fetch(_ db: Database) throws -> Fetched - - /// Returns a notified value - mutating func value(_ fetched: Fetched) -> Value? +// Observe a player's profile image +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .map { player in player?.loadBigProfileImage() } + +let observer = observation.start(in: dbQueue) { image: UIImage? in + print("Player picture has changed") } ``` -The `fetch` method is called upon changes in the observed [database region](#databaseregion). It runs inside a dispatch queue which can access the database. +The transformation closure does not run on the main queue, and is suitable for heavy computations. -The `value` method transforms a fetched value into a notified value. It returns nil if the observer should not be notified. This method runs inside a private dispatch queue. -The sample code below counts the number of times the player table is modified: +#### ValueObservation.compactMap + +The `compactMap` method lets you transform the and filter values notified by a ValueObservation. Only non-nil transformed values are notified. + +For example: ```swift -var count = 0 -let observation = ValueObservation.tracking(Player.all(), reducer: { _ in - AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - defer { count += 1 } - return count }) -}) -let observer = observation.start(in: dbQueue) { count: Int in - print("\(count) transaction(s) have modified the players.") +// Observe a player +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .compactMap { $0 } + +let observer = observation.start(in: dbQueue) { player: Player in + print("Player name: \(player.name)") } -// Prints "0 transaction(s) have modified the players." - -try dbQueue.write { db in - try Player(...).insert(db) -} -// Prints "1 transaction(s) have modified the players." ``` +The transformation closure does not run on the main queue, and is suitable for heavy computations. + + +#### ValueObservation.combine(...) + +Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. + +When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: + +```swift +// The two observed requests (the team and its players) +let teamRequest = Team.filter(key: 1) +let playersRequest = Player.filter(Column("teamId") == 1) + +// Two observations +let teamObservation = ValueObservation.trackingOne(teamRequest) +let playersObservation = ValueObservation.trackingAll(playersRequest) + +// The combined observation +let observation = ValueObservation.combine(teamObservation, playersObservation) + +// Start tracking players and teams +let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] in + print("Team or players have changed.") +} +``` + +Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). + +> :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. +> +> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. + ### ValueObservation Options @@ -6592,7 +6599,6 @@ Some behaviors of value observations can be configured: - [ValueObservation.extent](#valueobservationextent): Precise control of the observation duration. - [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. - [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. -- [ValueObservation.map](#valueobservationmap): Transform notified values. - [ValueObservation Error Handling](#valueobservation-error-handling) @@ -6707,22 +6713,6 @@ observation.requiresWriteAccess = true When you use a [database pool](#database-pools), don't use this flag unless you really need it. Observations with write access are less efficient because they block all writes for the whole duration of a fetch. -#### ValueObservation.map - -The `map` method lets you transform the values notified by a ValueObservation. - -The transformation runs in a dispatch queue which does not block the main queue or the database, and is suitable for heavy computations: - -```swift -let observation = ValueObservation - .trackingOne(Player.filter(key: 42)) - .map { player in player?.loadBigProfileImage() } - .start(in: dbQueue) { image: UIImage? in - print("Player picture has changed") - } -``` - - #### ValueObservation Error Handling When you start an observation, you can provide an `onError` callback. This callback is called whenever an error happens when a fresh value is fetched after a database change. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): @@ -6739,6 +6729,50 @@ let observer = try observation.start( ``` +### Advanced: ValueObservation.tracking(_:reducer:) + +The most low-level way to define a ValueObservation is to create one from an observed database region (see above), and a **reducer** that adopts the **ValueReducer** protocol ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)): + +```swift +protocol ValueReducer { + associatedtype Fetched + associatedtype Value + + /// Fetches a database value + func fetch(_ db: Database) throws -> Fetched + + /// Returns a notified value + mutating func value(_ fetched: Fetched) -> Value? +} +``` + +The `fetch` method is called upon changes in the observed [database region](#databaseregion). It runs inside a protected dispatch queue and is guaranteed an immutable view of the last committed state of the database. + +The `value` method transforms a fetched value into a notified value. It returns nil if the observer should not be notified. It runs inside a dispatch queue called the "reduce queue", which is not the main queue, and not a database queue. + +The sample code below counts the number of times the player table is modified: + +```swift +var count = 0 +let observation = ValueObservation.tracking(Player.all(), reducer: { _ in + AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) +}) +let observer = observation.start(in: dbQueue) { count: Int in + print("\(count) transaction(s) have modified the players.") +} +// Prints "0 transaction(s) have modified the players." + +try dbQueue.write { db in + try Player(...).insert(db) +} +// Prints "1 transaction(s) have modified the players." +``` + + ## FetchedRecordsController **FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.** From 838d9204ab78782bae50e1bc918133bb68a3b145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:02:30 +0100 Subject: [PATCH 074/118] CHANGELOG --- CHANGELOG.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4f01e5b2..f3b48f314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations +- [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. @@ -66,7 +67,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). ### Documentation Diff - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. -- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine(...)` method. +- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine(...)` and `ValueObservation.compactMap(...)` methods. ### API diff @@ -92,7 +93,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). + -> ValueObservation } - extension ValueObservation where Reducer == Void { ++extension ValueObservation where Reducer == Void { + static func tracking( + _ regions: [DatabaseRegionConvertible], + fetch: @escaping (Database) throws -> Value) @@ -104,7 +105,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). + where Value: Equatable + static func combine(_ o1: ValueObservation, ...) + -> ValueObservation<...> - } ++} + ++extension ValueObservation where Reducer: ValueReducer { ++ func compactMap(_ transform: @escaping (Reducer.Value) -> T?) ++ -> ValueObservation> ++} + struct Configuration { + var qos: DispatchQoS From 90c588a9f5f54b682900293e5bc9cc3539516905 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:06:10 +0100 Subject: [PATCH 075/118] README --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index af5d82aa7..7ca1201ca 100644 --- a/README.md +++ b/README.md @@ -6303,8 +6303,8 @@ The observer returned by the `start` method is stored in a property of the view - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) - [ValueObservation Transformations](#valueobservation-transformations) - - [ValueObservation.map](#valueobservationmap): Transform notified values. - - [ValueObservation.compactMap](#valueobservationcompactmap): Transform and filter notified values. + - [ValueObservation.map](#valueobservationmap) + - [ValueObservation.compactMap](#valueobservationcompactmap) - [ValueObservation.combine(...)](#valueobservationcombine) - [ValueObservation Options](#valueobservation-options) - [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) @@ -6516,8 +6516,8 @@ let observer = ValueObservation ### ValueObservation Transformations -- [ValueObservation.map](#valueobservationmap): Transform notified values. -- [ValueObservation.compactMap](#valueobservationcompactmap): Transform and filter notified values. +- [ValueObservation.map](#valueobservationmap) +- [ValueObservation.compactMap](#valueobservationcompactmap) - [ValueObservation.combine(...)](#valueobservationcombine) From 3687e119588bd6d04072b10ba33b29de1af3c1fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:10:17 +0100 Subject: [PATCH 076/118] README --- README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 7ca1201ca..81960ff4d 100644 --- a/README.md +++ b/README.md @@ -6306,6 +6306,7 @@ The observer returned by the `start` method is stored in a property of the view - [ValueObservation.map](#valueobservationmap) - [ValueObservation.compactMap](#valueobservationcompactmap) - [ValueObservation.combine(...)](#valueobservationcombine) +- [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) - [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) @@ -6592,6 +6593,22 @@ Combining observations provides the guarantee that notified values are [**consis > :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. +### ValueObservation Error Handling + +When you start an observation, you can provide an `onError` callback. This callback is called whenever an error happens when a fresh value is fetched after a database change. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): + +```swift +let observer = try observation.start( + in: dbQueue, + onError: { error in + print("fresh value could not be fetched") + }, + onChange: { value in + print("fresh value: \(value)") + }) +``` + + ### ValueObservation Options Some behaviors of value observations can be configured: @@ -6599,7 +6616,6 @@ Some behaviors of value observations can be configured: - [ValueObservation.extent](#valueobservationextent): Precise control of the observation duration. - [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. - [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. -- [ValueObservation Error Handling](#valueobservation-error-handling) #### ValueObservation.extent @@ -6713,22 +6729,6 @@ observation.requiresWriteAccess = true When you use a [database pool](#database-pools), don't use this flag unless you really need it. Observations with write access are less efficient because they block all writes for the whole duration of a fetch. -#### ValueObservation Error Handling - -When you start an observation, you can provide an `onError` callback. This callback is called whenever an error happens when a fresh value is fetched after a database change. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): - -```swift -let observer = try observation.start( - in: dbQueue, - onError: { error in - print("fresh value could not be fetched") - }, - onChange: { value in - print("fresh value: \(value)") - }) -``` - - ### Advanced: ValueObservation.tracking(_:reducer:) The most low-level way to define a ValueObservation is to create one from an observed database region (see above), and a **reducer** that adopts the **ValueReducer** protocol ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)): From c89540683f0493d44dd1df7218da429ce39e5372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:11:56 +0100 Subject: [PATCH 077/118] README --- README.md | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 81960ff4d..6a9b045cb 100644 --- a/README.md +++ b/README.md @@ -6260,6 +6260,21 @@ protocol TransactionObserverType : class { Changes are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +- **[ValueObservation Usage](#valueobservation-usage)** +- [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) +- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) +- [ValueObservation Transformations](#valueobservation-transformations) + - [ValueObservation.map](#valueobservationmap) + - [ValueObservation.compactMap](#valueobservationcompactmap) + - [ValueObservation.combine(...)](#valueobservationcombine) +- [ValueObservation Error Handling](#valueobservation-error-handling) +- [ValueObservation Options](#valueobservation-options) +- [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) + + +### ValueObservation Usage + Here is a typical UIViewController which observes the database in order to keep its view up-to-date: ```swift @@ -6300,16 +6315,6 @@ The observer returned by the `start` method is stored in a property of the view > :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. -- [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) -- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [ValueObservation Transformations](#valueobservation-transformations) - - [ValueObservation.map](#valueobservationmap) - - [ValueObservation.compactMap](#valueobservationcompactmap) - - [ValueObservation.combine(...)](#valueobservationcombine) -- [ValueObservation Error Handling](#valueobservation-error-handling) -- [ValueObservation Options](#valueobservation-options) -- [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) - ### ValueObservation.trackingCount, trackingOne, trackingAll From c1d8dcb10505fd1398278bb3bd9b49142872a5fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 17:17:11 +0100 Subject: [PATCH 078/118] Link to ValueObservation from GoodPracticesForDesigningRecordTypes --- Documentation/GoodPracticesForDesigningRecordTypes.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 61b709b22..0b761f1b3 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -308,11 +308,13 @@ This synchronization is not automatic with GRDB: records do not "auto-update". T Instead, have a look at [Database Observation]: -> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way. +> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes. > -> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request. +> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view. > -> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs. +> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way. +> +> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs. > > :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones. @@ -337,6 +339,7 @@ Instead, have a look at [Database Observation]: [Concurrency Guide]: ../README.md#concurrency [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation +[ValueObservation]: ../README.md#valueobservation [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [TransactionObserver]: ../README.md#transactionobserver-protocol From 2c3776d3723a29d3af9cbb2b1bfcee691c5a7527 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 18:59:01 +0100 Subject: [PATCH 079/118] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a9b045cb..854b88a05 100644 --- a/README.md +++ b/README.md @@ -6549,7 +6549,7 @@ The transformation closure does not run on the main queue, and is suitable for h #### ValueObservation.compactMap -The `compactMap` method lets you transform the and filter values notified by a ValueObservation. Only non-nil transformed values are notified. +The `compactMap` method lets you transform and filter the values notified by a ValueObservation. Only non-nil transformed values are notified. For example: From 3884141fc2d96a050eb4cbfbc5f403024cc41b60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 19:06:16 +0100 Subject: [PATCH 080/118] map/compactMap fail preserving ValueObservation configuration --- .../ValueObservationCompactMapTests.swift | 17 +++++++++++++++++ Tests/GRDBTests/ValueObservationMapTests.swift | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationCompactMapTests.swift b/Tests/GRDBTests/ValueObservationCompactMapTests.swift index 354437cc9..5d3d91f94 100644 --- a/Tests/GRDBTests/ValueObservationCompactMapTests.swift +++ b/Tests/GRDBTests/ValueObservationCompactMapTests.swift @@ -59,4 +59,21 @@ class ValueObservationCompactMapTests: GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + + func testCompactMapPreservesConfiguration() { + var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + observation.extent = .nextTransaction + observation.requiresWriteAccess = true + observation.scheduling = .unsafe(startImmediately: true) + + let mappedObservation = observation.compactMap { _ in } + XCTAssertEqual(mappedObservation.extent, observation.extent) + XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) + switch mappedObservation.scheduling { + case .unsafe: + break + default: + XCTFail() + } + } } diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 6b15756b6..16a8c08b5 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -56,4 +56,21 @@ class ValueObservationMapTests: GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + + func testMapPreservesConfiguration() { + var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + observation.extent = .nextTransaction + observation.requiresWriteAccess = true + observation.scheduling = .unsafe(startImmediately: true) + + let mappedObservation = observation.map { _ in } + XCTAssertEqual(mappedObservation.extent, observation.extent) + XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) + switch mappedObservation.scheduling { + case .unsafe: + break + default: + XCTFail() + } + } } From 8c543f507861488d620d11260531a16d5f94b74b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 1 Dec 2018 19:07:58 +0100 Subject: [PATCH 081/118] Fix failing tests --- GRDB/ValueObservation/ValueObservation+CompactMap.swift | 6 +++++- GRDB/ValueObservation/ValueObservation+Map.swift | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation+CompactMap.swift b/GRDB/ValueObservation/ValueObservation+CompactMap.swift index bb1fde1ca..66edf990e 100644 --- a/GRDB/ValueObservation/ValueObservation+CompactMap.swift +++ b/GRDB/ValueObservation/ValueObservation+CompactMap.swift @@ -6,9 +6,13 @@ extension ValueObservation where Reducer: ValueReducer { -> ValueObservation> { let makeReducer = self.makeReducer - return ValueObservation>( + var observation = ValueObservation>( tracking: observedRegion, reducer: { db in try makeReducer(db).compactMap(transform) }) + observation.extent = extent + observation.scheduling = scheduling + observation.requiresWriteAccess = requiresWriteAccess + return observation } } diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift index 3ed5a9532..c9e510b7e 100644 --- a/GRDB/ValueObservation/ValueObservation+Map.swift +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -6,9 +6,13 @@ extension ValueObservation where Reducer: ValueReducer { -> ValueObservation> { let makeReducer = self.makeReducer - return ValueObservation>( + var observation = ValueObservation>( tracking: observedRegion, reducer: { db in try makeReducer(db).map(transform) }) + observation.extent = extent + observation.scheduling = scheduling + observation.requiresWriteAccess = requiresWriteAccess + return observation } } From b8e3994858a54950680df02a421364f61912589d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Dec 2018 00:01:21 +0100 Subject: [PATCH 082/118] ValueObservation.mapReducer and expose more precise value reducers --- GRDB.xcodeproj/project.pbxproj | 8 + .../ValueObservation+Combine.swift | 362 +++++++++--------- .../ValueObservation+CompactMap.swift | 13 +- .../ValueObservation+Count.swift | 2 +- ...Observation+DatabaseValueConvertible.swift | 209 +++++----- .../ValueObservation+FetchableRecord.swift | 120 +++--- .../ValueObservation+Map.swift | 13 +- .../ValueObservation+MapReducer.swift | 15 + .../ValueObservation+Row.swift | 72 +++- GRDB/ValueObservation/ValueObservation.swift | 16 +- GRDB/ValueObservation/ValueReducer.swift | 84 ++-- GRDBCipher.xcodeproj/project.pbxproj | 6 + GRDBCustom.xcodeproj/project.pbxproj | 6 + ...rvationDatabaseValueConvertibleTests.swift | 4 +- 14 files changed, 519 insertions(+), 411 deletions(-) create mode 100644 GRDB/ValueObservation/ValueObservation+MapReducer.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 64db67dbc..ca19ec9f6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -211,6 +211,9 @@ 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; }; 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; + 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -974,6 +977,7 @@ 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1403,6 +1407,7 @@ 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */, + 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, @@ -2508,6 +2513,7 @@ 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, + 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, @@ -2658,6 +2664,7 @@ 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3118,6 +3125,7 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A01EA8D997004A4992 /* Result.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift index 64979a307..da06efc20 100644 --- a/GRDB/ValueObservation/ValueObservation+Combine.swift +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -12,7 +12,7 @@ extension ValueObservation where Reducer == Void { tracking: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0)) }, - reducer: { try ValueReducers.combine( + reducer: { try _combine( o1.makeReducer($0), o2.makeReducer($0)) }) } @@ -32,7 +32,7 @@ extension ValueObservation where Reducer == Void { o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0)) }, - reducer: { try ValueReducers.combine( + reducer: { try _combine( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0)) }) @@ -55,7 +55,7 @@ extension ValueObservation where Reducer == Void { o2.observedRegion($0), o3.observedRegion($0), o4.observedRegion($0)) }, - reducer: { try ValueReducers.combine( + reducer: { try _combine( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), @@ -81,7 +81,7 @@ extension ValueObservation where Reducer == Void { o3.observedRegion($0), o4.observedRegion($0), o5.observedRegion($0)) }, - reducer: { try ValueReducers.combine( + reducer: { try _combine( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), @@ -90,186 +90,184 @@ extension ValueObservation where Reducer == Void { } } -extension ValueReducers { - static func combine( - _ r1: R1, - _ r2: R2) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched), - (R1.Value, R2.Value)> - { - var r1 = r1 - var r2 = r2 - var prev1: R1.Value? - var prev2: R2.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - } - if v1 != nil || v2 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2 - { - return (c1, c2) - } else { - return nil - } - } - return AnyValueReducer(fetch: fetch, value: value) +private func _combine( + _ r1: R1, + _ r2: R2) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched), + (R1.Value, R2.Value)> +{ + var r1 = r1 + var r2 = r2 + var prev1: R1.Value? + var prev2: R2.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db)) } - - static func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched), - (R1.Value, R2.Value, R3.Value)> - { - var r1 = r1 - var r2 = r2 - var r3 = r3 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db)) + func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } - } - if v1 != nil || v2 != nil || v3 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3 - { - return (c1, c2, c3) - } else { - return nil - } + if v1 != nil || v2 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2 + { + return (c1, c2) + } else { + return nil } - return AnyValueReducer(fetch: fetch, value: value) - } - - static func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3, - _ r4: R4) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), - (R1.Value, R2.Value, R3.Value, R4.Value)> - { - var r1 = r1 - var r2 = r2 - var r3 = r3 - var r4 = r4 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - var prev4: R4.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db), - r4.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - let v4 = r4.value(tuple.3) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } - if let v4 = v4 { prev4 = v4 } - } - if v1 != nil || v2 != nil || v3 != nil || v4 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3, - let c4 = v4 ?? prev4 - { - return (c1, c2, c3, c4) - } else { - return nil - } - } - return AnyValueReducer(fetch: fetch, value: value) - } - - static func combine( - _ r1: R1, - _ r2: R2, - _ r3: R3, - _ r4: R4, - _ r5: R5) - -> AnyValueReducer< - (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), - (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> - { - var r1 = r1 - var r2 = r2 - var r3 = r3 - var r4 = r4 - var r5 = r5 - var prev1: R1.Value? - var prev2: R2.Value? - var prev3: R3.Value? - var prev4: R4.Value? - var prev5: R5.Value? - func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { - return try ( - r1.fetch(db), - r2.fetch(db), - r3.fetch(db), - r4.fetch(db), - r5.fetch(db)) - } - func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { - let v1 = r1.value(tuple.0) - let v2 = r2.value(tuple.1) - let v3 = r3.value(tuple.2) - let v4 = r4.value(tuple.3) - let v5 = r5.value(tuple.4) - defer { - if let v1 = v1 { prev1 = v1 } - if let v2 = v2 { prev2 = v2 } - if let v3 = v3 { prev3 = v3 } - if let v4 = v4 { prev4 = v4 } - if let v5 = v5 { prev5 = v5 } - } - if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil, - let c1 = v1 ?? prev1, - let c2 = v2 ?? prev2, - let c3 = v3 ?? prev3, - let c4 = v4 ?? prev4, - let c5 = v5 ?? prev5 - { - return (c1, c2, c3, c4, c5) - } else { - return nil - } - } - return AnyValueReducer(fetch: fetch, value: value) } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched), + (R1.Value, R2.Value, R3.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + } + if v1 != nil || v2 != nil || v3 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3 + { + return (c1, c2, c3) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4 + { + return (c1, c2, c3, c4) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4, + _ r5: R5) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var r5 = r5 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + var prev5: R5.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db), + r5.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + let v5 = r5.value(tuple.4) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + if let v5 = v5 { prev5 = v5 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4, + let c5 = v5 ?? prev5 + { + return (c1, c2, c3, c4, c5) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) } diff --git a/GRDB/ValueObservation/ValueObservation+CompactMap.swift b/GRDB/ValueObservation/ValueObservation+CompactMap.swift index 66edf990e..5778b5ab5 100644 --- a/GRDB/ValueObservation/ValueObservation+CompactMap.swift +++ b/GRDB/ValueObservation/ValueObservation+CompactMap.swift @@ -5,18 +5,13 @@ extension ValueObservation where Reducer: ValueReducer { public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) -> ValueObservation> { - let makeReducer = self.makeReducer - var observation = ValueObservation>( - tracking: observedRegion, - reducer: { db in try makeReducer(db).compactMap(transform) }) - observation.extent = extent - observation.scheduling = scheduling - observation.requiresWriteAccess = requiresWriteAccess - return observation + return mapReducer { $1.compactMap(transform) } } } extension ValueReducer { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// /// Returns a reducer which outputs the non-nil results of calling the given /// transformation which each element emitted by this reducer. public func compactMap(_ transform: @escaping (Value) -> T?) -> CompactMapValueReducer { @@ -24,6 +19,8 @@ extension ValueReducer { } } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// /// See ValueReducer.compactMap(_:) /// /// :nodoc: diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift index f455db68f..fec32c862 100644 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -26,7 +26,7 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingCount(_ request: Request) - -> ValueObservation> + -> ValueObservation> { return ValueObservation.tracking(request, fetchDistinct: request.fetchCount) } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index f92572f05..c32634532 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -27,12 +27,12 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: DatabaseValueConvertible { - return ValueObservation>.tracking( - request, - reducer: { _ in ValueReducers.Values { try DatabaseValue.fetchAll($0, request) } }) + return ValueObservation>.tracking(request, reducer: { _ in + DatabaseValuesReducer(request: request) } + ) } /// Creates a ValueObservation which observes *request*, and notifies a @@ -59,12 +59,11 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingOne(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: DatabaseValueConvertible { - return ValueObservation>.tracking( - request, - reducer: { _ in ValueReducers.Value { try DatabaseValue.fetchOne($0, request) } }) + return ValueObservation>.tracking(request, reducer: { _ in DatabaseValueReducer(request: request) + }) } /// Creates a ValueObservation which observes *request*, and notifies @@ -92,108 +91,120 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: _OptionalProtocol, Request.RowDecoder._Wrapped: DatabaseValueConvertible { - return ValueObservation>.tracking( - request, - reducer: { _ in ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) } }) + return ValueObservation>.tracking(request, reducer: { _ in + OptionalDatabaseValuesReducer(request: request) + }) } } -extension ValueReducers { - /// A reducer which outputs arrays of values, filtering out consecutive - /// identical database values. - public struct Values: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decode(from: $0, conversionContext: nil) - } - } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct DatabaseValuesReducer: ValueReducer + where Request.RowDecoder: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValues: [DatabaseValue]? + + init(request: Request) { + self.request = request } - /// A reducer which outputs optional values, filtering out consecutive - /// identical database values. - public struct Value: ValueReducer { - private let _fetch: (Database) throws -> DatabaseValue? - private var previousDbValue: DatabaseValue?? - private var previousValueWasNil = false - - init(_ fetch: @escaping (Database) throws -> DatabaseValue?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> DatabaseValue? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValue: DatabaseValue?) -> T?? { - if let previousDbValue = previousDbValue, previousDbValue == dbValue { - // Don't notify consecutive identical dbValue - return nil - } - self.previousDbValue = dbValue - if let dbValue = dbValue, - let value = T.decodeIfPresent(from: dbValue, conversionContext: nil) - { - previousValueWasNil = false - return .some(value) - } else if previousValueWasNil { - // Don't notify consecutive nil values - return nil - } else { - previousValueWasNil = true - return .some(nil) - } - } + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try DatabaseValue.fetchAll(db, request) } - /// A reducer which outputs arrays of optional values, filtering out consecutive - /// identical database values. - public struct OptionalValues: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch + public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + return nil } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T?]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decodeIfPresent(from: $0, conversionContext: nil) - } + self.previousDbValues = dbValues + return dbValues.map { + Request.RowDecoder.decode(from: $0, conversionContext: nil) + } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct DatabaseValueReducer: ValueReducer + where Request.RowDecoder: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValue: DatabaseValue?? + private var previousValueWasNil = false + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> DatabaseValue? { + return try DatabaseValue.fetchOne(db, request) + } + + public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? { + if let previousDbValue = previousDbValue, previousDbValue == dbValue { + // Don't notify consecutive identical dbValue + return nil + } + self.previousDbValue = dbValue + if let dbValue = dbValue, + let value = Request.RowDecoder.decodeIfPresent(from: dbValue, conversionContext: nil) + { + previousValueWasNil = false + return .some(value) + } else if previousValueWasNil { + // Don't notify consecutive nil values + return nil + } else { + previousValueWasNil = true + return .some(nil) + } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of optional values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct OptionalDatabaseValuesReducer: ValueReducer + where + Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder._Wrapped: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValues: [DatabaseValue]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try DatabaseValue.fetchAll(db, request) + } + + public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + return nil + } + self.previousDbValues = dbValues + return dbValues.map { + Request.RowDecoder._Wrapped.decodeIfPresent(from: $0, conversionContext: nil) } } } diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index 6b30f1ce1..1f18722fd 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -1,5 +1,5 @@ extension ValueObservation where Reducer == Void { - + // MARK: - FetchableRecord Observation /// Creates a ValueObservation which observes *request*, and notifies @@ -27,12 +27,12 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder: FetchableRecord { - return ValueObservation>.tracking( - request, - reducer: { _ in ValueReducers.Records { try Row.fetchAll($0, request) } }) + return ValueObservation>.tracking(request, reducer: { _ in + FetchableRecordsReducer(request: request) + }) } /// Creates a ValueObservation which observes *request*, and notifies a @@ -59,65 +59,71 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingOne(_ request: Request) -> - ValueObservation> + ValueObservation> where Request.RowDecoder: FetchableRecord { - return ValueObservation>.tracking( - request, - reducer: { _ in ValueReducers.Record { try Row.fetchOne($0, request) } }) + return ValueObservation>.tracking(request, reducer: { _ in + FetchableRecordReducer(request: request) + }) } } -extension ValueReducers { - /// A reducer which outputs arrays of records, filtering out consecutive - /// identical database rows. - public struct Records: ValueReducer { - private let _fetch: (Database) throws -> [Row] - private var previousRows: [Row]? - - init(_ fetch: @escaping (Database) throws -> [Row]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [Row] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ rows: [Row]) -> [Record]? { - if let previousRows = previousRows, previousRows == rows { - // Don't notify consecutive identical row arrays - return nil - } - self.previousRows = rows - return rows.map(Record.init(row:)) - } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct FetchableRecordsReducer: ValueReducer + where Request.RowDecoder: FetchableRecord +{ + public let request: Request + private var previousRows: [Row]? + + init(request: Request) { + self.request = request } - /// A reducer which outputs optional records, filtering out consecutive - /// identical database rows. - public struct Record: ValueReducer { - private let _fetch: (Database) throws -> Row? - private var previousRow: Row?? - - init(_ fetch: @escaping (Database) throws -> Row?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Row? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ row: Row?) -> Record?? { - if let previousRow = previousRow, previousRow == row { - // Don't notify consecutive identical rows - return nil - } - self.previousRow = row - return .some(row.map(Record.init(row:))) + public func fetch(_ db: Database) throws -> [Row] { + return try Row.fetchAll(db, request) + } + + public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? { + if let previousRows = previousRows, previousRows == rows { + // Don't notify consecutive identical row arrays + return nil } + self.previousRows = rows + return rows.map(Request.RowDecoder.init(row:)) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct FetchableRecordReducer: ValueReducer + where Request.RowDecoder: FetchableRecord +{ + public let request: Request + private var previousRow: Row?? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> Row? { + return try Row.fetchOne(db, request) + } + + public mutating func value(_ row: Row?) -> Request.RowDecoder?? { + if let previousRow = previousRow, previousRow == row { + // Don't notify consecutive identical rows + return nil + } + self.previousRow = row + return .some(row.map(Request.RowDecoder.init(row:))) } } diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift index c9e510b7e..cefd648b5 100644 --- a/GRDB/ValueObservation/ValueObservation+Map.swift +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -5,18 +5,13 @@ extension ValueObservation where Reducer: ValueReducer { public func map(_ transform: @escaping (Reducer.Value) -> T) -> ValueObservation> { - let makeReducer = self.makeReducer - var observation = ValueObservation>( - tracking: observedRegion, - reducer: { db in try makeReducer(db).map(transform) }) - observation.extent = extent - observation.scheduling = scheduling - observation.requiresWriteAccess = requiresWriteAccess - return observation + return mapReducer { $1.map(transform) } } } extension ValueReducer { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// /// Returns a reducer which outputs the results of calling the given /// transformation which each element emitted by this reducer. public func map(_ transform: @escaping (Value) -> T) -> MapValueReducer { @@ -24,6 +19,8 @@ extension ValueReducer { } } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// /// A ValueReducer whose values consist of those in a Base ValueReducer passed /// through a transform function. /// diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift new file mode 100644 index 000000000..baea470b8 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+MapReducer.swift @@ -0,0 +1,15 @@ +extension ValueObservation { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a ValueObservation with a transformed reducer. + public func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) -> ValueObservation { + let makeReducer = self.makeReducer + var observation = ValueObservation( + tracking: observedRegion, + reducer: { db in try transform(db, makeReducer(db)) }) + observation.extent = extent + observation.scheduling = scheduling + observation.requiresWriteAccess = requiresWriteAccess + return observation + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 35dee402f..e041f2e06 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -26,10 +26,12 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingAll(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder == Row { - return ValueObservation.tracking(request, fetchDistinct: request.fetchAll) + return ValueObservation>.tracking(request, reducer: { _ in + RowsReducer(request: request) + }) } /// Creates a ValueObservation which observes *request*, and notifies a @@ -56,9 +58,71 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingOne(_ request: Request) - -> ValueObservation> + -> ValueObservation> where Request.RowDecoder == Row { - return ValueObservation.tracking(request, fetchDistinct: request.fetchOne) + return ValueObservation>.tracking(request, reducer: { _ in + RowReducer(request: request) + }) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of database rows, filtering out +/// consecutive identical arrays. +/// +/// :nodoc: +public struct RowsReducer: ValueReducer + where Request.RowDecoder == Row +{ + public let request: Request + private var previousRows: [Row]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [Row] { + return try request.fetchAll(db) + } + + public mutating func value(_ rows: [Row]) -> [Row]? { + if let previousRows = previousRows, previousRows == rows { + // Don't notify consecutive identical row arrays + return nil + } + self.previousRows = rows + return rows + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct RowReducer: ValueReducer + where Request.RowDecoder == Row +{ + public let request: Request + private var previousRow: Row?? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> Row? { + return try request.fetchOne(db) + } + + public mutating func value(_ row: Row?) -> Row?? { + if let previousRow = previousRow, previousRow == row { + // Don't notify consecutive identical rows + return nil + } + self.previousRow = row + return row } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index e6727c8a9..73a40a483 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -326,7 +326,7 @@ extension ValueObservation where Reducer == Void { public static func tracking( _ regions: DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { return ValueObservation.tracking(regions, fetch: fetch) } @@ -359,11 +359,11 @@ extension ValueObservation where Reducer == Void { public static func tracking( _ regions: [DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> { - return ValueObservation>( + return ValueObservation>( tracking: DatabaseRegion.union(regions), - reducer: { _ in ValueReducers.Raw(fetch) }) + reducer: { _ in RawValueReducer(fetch) }) } /// Creates a ValueObservation which observes *regions*, and notifies the @@ -395,7 +395,7 @@ extension ValueObservation where Reducer == Void { public static func tracking( _ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> where Value: Equatable { return ValueObservation.tracking(regions, fetchDistinct: fetch) @@ -430,11 +430,11 @@ extension ValueObservation where Reducer == Void { public static func tracking( _ regions: [DatabaseRegionConvertible], fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation> where Value: Equatable { - return ValueObservation>( + return ValueObservation>( tracking: DatabaseRegion.union(regions), - reducer: { _ in ValueReducers.Distinct(fetch) }) + reducer: { _ in DistinctValueReducer(fetch) }) } } diff --git a/GRDB/ValueObservation/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer.swift index b2fcc9b12..6828451de 100644 --- a/GRDB/ValueObservation/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer.swift @@ -70,49 +70,49 @@ public struct AnyValueReducer: ValueReducer { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -public enum ValueReducers { - /// A reducer which outputs raw database values, without any processing. - public struct Raw: ValueReducer { - private let _fetch: (Database) throws -> Value - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public func value(_ fetched: Value) -> Value? { - return fetched - } +/// +/// A reducer which outputs raw values. +/// +/// :nodoc: +public struct RawValueReducer: ValueReducer { + private let _fetch: (Database) throws -> Value + + public init(_ fetch: @escaping (Database) throws -> Value) { + self._fetch = fetch } - /// A reducer which outputs raw database values, filtering out consecutive - /// values that are equal. - public struct Distinct: ValueReducer { - private let _fetch: (Database) throws -> Value - private var previousValue: Value?? - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ value: Value) -> Value? { - if let previousValue = previousValue, previousValue == value { - // Don't notify consecutive identical values - return nil - } - self.previousValue = value - return value - } + public func fetch(_ db: Database) throws -> Value { + return try _fetch(db) + } + + public func value(_ fetched: Value) -> Value? { + return fetched + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which filters out consecutive values that are equal. +/// +/// :nodoc: +public struct DistinctValueReducer: ValueReducer { + private let _fetch: (Database) throws -> Value + private var previousValue: Value?? + + public init(_ fetch: @escaping (Database) throws -> Value) { + self._fetch = fetch + } + + public func fetch(_ db: Database) throws -> Value { + return try _fetch(db) + } + + public mutating func value(_ value: Value) -> Value? { + if let previousValue = previousValue, previousValue == value { + // Don't notify consecutive identical values + return nil + } + self.previousValue = value + return value } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index a1843a183..b218fa0cb 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -272,6 +272,8 @@ 564CE4F221B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; 564CE4F321B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1087,6 +1089,7 @@ 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1486,6 +1489,7 @@ 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */, + 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */, 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */, 564CE43F21AA957000652B19 /* ValueObserver.swift */, 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */, @@ -2331,6 +2335,7 @@ 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, + 564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A11EA8D997004A4992 /* Result.swift in Sources */, 560FC5201CB003810014AA8E /* Date.swift in Sources */, 560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -2814,6 +2819,7 @@ 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, + 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A41EA8D997004A4992 /* Result.swift in Sources */, 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */, 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 9bfc3b181..3efd7d639 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -103,6 +103,8 @@ 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; }; 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; + 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -724,6 +726,7 @@ 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1089,6 +1092,7 @@ 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */, + 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */, @@ -1970,6 +1974,7 @@ F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5659F4A51EA8D997004A4992 /* Result.swift in Sources */, + 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, @@ -2274,6 +2279,7 @@ F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5659F4A21EA8D997004A4992 /* Result.swift in Sources */, + 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 50edc1864..bc996d858 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -174,8 +174,8 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { results.append(names) notificationExpectation.fulfill() } - let valueObserver = transactionObserver as! ValueObserver> - XCTAssertEqual(valueObserver.region.description, "t(id,name)") + let valueObserver = transactionObserver as! ValueObserver>> + XCTAssertEqual(valueObserver.region.description, "t(id,name)") // view is not tracked // Test view observation try dbQueue.inDatabase { db in From ce61d27a9ebda5ab7e2ed591ca336cc111b7349e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Dec 2018 01:02:14 +0100 Subject: [PATCH 083/118] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3b48f314..0b5b6b4d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap +- [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. From c7d28de3861abecd86020bf1679e99b4654b3114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Dec 2018 01:10:13 +0100 Subject: [PATCH 084/118] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b5b6b4d2..25eeead19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,6 +111,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). +extension ValueObservation where Reducer: ValueReducer { + func compactMap(_ transform: @escaping (Reducer.Value) -> T?) + -> ValueObservation> ++ func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) ++ -> ValueObservation +} From a8d9f2d82bdfd8258c222663d9dcde11e9b722e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Dec 2018 01:11:58 +0100 Subject: [PATCH 085/118] CHANGELOG --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25eeead19..a98177963 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,11 +111,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). +extension ValueObservation where Reducer: ValueReducer { + func compactMap(_ transform: @escaping (Reducer.Value) -> T?) + -> ValueObservation> ++} + ++extension ValueObservation { + func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) + -> ValueObservation +} - struct Configuration { + var qos: DispatchQoS + var targetQueue: DispatchQueue? From 56d49dd3853966d97e2a283e04154022d11a5a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Dec 2018 10:12:21 +0100 Subject: [PATCH 086/118] Cleanup --- GRDB/Core/DatabasePool.swift | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 621915f87..241723b58 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -403,18 +403,17 @@ extension DatabasePool : DatabaseReader { // isolation has been established: let semaphore = DispatchSemaphore(value: 0) - var readError: Error? = nil - let (reader, release) = try readerPool.get() + var snapshotIsolationError: Error? = nil + let (reader, releaseReader) = try readerPool.get() reader.async { db in defer { _ = try? db.commit() // Ignore commit error - release() + releaseReader() } do { try db.beginSnapshotIsolation() } catch { - // Snapshot isolation failure - readError = error + snapshotIsolationError = error semaphore.signal() // Release the writer queue and rethrow error return } @@ -423,12 +422,13 @@ extension DatabasePool : DatabaseReader { // Reset the schema cache before running user code in snapshot isolation db.schemaCache = SimpleDatabaseSchemaCache() block(db) - } + _ = semaphore.wait(timeout: .distantFuture) - if let readError = readError { + + if let error = snapshotIsolationError { // TODO: write a test for this - throw readError + throw error } } @@ -453,16 +453,15 @@ extension DatabasePool : DatabaseReader { var futureResult: Result? = nil do { - let (reader, release) = try readerPool.get() + let (reader, releaseReader) = try readerPool.get() reader.async { db in defer { try? db.commit() // Ignore commit error - release() + releaseReader() } do { try db.beginSnapshotIsolation() } catch { - // Snapshot isolation failure futureResult = .failure(error) isolationSemaphore.signal() futureSemaphore.signal() @@ -478,7 +477,6 @@ extension DatabasePool : DatabaseReader { // Fetch and release the future futureResult = Result { try block(db) } futureSemaphore.signal() - } } catch { return Future { throw error } From c711ca1e8fe42fd592cc92b0d891343f0aee8ee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 07:58:03 +0100 Subject: [PATCH 087/118] ValueObservation.distinctUntilChanged() --- GRDB.xcodeproj/project.pbxproj | 8 ++++ .../ValueObservation+Count.swift | 4 +- ...alueObservation+DistinctUntilChanged.swift | 47 +++++++++++++++++++ GRDB/ValueObservation/ValueObservation.swift | 42 ++--------------- GRDB/ValueObservation/ValueReducer.swift | 26 ---------- GRDBCipher.xcodeproj/project.pbxproj | 6 +++ GRDBCustom.xcodeproj/project.pbxproj | 6 +++ .../ValueObservationFetchTests.swift | 36 +++++++++++++- 8 files changed, 106 insertions(+), 69 deletions(-) create mode 100644 GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index ca19ec9f6..eefda912e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -214,6 +214,9 @@ 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -978,6 +981,7 @@ 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1405,6 +1409,7 @@ 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */, 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */, 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */, 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */, 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, @@ -2484,6 +2489,7 @@ 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, + 564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, @@ -2728,6 +2734,7 @@ 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, + 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */, 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, ); @@ -3121,6 +3128,7 @@ 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, + 564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift index fec32c862..78ff705bc 100644 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -26,8 +26,8 @@ extension ValueObservation where Reducer == Void { /// - parameter request: the observed request. /// - returns: a ValueObservation. public static func trackingCount(_ request: Request) - -> ValueObservation> + -> ValueObservation>> { - return ValueObservation.tracking(request, fetchDistinct: request.fetchCount) + return ValueObservation.tracking(request, fetch: request.fetchCount).distinctUntilChanged() } } diff --git a/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift b/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift new file mode 100644 index 000000000..a15102a71 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift @@ -0,0 +1,47 @@ +extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable { + /// Returns a ValueObservation which filters out consecutive equal values. + public func distinctUntilChanged() + -> ValueObservation> + { + return mapReducer { $1.distinctUntilChanged() } + } +} + +extension ValueReducer where Value: Equatable { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a ValueReducer which filters out consecutive equal values. + public func distinctUntilChanged() -> DistinctUntilChangedValueReducer { + return DistinctUntilChangedValueReducer(self) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// See ValueReducer.distinctUntilChanged() +/// +/// :nodoc: +public struct DistinctUntilChangedValueReducer: ValueReducer where Base.Value: Equatable { + private var base: Base + private var previousValue: Base.Value? + + init(_ base: Base) { + self.base = base + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> Base.Value? { + guard let value = base.value(fetched) else { + return nil + } + if let previousValue = previousValue, previousValue == value { + // Don't notify consecutive identical values + return nil + } + self.previousValue = value + return value + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 73a40a483..d71776dd5 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -392,49 +392,13 @@ extension ValueObservation where Reducer == Void { /// /// - parameter regions: A list of observed regions. /// - parameter fetch: A closure that fetches a value. + @available(*, deprecated, message: "Use distinctUntilChanged() instead") public static func tracking( _ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> + -> ValueObservation>> where Value: Equatable { - return ValueObservation.tracking(regions, fetchDistinct: fetch) - } - - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. Consecutive equal values - /// are filtered out. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// [Player.all()], - /// fetchDistinct: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: [DatabaseRegionConvertible], - fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - where Value: Equatable - { - return ValueObservation>( - tracking: DatabaseRegion.union(regions), - reducer: { _ in DistinctValueReducer(fetch) }) + return ValueObservation.tracking(regions, fetch: fetch).distinctUntilChanged() } } diff --git a/GRDB/ValueObservation/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer.swift index 6828451de..198e3af36 100644 --- a/GRDB/ValueObservation/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer.swift @@ -90,29 +90,3 @@ public struct RawValueReducer: ValueReducer { } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// A reducer which filters out consecutive values that are equal. -/// -/// :nodoc: -public struct DistinctValueReducer: ValueReducer { - private let _fetch: (Database) throws -> Value - private var previousValue: Value?? - - public init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - public mutating func value(_ value: Value) -> Value? { - if let previousValue = previousValue, previousValue == value { - // Don't notify consecutive identical values - return nil - } - self.previousValue = value - return value - } -} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index b218fa0cb..c26665b2c 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -274,6 +274,8 @@ 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; 564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1090,6 +1092,7 @@ 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1487,6 +1490,7 @@ 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */, 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */, 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */, 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */, @@ -2331,6 +2335,7 @@ 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2815,6 +2820,7 @@ 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3efd7d639..564602505 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -105,6 +105,8 @@ 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -727,6 +729,7 @@ 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1090,6 +1093,7 @@ 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */, 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */, 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */, 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, @@ -1970,6 +1974,7 @@ 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2275,6 +2280,7 @@ 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index e2df19a40..e4755699a 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -22,7 +22,6 @@ class ValueObservationFetchTests: GRDBTestCase { _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetchDistinct: { _ in 0 }) // array _ = ValueObservation.tracking([DatabaseRegion()], fetch: { _ in }) - _ = ValueObservation.tracking([DatabaseRegion()], fetchDistinct: { _ in 0 }) } func testFetch() throws { @@ -57,7 +56,8 @@ class ValueObservationFetchTests: GRDBTestCase { try test(makeDatabasePool()) } - func testFetchWithUniquing() throws { + // Test for a deprecated API + func testFetchDistinct() throws { func test(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -88,4 +88,36 @@ class ValueObservationFetchTests: GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + + func testDistinctUntilChanged() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }).distinctUntilChanged() + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 2]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } } From 88d7c58522391f10fa07ecf10c5c93051b2b8eb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 08:02:18 +0100 Subject: [PATCH 088/118] TODO: remove some magic in GRDB 4 --- GRDB/ValueObservation/ValueObservation+Count.swift | 1 + .../ValueObservation+DatabaseValueConvertible.swift | 4 ++++ GRDB/ValueObservation/ValueObservation+FetchableRecord.swift | 2 ++ GRDB/ValueObservation/ValueObservation+Row.swift | 1 + 4 files changed, 8 insertions(+) diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift index 78ff705bc..a702fc933 100644 --- a/GRDB/ValueObservation/ValueObservation+Count.swift +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -28,6 +28,7 @@ extension ValueObservation where Reducer == Void { public static func trackingCount(_ request: Request) -> ValueObservation>> { + // TODO: Remove distinctUntilChanged in GRDB 4 return ValueObservation.tracking(request, fetch: request.fetchCount).distinctUntilChanged() } } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index c32634532..63577d900 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -124,6 +124,7 @@ public struct DatabaseValuesReducer: ValueReducer public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? { if let previousDbValues = previousDbValues, previousDbValues == dbValues { // Don't notify consecutive identical dbValue arrays + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousDbValues = dbValues @@ -157,6 +158,7 @@ public struct DatabaseValueReducer: ValueReducer public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? { if let previousDbValue = previousDbValue, previousDbValue == dbValue { // Don't notify consecutive identical dbValue + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousDbValue = dbValue @@ -167,6 +169,7 @@ public struct DatabaseValueReducer: ValueReducer return .some(value) } else if previousValueWasNil { // Don't notify consecutive nil values + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } else { previousValueWasNil = true @@ -200,6 +203,7 @@ public struct OptionalDatabaseValuesReducer: ValueReducer public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? { if let previousDbValues = previousDbValues, previousDbValues == dbValues { // Don't notify consecutive identical dbValue arrays + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousDbValues = dbValues diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index 1f18722fd..a9eb2431a 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -91,6 +91,7 @@ public struct FetchableRecordsReducer: ValueReducer public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? { if let previousRows = previousRows, previousRows == rows { // Don't notify consecutive identical row arrays + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousRows = rows @@ -121,6 +122,7 @@ public struct FetchableRecordReducer: ValueReducer public mutating func value(_ row: Row?) -> Request.RowDecoder?? { if let previousRow = previousRow, previousRow == row { // Don't notify consecutive identical rows + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousRow = row diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index e041f2e06..011fa3aa5 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -120,6 +120,7 @@ public struct RowReducer: ValueReducer public mutating func value(_ row: Row?) -> Row?? { if let previousRow = previousRow, previousRow == row { // Don't notify consecutive identical rows + // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 return nil } self.previousRow = row From dd59186887e2bb3285f5c244f0683e39b413309c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 08:24:12 +0100 Subject: [PATCH 089/118] Documentation --- README.md | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 854b88a05..62ac3816c 100644 --- a/README.md +++ b/README.md @@ -6377,6 +6377,8 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me } ``` +> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods perform a filtering of consecutive identical values, based on raw database values. + ### ValueObservation.tracking(_:fetch:) @@ -6436,18 +6438,16 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. -When such a database change happens, `ValueObservation.tracking(_:fetch:)` notifies identical consecutive values. +When such a database change happens, `ValueObservation.tracking(_:fetch:)` is triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. -You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the observed value to adopt the Equatable protocol: +You can filter out those duplicates with the [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) method. It requires the observed value to adopt the Equatable protocol: ```swift extension HallOfFame: Equatable { ... } -let observation = ValueObservation.tracking( - Player.all(), - fetchDistinct: { db -> HallOfFame in - return HallOfFame.fetch(db) - }) +let observation = ValueObservation + .tracking(Player.all(), fetch: HallOfFame.fetch) + .distinctUntilChanged() let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in print(""" @@ -6524,6 +6524,7 @@ let observer = ValueObservation - [ValueObservation.map](#valueobservationmap) - [ValueObservation.compactMap](#valueobservationcompactmap) +- [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) - [ValueObservation.combine(...)](#valueobservationcombine) @@ -6567,6 +6568,30 @@ let observer = observation.start(in: dbQueue) { player: Player in The transformation closure does not run on the main queue, and is suitable for heavy computations. +#### ValueObservation.distinctUntilChanged + +The `distinctUntilChanged` method filters out the consecutive equal values notified by a ValueObservation. The observed values must adopt the standard Equatable protocol. + +For example: + +```swift +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .map { player in player != nil } // existence test + .distinctUntilChanged() + +let observer = observation.start(in: dbQueue) { exists: Bool in + if exists { + print("Player 42 exists.") + } else { + print("Player 42 does not exist.") + } +} +``` + +> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods already perform a similar filtering, based on raw database values. + + #### ValueObservation.combine(...) Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. From d3d5b1d24c28f1613578a5c75250eab36af07723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 08:28:08 +0100 Subject: [PATCH 090/118] CHANGELOG --- CHANGELOG.md | 3 ++- README.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a98177963..277107ac4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer +- [#454](https://github.com/groue/GRDB.swift/pull/454): Value.distinctUntilChanged - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. @@ -68,7 +69,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). ### Documentation Diff - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. -- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine(...)` and `ValueObservation.compactMap(...)` methods. +- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods. ### API diff diff --git a/README.md b/README.md index 62ac3816c..69404ab88 100644 --- a/README.md +++ b/README.md @@ -6267,6 +6267,7 @@ Changes are only notified after they have been committed in the database. No ins - [ValueObservation Transformations](#valueobservation-transformations) - [ValueObservation.map](#valueobservationmap) - [ValueObservation.compactMap](#valueobservationcompactmap) + - [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) - [ValueObservation.combine(...)](#valueobservationcombine) - [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) From 546289bc88544fb99ba6beb5a67f4656b7533faa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 08:29:49 +0100 Subject: [PATCH 091/118] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 277107ac4..d84367934 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,7 +55,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer -- [#454](https://github.com/groue/GRDB.swift/pull/454): Value.distinctUntilChanged +- [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. From 61f2544afefb5c5fdbfa9f9a2cff1247e3bcb020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 08:47:55 +0100 Subject: [PATCH 092/118] Remove a breaking change introduced by #446 --- CHANGELOG.md | 6 +- GRDB/ValueObservation/ValueObservation.swift | 72 ++++++++++++++----- README.md | 19 +++-- .../ValueObservationReducerTests.swift | 54 ++++++++++++-- 4 files changed, 113 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d84367934..4c4ca1807 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update +- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer @@ -61,11 +62,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. -### Breaking Change - -- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation - - ### Documentation Diff - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index d71776dd5..8c752dda3 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -207,7 +207,7 @@ extension ValueObservation { // MARK: - Creating ValueObservation from ValueReducer - /// Returs a ValueObservation which observes *regions*, and notifies the + /// Returns a ValueObservation which observes *regions*, and notifies the /// values returned by the *reducer* whenever one of the observed /// regions is modified by a database transaction. /// @@ -217,13 +217,54 @@ extension ValueObservation { /// table is modified: /// /// var count = 0 - /// let observation = ValueObservation.tracking(Player.all(), reducer: ( db in - /// AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count }) - /// }) + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count }) + /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + @available(*, deprecated, message: "Provide the reducer in a (Database) -> Reducer closure") + public static func tracking( + _ regions: DatabaseRegionConvertible..., + reducer: Reducer) + -> ValueObservation + { + return ValueObservation.tracking(regions, reducer: { _ in reducer }) + } + + /// Returns a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in /* don't fetch anything */ }, + /// value: { _ -> Int? in + /// defer { count += 1 } + /// return count }) + /// let observation = ValueObservation.tracking(Player.all(), reducer: { db in reducer }) /// let observer = observation.start(in: dbQueue) { count: Int in /// print("Players have been modified \(count) times.") /// } @@ -249,7 +290,7 @@ extension ValueObservation { return ValueObservation.tracking(regions, reducer: reducer) } - /// Returs a ValueObservation which observes *regions*, and notifies the + /// Returns a ValueObservation which observes *regions*, and notifies the /// values returned by the *reducer* whenever one of the observed /// regions is modified by a database transaction. /// @@ -259,13 +300,12 @@ extension ValueObservation { /// table is modified: /// /// var count = 0 - /// let observation = ValueObservation.tracking([Player.all()], reducer: ( db in - /// AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count }) - /// }) + /// let reducer = AnyValueReducer( + /// fetch: { _ in /* don't fetch anything */ }, + /// value: { _ -> Int? in + /// defer { count += 1 } + /// return count }) + /// let observation = ValueObservation.tracking([Player.all()], reducer: { db in reducer }) /// let observer = observation.start(in: dbQueue) { count: Int in /// print("Players have been modified \(count) times.") /// } diff --git a/README.md b/README.md index 69404ab88..4025a86a5 100644 --- a/README.md +++ b/README.md @@ -6785,22 +6785,21 @@ The sample code below counts the number of times the player table is modified: ```swift var count = 0 -let observation = ValueObservation.tracking(Player.all(), reducer: { _ in - AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - defer { count += 1 } - return count }) -}) +let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) +let observation = ValueObservation.tracking(Player.all(), reducer: { _ in reducer }) let observer = observation.start(in: dbQueue) { count: Int in - print("\(count) transaction(s) have modified the players.") + print("Number of transactions that have modified players: \(count)") } -// Prints "0 transaction(s) have modified the players." +// Prints "Number of transactions that have modified players: 0" try dbQueue.write { db in try Player(...).insert(db) } -// Prints "1 transaction(s) have modified the players." +// Prints "Number of transactions that have modified players: 1" ``` diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index ca6ca4f40..c34f83a4a 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -205,6 +205,47 @@ class ValueObservationReducerTests: GRDBTestCase { try test(makeDatabasePool()) } + func testDeprecatedReadMeReducer() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // Test for the reducer documented in the main README + + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // Create an observation + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + func testReadMeReducer() throws { func test(_ dbWriter: DatabaseWriter) throws { // Test for the reducer documented in the main README @@ -220,13 +261,12 @@ class ValueObservationReducerTests: GRDBTestCase { // Create an observation var count = 0 - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in - AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - defer { count += 1 } - return count }) - }) + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer}) observation.extent = .databaseLifetime // Start observation From 8ab6e67f0712e4a07c6c4034ec6e9f56eb23bb52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 19:23:06 +0100 Subject: [PATCH 093/118] Hide DatabaseWriter.add(observation:onError:onChange:) from Jazzy --- GRDB/Core/DatabaseWriter.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index b1e531940..52f24bcf9 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -198,6 +198,8 @@ extension DatabaseWriter { // MARK: - Value Observation + /// Default implementation for the DatabaseReader requirement. + /// :nodoc: public func add( observation: ValueObservation, onError: ((Error) -> Void)?, From 82329c899e7c6e960d6a4b8394262e4a7109c022 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 5 Dec 2018 19:27:04 +0100 Subject: [PATCH 094/118] Hide DatabaseWriter.remove(transactionObserver:) from Jazzy --- GRDB/Core/DatabaseWriter.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 52f24bcf9..5dbe867f5 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -129,6 +129,8 @@ extension DatabaseWriter { /// Add a transaction observer, so that it gets notified of /// database changes. /// + /// To remove the observer, use `DatabaseReader.remove(transactionObserver:)`. + /// /// - parameter transactionObserver: A transaction observer. /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer @@ -137,6 +139,8 @@ extension DatabaseWriter { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } + /// Default implementation for the DatabaseReader requirement. + /// :nodoc: public func remove(transactionObserver: TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } From 1e72731c076071a839d0cf2d05ec7da2d044264c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 07:04:40 +0100 Subject: [PATCH 095/118] Distinguish distinctUntilChanged from distinctUntilDatabaseChanged --- .../ValueObservation+DatabaseValueConvertible.swift | 8 ++++---- .../ValueObservation+FetchableRecord.swift | 4 ++-- GRDB/ValueObservation/ValueObservation+Row.swift | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 63577d900..de4b240d6 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -124,7 +124,7 @@ public struct DatabaseValuesReducer: ValueReducer public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? { if let previousDbValues = previousDbValues, previousDbValues == dbValues { // Don't notify consecutive identical dbValue arrays - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousDbValues = dbValues @@ -158,7 +158,7 @@ public struct DatabaseValueReducer: ValueReducer public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? { if let previousDbValue = previousDbValue, previousDbValue == dbValue { // Don't notify consecutive identical dbValue - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousDbValue = dbValue @@ -169,7 +169,7 @@ public struct DatabaseValueReducer: ValueReducer return .some(value) } else if previousValueWasNil { // Don't notify consecutive nil values - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } else { previousValueWasNil = true @@ -203,7 +203,7 @@ public struct OptionalDatabaseValuesReducer: ValueReducer public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? { if let previousDbValues = previousDbValues, previousDbValues == dbValues { // Don't notify consecutive identical dbValue arrays - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousDbValues = dbValues diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index a9eb2431a..2a3ac9d7c 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -91,7 +91,7 @@ public struct FetchableRecordsReducer: ValueReducer public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? { if let previousRows = previousRows, previousRows == rows { // Don't notify consecutive identical row arrays - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousRows = rows @@ -122,7 +122,7 @@ public struct FetchableRecordReducer: ValueReducer public mutating func value(_ row: Row?) -> Request.RowDecoder?? { if let previousRow = previousRow, previousRow == row { // Don't notify consecutive identical rows - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousRow = row diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index 011fa3aa5..e3c1f55ba 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -120,7 +120,7 @@ public struct RowReducer: ValueReducer public mutating func value(_ row: Row?) -> Row?? { if let previousRow = previousRow, previousRow == row { // Don't notify consecutive identical rows - // TODO: Remove this implicit `distinctUntilChanged` in GRDB 4 + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 return nil } self.previousRow = row From 6ec4556c2ce38611fb83945ea524e1586e038050 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 07:49:41 +0100 Subject: [PATCH 096/118] DatabaseRegionObservation --- GRDB.xcodeproj/project.pbxproj | 8 +++ GRDB/Core/DatabaseRegionObservation.swift | 69 +++++++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 6 ++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ 4 files changed, 89 insertions(+) create mode 100644 GRDB/Core/DatabaseRegionObservation.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index eefda912e..9b13eb1d4 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -217,6 +217,9 @@ 564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -982,6 +985,7 @@ 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1821,6 +1825,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */, + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2477,6 +2482,7 @@ 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, + 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, @@ -2714,6 +2720,7 @@ C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, + 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -3142,6 +3149,7 @@ 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, + 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift new file mode 100644 index 000000000..23d756d48 --- /dev/null +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -0,0 +1,69 @@ +public final class DatabaseRegionObservation { + /// A closure that is evaluated when the observation starts, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + public init(tracking region: @escaping (Database) throws -> DatabaseRegion) { + 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) + } + } + + public convenience init(tracking regions: DatabaseRegionConvertible...) { + self.init(tracking: regions) + } + + public convenience init(tracking regions: [DatabaseRegionConvertible]) { + self.init(tracking: DatabaseRegion.union(regions)) + } +} + +extension DatabaseWriter { + public func add(observation: DatabaseRegionObservation, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + return try writeWithoutTransaction { db -> TransactionObserver in + let region = try observation.observedRegion(db) + let observer = DatabaseRegionObserver(region: region, onChange: onChange) + add(transactionObserver: observer) + return observer + } + } +} + +private class DatabaseRegionObserver: TransactionObserver { + let region: DatabaseRegion + let onChange: (Database) -> Void + var isChanged = false + + init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) { + self.region = region + self.onChange = onChange + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + isChanged = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidCommit(_ db: Database) { + guard isChanged else { return } + isChanged = false + + onChange(db) + } + + func databaseDidRollback(_ db: Database) { + isChanged = false + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index c26665b2c..d43baa2b1 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -276,6 +276,8 @@ 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; 564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1093,6 +1095,7 @@ 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1887,6 +1890,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */, + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2409,6 +2413,7 @@ 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, @@ -2894,6 +2899,7 @@ 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 564602505..7b92d899d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -107,6 +107,8 @@ 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; 564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -730,6 +732,7 @@ 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1497,6 +1500,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */, + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -2048,6 +2052,7 @@ 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, @@ -2354,6 +2359,7 @@ 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, From e3681fdde5fa17790a38e56f85d5dab2e8c24008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:28:43 +0100 Subject: [PATCH 097/118] DatabaseRegionObservationTests --- GRDB.xcodeproj/project.pbxproj | 6 + GRDB/Core/DatabaseRegionObservation.swift | 20 +- GRDBCipher.xcodeproj/project.pbxproj | 10 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../DatabaseRegionObservationTests.swift | 195 ++++++++++++++++++ 5 files changed, 229 insertions(+), 8 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseRegionObservationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9b13eb1d4..1782e4008 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -220,6 +220,8 @@ 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -986,6 +988,7 @@ 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1728,6 +1731,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2879,6 +2883,7 @@ 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, + 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, @@ -3058,6 +3063,7 @@ 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, + 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 23d756d48..b34afe430 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -1,4 +1,6 @@ -public final class DatabaseRegionObservation { +public struct DatabaseRegionObservation { + public var extent = Database.TransactionObservationExtent.observerLifetime + /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion @@ -15,21 +17,23 @@ public final class DatabaseRegionObservation { } } - public convenience init(tracking regions: DatabaseRegionConvertible...) { + public init(tracking regions: DatabaseRegionConvertible...) { self.init(tracking: regions) } - public convenience init(tracking regions: [DatabaseRegionConvertible]) { + public init(tracking regions: [DatabaseRegionConvertible]) { self.init(tracking: DatabaseRegion.union(regions)) } } -extension DatabaseWriter { - public func add(observation: DatabaseRegionObservation, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { - return try writeWithoutTransaction { db -> TransactionObserver in - let region = try observation.observedRegion(db) +extension DatabaseRegionObservation { + public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + // Use unsafeReentrantWrite so that observation can start from any + // dispatch queue. + return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in + let region = try observedRegion(db) let observer = DatabaseRegionObserver(region: region, onChange: onChange) - add(transactionObserver: observer) + db.add(transactionObserver: observer, extent: extent) return observer } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index d43baa2b1..3f14b05e5 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -278,6 +278,10 @@ 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; 564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -1096,6 +1100,7 @@ 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1793,6 +1798,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2569,6 +2575,7 @@ 565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, 564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -2748,6 +2755,7 @@ 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, @@ -3055,6 +3063,7 @@ 56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, @@ -3234,6 +3243,7 @@ 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7b92d899d..91458697c 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -109,6 +109,8 @@ 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -733,6 +735,7 @@ 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1403,6 +1406,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -2208,6 +2212,7 @@ F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, @@ -2515,6 +2520,7 @@ F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift new file mode 100644 index 000000000..92e51526c --- /dev/null +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -0,0 +1,195 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class DatabaseRegionObservationTests: GRDBTestCase { + func testDatabaseRegionObservation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + let request = SQLRequest("SELECT * FROM t ORDER BY id") + let observation = DatabaseRegionObservation(tracking: { db in + try request.databaseRegion(db) + }) + let observer = try observation.start(in: dbQueue) { db in + let rows = try! request.fetchAll(db) + results.append(rows) + notificationExpectation.fulfill() + } + try withExtendedLifetime(observer) { + 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, [ + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"], ["id":2, "name":"bar"]], + [["id":2, "name":"bar"]]]) + } + + func testDatabaseRegionObservationVariadic() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + let request1 = SQLRequest("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("SELECT * FROM t2 ORDER BY id") + + var observation = DatabaseRegionObservation(tracking: request1, request2) + observation.extent = .databaseLifetime + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + + func testDatabaseRegionObservationArray() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + let request1 = SQLRequest("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("SELECT * FROM t2 ORDER BY id") + + var observation = DatabaseRegionObservation(tracking: [request1, request2]) + observation.extent = .databaseLifetime + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + + func testDatabaseRegionDefaultExtent() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let observation = DatabaseRegionObservation(tracking: SQLRequest("SELECT * FROM t ORDER BY id")) + + var count = 0 + do { + let observer = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + } + } + } + // not notified + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 2) + } + + func testDatabaseRegionExtentNextTransaction() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + var observation = DatabaseRegionObservation(tracking: SQLRequest("SELECT * FROM t ORDER BY id")) + observation.extent = .nextTransaction + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 1) + } +} From 78bb086f69f4a801706a9003f06630c46b700c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:43:44 +0100 Subject: [PATCH 098/118] Documentation --- GRDB/Core/DatabaseRegionObservation.swift | 62 ++++++++++++++++++- GRDB/ValueObservation/ValueObservation.swift | 3 +- .../DatabaseRegionObservationTests.swift | 1 + 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index b34afe430..a55fd2b3f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -1,11 +1,26 @@ +/// DatabaseRegionObservation tracks changes in the results of database +/// requests, and notifies each database transaction whenever the +/// database changes. +/// +/// For example: +/// +/// let observation = DatabaseRegionObservation(tracking: Player.all) +/// let observer = try observation.start(in: dbQueue) { db: Database in +/// print("Players have changed.") +/// } public struct DatabaseRegionObservation { + /// The extent of the database observation. The default is + /// `.observerLifetime`: the observation lasts until the + /// observer returned by the `start(in:onChange:)` method + /// is deallocated. public var extent = Database.TransactionObservationExtent.observerLifetime /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion - public init(tracking region: @escaping (Database) throws -> DatabaseRegion) { + // Not public because we foster DatabaseRegionConvertible. + init(tracking region: @escaping (Database) throws -> DatabaseRegion) { self.observedRegion = { db in // Remove views from the observed region. // @@ -17,16 +32,61 @@ public struct DatabaseRegionObservation { } } + /// Creates a DatabaseRegionObservation which observes *regions*, and + /// notifies whenever one of the observed regions is modified by a + /// database transaction. + /// + /// For example, this sample code counts the number of a times the player + /// table is modified: + /// + /// let observation = DatabaseRegionObservation(tracking: Player.all()) + /// + /// var count = 0 + /// let observer = observation.start(in: dbQueue) { _ in + /// count += 1 + /// print("Players have been modified \(count) times.") + /// } + /// + /// The observation lasts until the observer returned by `start` is + /// deallocated. See the `extent` property for more information. + /// + /// - parameter regions: A list of observed regions. public init(tracking regions: DatabaseRegionConvertible...) { self.init(tracking: regions) } + /// Creates a DatabaseRegionObservation which observes *regions*, and + /// notifies whenever one of the observed regions is modified by a + /// database transaction. + /// + /// For example, this sample code counts the number of a times the player + /// table is modified: + /// + /// let observation = DatabaseRegionObservation(tracking: [Player.all()]) + /// + /// var count = 0 + /// let observer = observation.start(in: dbQueue) { _ in + /// count += 1 + /// print("Players have been modified \(count) times.") + /// } + /// + /// The observation lasts until the observer returned by `start` is + /// deallocated. See the `extent` property for more information. + /// + /// - parameter regions: A list of observed regions. public init(tracking regions: [DatabaseRegionConvertible]) { self.init(tracking: DatabaseRegion.union(regions)) } } extension DatabaseRegionObservation { + /// Starts the observation in the provided database writer (such as + /// a database queue or database pool), and returns a transaction observer. + /// + /// - parameter reader: A DatabaseWriter. + /// - parameter onChange: A closure that is provided a database connection + /// with write access each time the observed region has been modified. + /// - returns: a TransactionObserver public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 8c752dda3..b142571df 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -164,7 +164,8 @@ public struct ValueObservation { } } - // Not public. See ValueObservation.tracking(_:reducer:) + // Not public because we foster DatabaseRegionConvertible. + // See ValueObservation.tracking(_:reducer:) init( tracking region: @escaping (Database) throws -> DatabaseRegion, reducer: @escaping (Database) throws -> Reducer) diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index 92e51526c..aa9a99f87 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -185,6 +185,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { try dbQueue.write { db in try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") } + // not notified try dbQueue.write { db in try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") } From 1472385242505c50b257f6624d6f6d614087bac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 08:55:31 +0100 Subject: [PATCH 099/118] Documentation --- README.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4025a86a5..3aee35ba5 100644 --- a/README.md +++ b/README.md @@ -2061,7 +2061,7 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.5/Structs/Configuration.html) - `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.5/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) -- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [ValueObservation], [FetchedRecordsController] +- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController] - `sqlite3_config`: see [Error Log](#error-log) - `sqlite3_create_collation_v2`: see [String Comparison](#string-comparison) - `sqlite3_db_release_memory`: see [Memory Management](#memory-management) @@ -4571,7 +4571,7 @@ The `prepare` method returns a prepared statement and an optional row adapter. T The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. -The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), and [ValueObservation]. +The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), [DatabaseRegionObservation], and [ValueObservation]. The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -5848,6 +5848,7 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): The simplest way to handle successful transactions. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. +- [DatabaseRegionObservation]: Focused tracking of database transactions. - [ValueObservation]: Automated tracking of database changes. - [FetchedRecordsController]: Automated tracking of database changes, with table view animations. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). @@ -6038,7 +6039,7 @@ do { > :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. -[ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. +[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. @@ -6254,6 +6255,23 @@ protocol TransactionObserverType : class { ``` +## DatabaseRegionObservation + +**ValueObservation tracks changes in the results of database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** + +Transactions are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + + +### DatabaseRegionObservation Usage + +```swift +let observation = DatabaseRegionObservation(tracking: Player.all()) +let observer = observation.start(in: dbQueue) { db: Database in + print("Players were changed") +} +``` + + ## ValueObservation **ValueObservation tracks changes in the results of database [requests](#requests), and notifies fresh values whenever the database changes.** @@ -7957,6 +7975,7 @@ Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.gith These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: - [Migrations](#migrations) +- [DatabaseRegionObservation] - [ValueObservation] - [FetchedRecordsController] - [RxGRDB] @@ -8519,5 +8538,6 @@ This chapter has been renamed [Beyond FetchableRecord]. [Record Customization Options]: #record-customization-options [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation +[DatabaseRegionObservation]: #databaseregionobservation [FetchedRecordsController]: #fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file From 194624212eb7119195c41e944e94aee24751005f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:33:17 +0100 Subject: [PATCH 100/118] Move db observation documentations around --- README.md | 753 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 429 insertions(+), 324 deletions(-) diff --git a/README.md b/README.md index 3aee35ba5..db21aacb1 100644 --- a/README.md +++ b/README.md @@ -5846,11 +5846,12 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: -- [After Commit Hook](#after-commit-hook): The simplest way to handle successful transactions. +- [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. +- [ValueObservation and DatabaseRegionObservation](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. + - [DatabaseRegionObservation] + - [ValueObservation] +- [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. -- [DatabaseRegionObservation]: Focused tracking of database transactions. -- [ValueObservation]: Automated tracking of database changes. -- [FetchedRecordsController]: Automated tracking of database changes, with table view animations. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage. @@ -5915,362 +5916,125 @@ try dbQueue.write { db in ``` -## TransactionObserver Protocol +## ValueObservation and DatabaseRegionObservation -The `TransactionObserver` protocol lets you **observe database changes and transactions**: +**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests): ```swift -protocol TransactionObserver : class { - /// Notifies a database change: - /// - event.kind (insert, update, or delete) - /// - event.tableName - /// - event.rowID - /// - /// For performance reasons, the event is only valid for the duration of - /// this method call. If you need to keep it longer, store a copy: - /// event.copy(). - func databaseDidChange(with event: DatabaseEvent) - - /// Filters the database changes that should be notified to the - /// `databaseDidChange(with:)` method. - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - - /// An opportunity to rollback pending changes by throwing an error. - func databaseWillCommit() throws - - /// Database changes have been committed. - func databaseDidCommit(_ db: Database) - - /// Database changes have been rollbacked. - func databaseDidRollback(_ db: Database) -} +// Two observations that track the players: +let request = Player.all() +let valueObservation = ValueObservation.trackingAll(request) +let regionObservation = DatabaseRegionObservation(tracking: request) ``` -- [Activate a Transaction Observer](#activate-a-transaction-observer) -- [Database Changes And Transactions](#database-changes-and-transactions) -- [Filtering Database Events](#filtering-database-events) -- [Observation Extent](#observation-extent) -- [DatabaseRegion](#databaseregion) -- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - - -### Activate a Transaction Observer - -**To activate a transaction observer, add it to the database queue or pool:** +[ValueObservation] notifies your application with **fresh values**. This is what most applications need: ```swift -let observer = MyObserver() -dbQueue.add(transactionObserver: observer) -``` - -By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options. - - -### Database Changes And Transactions - -**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). - -> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). - -Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: - -```swift -try dbQueue.write { db in - try db.execute("INSERT ...") // 1. didChange - try db.execute("UPDATE ...") // 2. didChange -} // 3. willCommit, 4. didCommit - -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // 1. didChange - try db.execute("UPDATE ...") // 2. didChange - return .rollback // 3. didRollback +let observer = valueObservation.start(in: dbQueue) { players: [Player] in + print("Player have changed: \(players)") } try dbQueue.write { db in - try db.execute("INSERT ...") // 1. didChange - throw SomeError() -} // 2. didRollback -``` - -Database statements that are executed outside of any transaction do not drop off the radar: - -```swift -try dbQueue.inDatabase { db in - try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit - try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit + try Player(name: "Arthur").insert(db) } +// Prints "Players have changed: ..." + ``` -Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed: +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed: ```swift -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // 1. didChange - - try db.execute("SAVEPOINT foo") - try db.execute("UPDATE ...") // delayed - try db.execute("UPDATE ...") // delayed - try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange - - try db.execute("SAVEPOINT foo") - try db.execute("UPDATE ...") // not notified - try db.execute("ROLLBACK TO SAVEPOINT foo") - - return .commit // 4. willCommit, 5. didCommit +let observer = regionObservation.start(in: dbQueue) { db: Database in + print("Player have changed.") } -``` - -**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: - -```swift -do { - try dbQueue.inTransaction { db in - ... - return .commit // 1. willCommit (throws), 2. didRollback - } -} catch { - // 3. The error thrown by the transaction observer. -} -``` - -> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. -> -> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. - - -[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. - -See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. - - -### Filtering Database Events - -**Transaction observers can avoid being notified of database changes they are not interested in.** - -The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: - -```swift -class PlayerObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "player" table. - return eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - // This method is only called for changes that happen to - // the "player" table. - } -} -``` - -Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed: - -```swift -class PlayerScoreObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "score" column of the "player" table. - switch eventKind { - case .insert(let tableName): - return tableName == "player" - case .delete(let tableName): - return tableName == "player" - case .update(let tableName, let columnNames): - return tableName == "player" && columnNames.contains("score") - } - } -} -``` - -When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks: - -```swift -class PureTransactionObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Ignore all individual changes - return false - } - - func databaseDidChange(with event: DatabaseEvent) { /* Never called */ } - func databaseWillCommit() throws { /* Called before commit */ } - func databaseDidRollback(_ db: Database) { /* Called on rollback */ } - func databaseDidCommit(_ db: Database) { /* Called on commit */ } -} -``` - -For more information about event filtering, see [DatabaseRegion](#databaseregion). - - -### Observation Extent - -**You can specify how long an observer is notified of database changes and transactions.** - -The `remove(transactionObserver:)` method explicitly stops notifications, at any time: - -```swift -// From a database queue or pool: -dbQueue.remove(transactionObserver: observer) - -// From a database connection: -dbQueue.inDatabase { db in - db.remove(transactionObserver: observer) -} -``` - -Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: - -```swift -let observer = MyObserver() - -// On a database queue or pool: -dbQueue.add(transactionObserver: observer) // default extent -dbQueue.add(transactionObserver: observer, extent: .observerLifetime) -dbQueue.add(transactionObserver: observer, extent: .nextTransaction) -dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - -// On a database connection: -dbQueue.inDatabase { db in - db.add(transactionObserver: ...) -} -``` - -- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions. - -- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification. - -- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. - -Finally, an observer may ignore all database changes until the end of the current transaction: - -```swift -class PlayerObserver: TransactionObserver { - var playerTableWasModified = false - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - playerTableWasModified = true - - // It is pointless to keep on tracking further changes: - stopObservingDatabaseChangesUntilNextTransaction() - } -} -``` - -After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation. - - -### DatabaseRegion - -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. - -A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region. - -You start by building regions: - -```swift try dbQueue.write { db in - let teamRegion = try Team.filter(key: 1).databaseRegion(db) - let playersRegion = try SQLRequest("SELECT * FROM player").databaseRegion(db) - let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db) + try Player(name: "Barbara").insert(db) +} +// Prints "Players have changed." ``` -You can group regions: - -```swift - let region = teamRegion.union(playersRegion).union(maxScoreRegion) -} -``` - -There are two special regions: `DatabaseRegion()` (the empty region), and `DatabaseRegion.fullDatabase` (the region that spans the whole database). - -Regions feed the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example: - -```swift -// A transaction observer which notifies all changes to a database region. -class DatabaseRegionObserver: TransactionObserver { - let region: DatabaseRegion - var regionIsModified = false - - init(region: DatabaseRegion) { - self.region = region - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - regionIsModified = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidRollback(_ db: Database) { - regionIsModified = false - } - - func databaseDidCommit(_ db: Database) { - if regionIsModified == false { return } - regionIsModified = false - - // You'll customize your handling of changes here: - print("Region has been modified.") - } -} - -// Observe a region -try dbQueue.write { db in - observer = DatabaseRegionObserver(region: region) - db.add(transactionObserver: observer) -} -``` - -A region notifies *potential* changes, not *actual* changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. - -For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. - -Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key *is* the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. - - -### Support for SQLite Pre-Update Hooks - -A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: - -```swift -protocol TransactionObserverType : class { - #if SQLITE_ENABLE_PREUPDATE_HOOK - /// Notifies before a database change (insert, update, or delete) - /// with change information (initial / final values for the row's - /// columns). - /// - /// The event is only valid for the duration of this method call. If you - /// need to keep it longer, store a copy: event.copy(). - func databaseWillChange(with event: DatabasePreUpdateEvent) - #endif -} -``` +Both observations are based on the low-level [TransactionObserver Protocol](#transactionobserver-protocol). ## DatabaseRegionObservation -**ValueObservation tracks changes in the results of database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** +**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** -Transactions are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +No insertion, update, or deletion in the tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation. ### DatabaseRegionObservation Usage +Define an observation by providing one or several requests to track: + ```swift +// Track all players let observation = DatabaseRegionObservation(tracking: Player.all()) +``` + +Then start the observation from a [database queue](#database-queues) or [pool](#database-pools): + +```swift let observer = observation.start(in: dbQueue) { db: Database in print("Players were changed") } ``` +And enjoy the changes notifications: + +```swift +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} +// Prints "Players were changed" +``` + +By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. + + +### DatabaseRegionObservation Use Cases + +**There are very few use cases for DatabaseRegionObservation**. + +For example: + +- One needs to write in the database after an impactful transaction. + +- One needs to synchronize the content of the database file with some external resources, like other files, or system sensors like CLRegion monitoring. + +- On iOS, one needs to process a database transaction before the operating system had any opportunity to put the application in the suspended state. + +- One want to build a [database snapshot](#database-snapshots) with a guaranteed snapshot content. + +Outside of those use cases, it is much likely *wrong* to use a DatabaseRegionObservation. Please check other [Database Observation](#database-changes-observation) options. + + +### DatabaseRegionObservation.extent + +The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: + +```swift +// This observation lasts until the database connection is closed +var observation = DatabaseRegionObservation... +observation.extent = .databaseLifetime +_ = observation.start(in: dbQueue) { db in ... } +``` + +The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated. + +Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: + +```swift +// Start +let observer = observation.start(in: dbQueue) { db in ... } + +// Stop +dbQueue.remove(transactionObserver: observer) +``` + ## ValueObservation @@ -6821,6 +6585,7 @@ try dbQueue.write { db in ``` + ## FetchedRecordsController **FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.** @@ -7161,6 +6926,346 @@ try controller.performFetch() > ``` +## TransactionObserver Protocol + +The `TransactionObserver` protocol lets you **observe individual database changes and transactions**: + +```swift +protocol TransactionObserver : class { + /// Notifies a database change: + /// - event.kind (insert, update, or delete) + /// - event.tableName + /// - event.rowID + /// + /// For performance reasons, the event is only valid for the duration of + /// this method call. If you need to keep it longer, store a copy: + /// event.copy(). + func databaseDidChange(with event: DatabaseEvent) + + /// Filters the database changes that should be notified to the + /// `databaseDidChange(with:)` method. + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool + + /// An opportunity to rollback pending changes by throwing an error. + func databaseWillCommit() throws + + /// Database changes have been committed. + func databaseDidCommit(_ db: Database) + + /// Database changes have been rollbacked. + func databaseDidRollback(_ db: Database) +} +``` + +- [Activate a Transaction Observer](#activate-a-transaction-observer) +- [Database Changes And Transactions](#database-changes-and-transactions) +- [Filtering Database Events](#filtering-database-events) +- [Observation Extent](#observation-extent) +- [DatabaseRegion](#databaseregion) +- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) + + +### Activate a Transaction Observer + +**To activate a transaction observer, add it to the database queue or pool:** + +```swift +let observer = MyObserver() +dbQueue.add(transactionObserver: observer) +``` + +By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options. + + +### Database Changes And Transactions + +**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). + +Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: + +```swift +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + try db.execute("UPDATE ...") // 2. didChange +} // 3. willCommit, 4. didCommit + +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // 1. didChange + try db.execute("UPDATE ...") // 2. didChange + return .rollback // 3. didRollback +} + +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + throw SomeError() +} // 2. didRollback +``` + +Database statements that are executed outside of any transaction do not drop off the radar: + +```swift +try dbQueue.inDatabase { db in + try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit + try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit +} +``` + +Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed: + +```swift +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // 1. didChange + + try db.execute("SAVEPOINT foo") + try db.execute("UPDATE ...") // delayed + try db.execute("UPDATE ...") // delayed + try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange + + try db.execute("SAVEPOINT foo") + try db.execute("UPDATE ...") // not notified + try db.execute("ROLLBACK TO SAVEPOINT foo") + + return .commit // 4. willCommit, 5. didCommit +} +``` + + +**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: + +```swift +do { + try dbQueue.inTransaction { db in + ... + return .commit // 1. willCommit (throws), 2. didRollback + } +} catch { + // 3. The error thrown by the transaction observer. +} +``` + +> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. +> +> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. + + +[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. + +See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. + + +### Filtering Database Events + +**Transaction observers can avoid being notified of database changes they are not interested in.** + +The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: + +```swift +class PlayerObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Only observe changes to the "player" table. + return eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + // This method is only called for changes that happen to + // the "player" table. + } +} +``` + +Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed: + +```swift +class PlayerScoreObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Only observe changes to the "score" column of the "player" table. + switch eventKind { + case .insert(let tableName): + return tableName == "player" + case .delete(let tableName): + return tableName == "player" + case .update(let tableName, let columnNames): + return tableName == "player" && columnNames.contains("score") + } + } +} +``` + +When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks: + +```swift +class PureTransactionObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Ignore all individual changes + return false + } + + func databaseDidChange(with event: DatabaseEvent) { /* Never called */ } + func databaseWillCommit() throws { /* Called before commit */ } + func databaseDidRollback(_ db: Database) { /* Called on rollback */ } + func databaseDidCommit(_ db: Database) { /* Called on commit */ } +} +``` + +For more information about event filtering, see [DatabaseRegion](#databaseregion). + + +### Observation Extent + +**You can specify how long an observer is notified of database changes and transactions.** + +The `remove(transactionObserver:)` method explicitly stops notifications, at any time: + +```swift +// From a database queue or pool: +dbQueue.remove(transactionObserver: observer) + +// From a database connection: +dbQueue.inDatabase { db in + db.remove(transactionObserver: observer) +} +``` + +Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: + +```swift +let observer = MyObserver() + +// On a database queue or pool: +dbQueue.add(transactionObserver: observer) // default extent +dbQueue.add(transactionObserver: observer, extent: .observerLifetime) +dbQueue.add(transactionObserver: observer, extent: .nextTransaction) +dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) + +// On a database connection: +dbQueue.inDatabase { db in + db.add(transactionObserver: ...) +} +``` + +- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions. + +- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification. + +- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. + +Finally, an observer may ignore all database changes until the end of the current transaction: + +```swift +class PlayerObserver: TransactionObserver { + var playerTableWasModified = false + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + playerTableWasModified = true + + // It is pointless to keep on tracking further changes: + stopObservingDatabaseChangesUntilNextTransaction() + } +} +``` + +After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation. + + +### DatabaseRegion + +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. + +A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region. + +You start by building regions: + +```swift +try dbQueue.write { db in + let teamRegion = try Team.filter(key: 1).databaseRegion(db) + let playersRegion = try SQLRequest("SELECT * FROM player").databaseRegion(db) + let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db) +``` + +You can group regions: + +```swift + let region = teamRegion.union(playersRegion).union(maxScoreRegion) +} +``` + +There are two special regions: `DatabaseRegion()` (the empty region), and `DatabaseRegion.fullDatabase` (the region that spans the whole database). + +Regions feed the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example: + +```swift +// A transaction observer which notifies all changes to a database region. +class DatabaseRegionObserver: TransactionObserver { + let region: DatabaseRegion + var regionIsModified = false + + init(region: DatabaseRegion) { + self.region = region + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + regionIsModified = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidRollback(_ db: Database) { + regionIsModified = false + } + + func databaseDidCommit(_ db: Database) { + if regionIsModified == false { return } + regionIsModified = false + + // You'll customize your handling of changes here: + print("Region has been modified.") + } +} + +// Observe a region +try dbQueue.write { db in + observer = DatabaseRegionObserver(region: region) + db.add(transactionObserver: observer) +} +``` + +A region notifies *potential* changes, not *actual* changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. + +For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. + +Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key *is* the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. + + +### Support for SQLite Pre-Update Hooks + +A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: + +```swift +protocol TransactionObserverType : class { + #if SQLITE_ENABLE_PREUPDATE_HOOK + /// Notifies before a database change (insert, update, or delete) + /// with change information (initial / final values for the row's + /// columns). + /// + /// The event is only valid for the duration of this method call. If you + /// need to keep it longer, store a copy: event.copy(). + func databaseWillChange(with event: DatabasePreUpdateEvent) + #endif +} +``` + + Encryption ========== From fd79a53a96e1ef5291bc61814651c7fac83ec16d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:34:02 +0100 Subject: [PATCH 101/118] Documentation --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index db21aacb1..89b4c0d10 100644 --- a/README.md +++ b/README.md @@ -5848,8 +5848,6 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. - [ValueObservation and DatabaseRegionObservation](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. - - [DatabaseRegionObservation] - - [ValueObservation] - [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). From bc5899543f78fcc5ea7c6a3b9c19bb2e13b231b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:55:08 +0100 Subject: [PATCH 102/118] Documentation --- README.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 89b4c0d10..03c5a6538 100644 --- a/README.md +++ b/README.md @@ -5925,7 +5925,7 @@ let valueObservation = ValueObservation.trackingAll(request) let regionObservation = DatabaseRegionObservation(tracking: request) ``` -[ValueObservation] notifies your application with **fresh values**. This is what most applications need: +[ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift let observer = valueObservation.start(in: dbQueue) { players: [Player] in @@ -5939,7 +5939,7 @@ try dbQueue.write { db in ``` -[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed: +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for advanced use cases :nerd_face:): ```swift let observer = regionObservation.start(in: dbQueue) { db: Database in @@ -5952,8 +5952,6 @@ try dbQueue.write { db in // Prints "Players have changed." ``` -Both observations are based on the low-level [TransactionObserver Protocol](#transactionobserver-protocol). - ## DatabaseRegionObservation @@ -6044,11 +6042,7 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [ValueObservation Transformations](#valueobservation-transformations) - - [ValueObservation.map](#valueobservationmap) - - [ValueObservation.compactMap](#valueobservationcompactmap) - - [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) - - [ValueObservation.combine(...)](#valueobservationcombine) +- [ValueObservation Transformations](#valueobservation-transformations): ([map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ...) - [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) - [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) From 9a3e6f0b975399d21834e24468d26225934f8fb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 13:58:47 +0100 Subject: [PATCH 103/118] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c4ca1807..b25f96591 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer - [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged +- [#455](https://github.com/groue/GRDB.swift/pull/455): DatabaseRegionObservation - [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. @@ -66,6 +67,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. - [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods. +- [DatabaseRegionObservation](README.md#databaseregionobservation): this chapter describes the new `DatabaseRegionObservation` type. ### API diff From 73935dfa9d7f416027fd02f79da3741524b24162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 14:02:10 +0100 Subject: [PATCH 104/118] CHANGELOG --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b25f96591..f0795c51a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -121,6 +121,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). + var qos: DispatchQoS + var targetQueue: DispatchQueue? } + ++struct DatabaseRegionObservation { ++ var extent: Database.TransactionObservationExtent ++ init(tracking regions: DatabaseRegionConvertible...) ++ init(tracking regions: [DatabaseRegionConvertible]) ++ func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver ++} ``` From 862563fdaad93053d5ba1c4eece6056461e6a0a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 16:42:20 +0100 Subject: [PATCH 105/118] Remove obsolete test --- .../DatabaseRegionObservationTests.swift | 41 ------------------- 1 file changed, 41 deletions(-) diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index aa9a99f87..dff415cc5 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -13,47 +13,6 @@ import XCTest #endif class DatabaseRegionObservationTests: GRDBTestCase { - func testDatabaseRegionObservation() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } - - var results: [[Row]] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - let request = SQLRequest("SELECT * FROM t ORDER BY id") - let observation = DatabaseRegionObservation(tracking: { db in - try request.databaseRegion(db) - }) - let observer = try observation.start(in: dbQueue) { db in - let rows = try! request.fetchAll(db) - results.append(rows) - notificationExpectation.fulfill() - } - try withExtendedLifetime(observer) { - 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, [ - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"]], - [["id":1, "name":"foo"], ["id":2, "name":"bar"]], - [["id":2, "name":"bar"]]]) - } - func testDatabaseRegionObservationVariadic() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { From 03934041c27d937d371a6d0b2664827e5ed07077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:41:43 +0100 Subject: [PATCH 106/118] Fix DatabaseRegion doc layout --- GRDB/Core/DatabaseRegion.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 737cfd8fc..042bf335a 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -18,15 +18,15 @@ /// /// - `SelectStatement.databaseRegion`: /// -/// let statement = db.makeSelectStatement("SELECT name, score FROM player") -/// print(statement.databaseRegion) -/// // prints "player(name,score)" +/// let statement = db.makeSelectStatement("SELECT name, score FROM player") +/// print(statement.databaseRegion) +/// // prints "player(name,score)" /// /// - `FetchRequest.databaseRegion(_:)` /// -/// let request = Player.filter(key: 1) -/// try print(request.databaseRegion(db)) -/// // prints "player(*)[1]" +/// let request = Player.filter(key: 1) +/// try print(request.databaseRegion(db)) +/// // prints "player(*)[1]" /// /// Database regions returned by requests can be more precise than regions /// returned by select statements. Especially, regions returned by statements From 97936c3fad53adc3aae381d22002c64c17b9f440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:46:57 +0100 Subject: [PATCH 107/118] Documentation --- README.md | 116 ++++++++++++++++++------------------------------------ 1 file changed, 39 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 03c5a6538..fa064eb49 100644 --- a/README.md +++ b/README.md @@ -5847,7 +5847,7 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: - [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. -- [ValueObservation and DatabaseRegionObservation](#valueobservation-and-databaseregionobservation): Automated tracking of database requests. +- [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests. - [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). @@ -5990,6 +5990,16 @@ try dbQueue.write { db in By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. +You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example: + +```swift +// Observe the full database +let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) +let observer = observation.start(in: dbQueue) { db: Database in + print("Database was changed") +} +``` + ### DatabaseRegionObservation Use Cases @@ -6233,19 +6243,11 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in ``` -#### The DatabaseRegionConvertible Protocol +#### DatabaseRegionConvertible Observation -The initial parameter of the `ValueObservation.tracking(_:fetch:)` and `ValueObservation.tracking(_:fetchDistinct:)` methods can be fed with requests, and generally speaking, values that adopt the **DatabaseRegionConvertible** protocol. +The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. -```swift -protocol DatabaseRegionConvertible { - func databaseRegion(_ db: Database) throws -> DatabaseRegion -} -``` - -[DatabaseRegion](#databaseregion) is a type that helps observing the database. - -Use this protocol when you want to encapsulate your complex requests in a dedicated type. In the sample code below, `TeamInfoRequest` is not only able to fetch a team and its players, but also to be observed. +Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. ```swift struct TeamInfo { @@ -6286,7 +6288,7 @@ let request = TeamInfoRequest(teamId: 1) // Simple fetch let teamInfo: TeamInfo? = try dbQueue.read(request.fetch) -// Observatin +// Observation let observer = ValueObservation .tracking(request, fetch: request.fetch) .start(in: dbQueue) { teamInfo: TeamInfo? in @@ -7169,74 +7171,32 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan **[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. -A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region. +A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. -You start by building regions: +DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservation]. -```swift -try dbQueue.write { db in - let teamRegion = try Team.filter(key: 1).databaseRegion(db) - let playersRegion = try SQLRequest("SELECT * FROM player").databaseRegion(db) - let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db) -``` - -You can group regions: - -```swift - let region = teamRegion.union(playersRegion).union(maxScoreRegion) -} -``` - -There are two special regions: `DatabaseRegion()` (the empty region), and `DatabaseRegion.fullDatabase` (the region that spans the whole database). - -Regions feed the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example: - -```swift -// A transaction observer which notifies all changes to a database region. -class DatabaseRegionObserver: TransactionObserver { - let region: DatabaseRegion - var regionIsModified = false - - init(region: DatabaseRegion) { - self.region = region - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - regionIsModified = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidRollback(_ db: Database) { - regionIsModified = false - } - - func databaseDidCommit(_ db: Database) { - if regionIsModified == false { return } - regionIsModified = false - - // You'll customize your handling of changes here: - print("Region has been modified.") - } -} - -// Observe a region -try dbQueue.write { db in - observer = DatabaseRegionObserver(region: region) - db.add(transactionObserver: observer) -} -``` - -A region notifies *potential* changes, not *actual* changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. +**A region notifies *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key *is* the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. +Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. + +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). + + +#### The DatabaseRegionConvertible Protocol + +**DatabaseRegionConvertible** is a protocol for all types that can turn into a [DatabaseRegion]: + +```swift +protocol DatabaseRegionConvertible { + func databaseRegion(_ db: Database) throws -> DatabaseRegion +} +``` + +All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. + +Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from observation APIs. See [DatabaseRegionConvertible Observation](#databaseregionconvertible-observation) for more information. ### Support for SQLite Pre-Update Hooks @@ -8637,4 +8597,6 @@ This chapter has been renamed [Beyond FetchableRecord]. [ValueObservation]: #valueobservation [DatabaseRegionObservation]: #databaseregionobservation [FetchedRecordsController]: #fetchedrecordscontroller -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol +[ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation From 21d243fc33374eee6ee933d9043046cb780a6655 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:51:45 +0100 Subject: [PATCH 108/118] Documentation --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fa064eb49..4228d1fde 100644 --- a/README.md +++ b/README.md @@ -4571,7 +4571,7 @@ The `prepare` method returns a prepared statement and an optional row adapter. T The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. -The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), [DatabaseRegionObservation], and [ValueObservation]. +The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion], [DatabaseRegionObservation], and [ValueObservation]. The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -6955,7 +6955,7 @@ protocol TransactionObserver : class { - [Database Changes And Transactions](#database-changes-and-transactions) - [Filtering Database Events](#filtering-database-events) - [Observation Extent](#observation-extent) -- [DatabaseRegion](#databaseregion) +- [DatabaseRegion] - [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) @@ -7103,7 +7103,7 @@ class PureTransactionObserver: TransactionObserver { } ``` -For more information about event filtering, see [DatabaseRegion](#databaseregion). +For more information about event filtering, see [DatabaseRegion]. ### Observation Extent @@ -8600,3 +8600,4 @@ This chapter has been renamed [Beyond FetchableRecord]. [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol [ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation +[DatabaseRegion]: #databaseregion \ No newline at end of file From 9fd802b3eae9593f304ea3f370689ec4175abe9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Dec 2018 18:54:09 +0100 Subject: [PATCH 109/118] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4228d1fde..76faafeaa 100644 --- a/README.md +++ b/README.md @@ -6052,7 +6052,7 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** - [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [ValueObservation Transformations](#valueobservation-transformations): ([map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ...) +- [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... - [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) - [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) From 815a3697dace57353e9bb3efefa0eeded2f30a9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 08:20:18 +0100 Subject: [PATCH 110/118] Documentation --- README.md | 198 +++++++++++++++++++++++++++--------------------------- 1 file changed, 100 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index 76faafeaa..de4815ac4 100644 --- a/README.md +++ b/README.md @@ -5916,33 +5916,33 @@ try dbQueue.write { db in ## ValueObservation and DatabaseRegionObservation -**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests): +**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests). ```swift -// Two observations that track the players: +// Let's observe all players! let request = Player.all() -let valueObservation = ValueObservation.trackingAll(request) -let regionObservation = DatabaseRegionObservation(tracking: request) ``` [ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift -let observer = valueObservation.start(in: dbQueue) { players: [Player] in - print("Player have changed: \(players)") +let observation = ValueObservation.trackingAll(request) +let observer = observation.start(in: dbQueue) { players: [Player]? in + let names = players.map { $0.name }.joined(separator: ", ") + print("Fresh players: \(names)") } try dbQueue.write { db in try Player(name: "Arthur").insert(db) } -// Prints "Players have changed: ..." - +// Prints "Fresh players: Arthur, ..." ``` -[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for advanced use cases :nerd_face:): +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for more advanced use cases :nerd_face:): ```swift -let observer = regionObservation.start(in: dbQueue) { db: Database in +let observation = DatabaseRegionObservation(tracking: request) +let observer = observation.start(in: dbQueue) { db: Database in print("Player have changed.") } @@ -5952,94 +5952,8 @@ try dbQueue.write { db in // Prints "Players have changed." ``` - -## DatabaseRegionObservation - -**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** - -No insertion, update, or deletion in the tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). - -DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation. - - -### DatabaseRegionObservation Usage - -Define an observation by providing one or several requests to track: - -```swift -// Track all players -let observation = DatabaseRegionObservation(tracking: Player.all()) -``` - -Then start the observation from a [database queue](#database-queues) or [pool](#database-pools): - -```swift -let observer = observation.start(in: dbQueue) { db: Database in - print("Players were changed") -} -``` - -And enjoy the changes notifications: - -```swift -try dbQueue.write { db in - try Player(name: "Arthur").insert(db) -} -// Prints "Players were changed" -``` - -By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. - -You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example: - -```swift -// Observe the full database -let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) -let observer = observation.start(in: dbQueue) { db: Database in - print("Database was changed") -} -``` - - -### DatabaseRegionObservation Use Cases - -**There are very few use cases for DatabaseRegionObservation**. - -For example: - -- One needs to write in the database after an impactful transaction. - -- One needs to synchronize the content of the database file with some external resources, like other files, or system sensors like CLRegion monitoring. - -- On iOS, one needs to process a database transaction before the operating system had any opportunity to put the application in the suspended state. - -- One want to build a [database snapshot](#database-snapshots) with a guaranteed snapshot content. - -Outside of those use cases, it is much likely *wrong* to use a DatabaseRegionObservation. Please check other [Database Observation](#database-changes-observation) options. - - -### DatabaseRegionObservation.extent - -The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: - -```swift -// This observation lasts until the database connection is closed -var observation = DatabaseRegionObservation... -observation.extent = .databaseLifetime -_ = observation.start(in: dbQueue) { db in ... } -``` - -The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated. - -Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: - -```swift -// Start -let observer = observation.start(in: dbQueue) { db in ... } - -// Stop -dbQueue.remove(transactionObserver: observer) -``` +- [ValueObservation] +- [DatabaseRegionObservation] ## ValueObservation @@ -6579,6 +6493,94 @@ try dbQueue.write { db in ``` +## DatabaseRegionObservation + +**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** + +No insertion, update, or deletion in the tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation. + + +### DatabaseRegionObservation Usage + +Define an observation by providing one or several requests to track: + +```swift +// Track all players +let observation = DatabaseRegionObservation(tracking: Player.all()) +``` + +Then start the observation from a [database queue](#database-queues) or [pool](#database-pools): + +```swift +let observer = observation.start(in: dbQueue) { db: Database in + print("Players were changed") +} +``` + +And enjoy the changes notifications: + +```swift +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} +// Prints "Players were changed" +``` + +By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. + +You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example: + +```swift +// Observe the full database +let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) +let observer = observation.start(in: dbQueue) { db: Database in + print("Database was changed") +} +``` + + +### DatabaseRegionObservation Use Cases + +**There are very few use cases for DatabaseRegionObservation**. + +For example: + +- One needs to write in the database after an impactful transaction. + +- One needs to synchronize the content of the database file with some external resources, like other files, or system sensors like CLRegion monitoring. + +- On iOS, one needs to process a database transaction before the operating system had any opportunity to put the application in the suspended state. + +- One want to build a [database snapshot](#database-snapshots) with a guaranteed snapshot content. + +Outside of those use cases, it is much likely *wrong* to use a DatabaseRegionObservation. Please check other [Database Observation](#database-changes-observation) options. + + +### DatabaseRegionObservation.extent + +The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: + +```swift +// This observation lasts until the database connection is closed +var observation = DatabaseRegionObservation... +observation.extent = .databaseLifetime +_ = observation.start(in: dbQueue) { db in ... } +``` + +The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated. + +Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: + +```swift +// Start +let observer = observation.start(in: dbQueue) { db in ... } + +// Stop +dbQueue.remove(transactionObserver: observer) +``` + ## FetchedRecordsController From 37983b8581b97bce3522a18fb74651fa85efcaf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 08:36:11 +0100 Subject: [PATCH 111/118] Documentation --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index de4815ac4..6ad5fcf8d 100644 --- a/README.md +++ b/README.md @@ -6103,7 +6103,7 @@ struct HallOfFame { } } -let hallOfFame = try dbQueue.read { try HallOfFame.fetch($0) } +let hallOfFame = try dbQueue.read { db in try HallOfFame.fetch(db) } print(""" Best players out of \(hallOfFame.totalPlayerCount): \(hallOfFame.bestPlayers) @@ -6118,11 +6118,9 @@ In order to track changes in the Hall of Fame, we'll use the `ValueObservation.t In our case, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: ```swift -let observation = ValueObservation.tracking( - Player.all(), - fetch: { db -> HallOfFame in - return HallOfFame.fetch(db) - }) +let observation = ValueObservation.tracking(Player.all(), fetch: { db in + try HallOfFame.fetch(db) +}) let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in print(""" From 5badd625150284a535a1af1214e4ba697fe445ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 08:41:17 +0100 Subject: [PATCH 112/118] Documentation --- README.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6ad5fcf8d..2b880b37e 100644 --- a/README.md +++ b/README.md @@ -6162,29 +6162,26 @@ The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. ```swift +/// A team and its players struct TeamInfo { var team: Team var players: [Player] } -struct TeamInfoRequest: DatabaseRegionConvertible { +/// A request that can fetch TeamInfo, given a team id. +struct TeamInfoRequest { var teamId: Int64 + /// The request for the team private var teamRequest: QueryInterfaceRequest { return Team.filter(key: teamId) } + /// The request for the players private var playersRequest: QueryInterfaceRequest { return Player.filter(Column("teamId") == teamId) } - /// DatabaseRegionConvertible adoption - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let teamRegion = try teamRequest.databaseRegion(db) - let playersRegion = try playersRequest.databaseRegion(db) - return teamRegion.union(playersRegion) - } - /// Fetch a TeamInfo func fetch(_ db: Database) throws -> TeamInfo? { guard let team = try teamRequest.fetchOne(db) else { @@ -6195,6 +6192,15 @@ struct TeamInfoRequest: DatabaseRegionConvertible { } } +extension TeamInfoRequest: DatabaseRegionConvertible { + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + // Returns the union of the team region and the players region + let teamRegion = try teamRequest.databaseRegion(db) + let playersRegion = try playersRequest.databaseRegion(db) + return teamRegion.union(playersRegion) + } +} + let request = TeamInfoRequest(teamId: 1) // Simple fetch From 37ac126d26efbd81ce9b0fc0cc869a4e6680aa8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 08:42:28 +0100 Subject: [PATCH 113/118] Documentation --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2b880b37e..b2a5069e5 100644 --- a/README.md +++ b/README.md @@ -6192,6 +6192,7 @@ struct TeamInfoRequest { } } +/// Make TeamInfoRequest observable extension TeamInfoRequest: DatabaseRegionConvertible { func databaseRegion(_ db: Database) throws -> DatabaseRegion { // Returns the union of the team region and the players region From ca4a867803ec50a47d1a946b99d6aa80696d91b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 08:43:59 +0100 Subject: [PATCH 114/118] Remove picture that breaks anchor linking --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index b2a5069e5..36eb1f333 100644 --- a/README.md +++ b/README.md @@ -359,9 +359,6 @@ The repository comes with a [demo application](DemoApps/GRDBDemoiOS/README.md) t - how to define a simple [Codable Record](#codable-records) - how to track database changes with [ValueObservation] and [FetchedRecordsController]. -

- -

Database Connections ==================== From 59a65bf81e728600e24e8fe3f8f2d8d3a64def2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 17:57:50 +0100 Subject: [PATCH 115/118] PULL_REQUEST_TEMPLATE --- .github/PULL_REQUEST_TEMPLATE.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 529ad6e18..1c05fd109 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,18 +1,13 @@ -### One more thing… +### Pull Request Checklist + - [ ] This pull request is submitted against the `development` branch. - [ ] Inline documentation has been updated. - [ ] README.md or another dedicated guide has been updated. - [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite. -- [ ] Updated CHANGELOG.md +- [ ] CHANGELOG.md has been updated. From 343816ed7bfacf9e72bb7fdb9a6f26a7ae292679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 18:04:16 +0100 Subject: [PATCH 116/118] Documentation --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 36eb1f333..531fd025a 100644 --- a/README.md +++ b/README.md @@ -2174,8 +2174,10 @@ It is possible to [avoid useless updates](#record-comparison): ```swift if let player = try Player.fetchOne(db, key: 1) { - player.score = 1000 - try player.updateChanges(db) // does nothing if score has not changed + // does nothing if score has not changed + try player.updateChanges(db) { + $0.score = 1000 + } } ``` @@ -2578,6 +2580,7 @@ try place.insert(db) // INSERT try place.update(db) // UPDATE try place.update(db, columns: ...) // UPDATE try place.updateChanges(db, from: ...) // Maybe UPDATE +try place.updateChanges(db) { ... } // Maybe UPDATE try place.updateChanges(db) // Maybe UPDATE (Record class only) try place.delete(db) // DELETE try place.exists(db) From f6f236512bfb17c39bfe91af891be5756c037999 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 18:08:53 +0100 Subject: [PATCH 117/118] Documentation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 531fd025a..2f7014917 100644 --- a/README.md +++ b/README.md @@ -2174,7 +2174,7 @@ It is possible to [avoid useless updates](#record-comparison): ```swift if let player = try Player.fetchOne(db, key: 1) { - // does nothing if score has not changed + // does not hit the database if score has not changed try player.updateChanges(db) { $0.score = 1000 } @@ -2960,7 +2960,7 @@ The `updateChanges` methods perform a database update of the changed columns onl if try newPlayer.updateChanges(db, from: oldPlayer) { print("player was modified, and updated in the database") } else { - print("player was not modified") + print("player was not modified, and database was not hit") } } ``` @@ -2977,7 +2977,7 @@ The `updateChanges` methods perform a database update of the changed columns onl if modified { print("player was modified, and updated in the database") } else { - print("player was not modified") + print("player was not modified, and database was not hit") } } ``` @@ -2993,7 +2993,7 @@ The `updateChanges` methods perform a database update of the changed columns onl if try player.updateChanges(db) { print("player was modified, and updated in the database") } else { - print("player was not modified") + print("player was not modified, and database was not hit") } } ``` From 11d3dd953808c662d820a2a3cdc6a5f02c9fc7d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 7 Dec 2018 18:22:01 +0100 Subject: [PATCH 118/118] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0795c51a..804d541c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,13 +52,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/). - [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex - [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update +- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation - [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations - [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap - [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer - [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged - [#455](https://github.com/groue/GRDB.swift/pull/455): DatabaseRegionObservation -- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue - ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. - ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired.