diff --git a/CHANGELOG.md b/CHANGELOG.md index b3168af77..a74299f39 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 @@ -24,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 @@ -31,6 +31,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( diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 9c4197a91..47a33a7ff 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -521,28 +521,62 @@ 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 = try 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 { + return try updateChanges(db, from: PersistenceContainer(record)) + } + + /// 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 = 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 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 /// 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) - if changedColumns.isEmpty { - return false - } else { - try update(db, columns: changedColumns) - return true - } + public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { + let container = PersistenceContainer(self) + try change(&self) + return try updateChanges(db, from: container) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -574,7 +608,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,16 +620,15 @@ 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) + 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 { @@ -606,6 +639,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 @@ -929,6 +973,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 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 + /// 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 container = PersistenceContainer(self) + try change(self) + return try updateChanges(db, from: container) + } + // MARK: - Immutable CRUD Internals diff --git a/README.md b/README.md index ba7ab2927..3279733bc 100644 --- a/README.md +++ b/README.md @@ -2936,39 +2936,72 @@ 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-updatechanges-methods) +- [The `databaseEquals` Method](#the-databaseequals-method) +- [The `databaseChanges` and `hasDatabaseChanges` Methods](#the-databasechanges-and-hasdatabasechanges-methods) -```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") -} -``` -> :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 `updateChanges` Methods -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 `updateChanges` methods perform a database update of the changed columns only (and does nothing if record has no change). -```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") -} -``` +- `updateChanges(_:from:)` -You can also use the `databaseEquals` method, which returns whether two records have the same database representation: + 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 class only) + + 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 + 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: Player = ... @@ -2978,11 +3011,40 @@ if newPlayer.databaseEquals(oldPlayer) == false { } ``` -Again, [Record](#record-class) instances can compare against themselves, with the `hasDatabaseChanges` property: +> :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` and `hasDatabaseChanges` Methods + +`databaseChanges(from:)` returns a dictionary of 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 -player.score = 100 +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" +``` + +[Record](#record-class) instances also have a `hasDatabaseChanges` property: + +```swift +// Record class only +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) | | diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f8b01ebce..a3f7db736 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -269,4 +269,238 @@ 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) + } + + // This `let` is part of the test + let 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) + } + + // This `let` is part of the test + let 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)) + } + } + } } 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"]) }