From 4887eaabb89a1cb29df1109d1ce6668bde0d1dcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Jul 2015 07:42:47 +0200 Subject: [PATCH] RowModel.isDirty experimentation --- GRDB Tests/GRDBTestCase.swift | 16 +- GRDB Tests/RowModel/RowModelDirtyTests.swift | 152 +++++++++++++++++++ GRDB.xcodeproj/project.pbxproj | 6 + GRDB/DatabaseValue.swift | 20 ++- GRDB/Row.swift | 2 +- GRDB/RowModel.swift | 121 ++++++++++++--- 6 files changed, 290 insertions(+), 27 deletions(-) create mode 100644 GRDB Tests/RowModel/RowModelDirtyTests.swift diff --git a/GRDB Tests/GRDBTestCase.swift b/GRDB Tests/GRDBTestCase.swift index d17abd4c7..5ae5c57a0 100644 --- a/GRDB Tests/GRDBTestCase.swift +++ b/GRDB Tests/GRDBTestCase.swift @@ -61,20 +61,28 @@ struct DBDate: DatabaseValueConvertible { class GRDBTestCase: XCTestCase { var databasePath: String! var dbQueue: DatabaseQueue! + var sqlQueries: [String]! override func setUp() { super.setUp() - self.databasePath = "/tmp/GRDB.sqlite" + sqlQueries = [] + databasePath = "/tmp/GRDB.sqlite" do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { } - let configuration = Configuration(trace: Configuration.logSQL) - self.dbQueue = try! DatabaseQueue(path: databasePath, configuration: configuration) + let configuration = Configuration(trace: { (sql, bindings) in + self.sqlQueries.append(sql) + NSLog("GRDB: %@", sql) + if let bindings = bindings { + NSLog("GRDB: bindings %@", bindings.description) + } + }) + dbQueue = try! DatabaseQueue(path: databasePath, configuration: configuration) } override func tearDown() { super.tearDown() - self.dbQueue = nil + dbQueue = nil try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } diff --git a/GRDB Tests/RowModel/RowModelDirtyTests.swift b/GRDB Tests/RowModel/RowModelDirtyTests.swift new file mode 100644 index 000000000..888cb546c --- /dev/null +++ b/GRDB Tests/RowModel/RowModelDirtyTests.swift @@ -0,0 +1,152 @@ +// +// GRDB.swift +// https://github.com/groue/GRDB.swift +// Copyright (c) 2015 Gwendal Roué +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +import XCTest +import GRDB + +class RowModelDirtyTests: RowModelTestCase { + + func testRowModelIsDirtyAfterInit() { + // Create a RowModel. No fetch has happen, so we don't know if it is + // identical to its eventual row in the database. So it is dirty. + let person = Person(name: "Arthur", age: 41) + XCTAssertTrue(person.isDirty) + } + + func testRowModelIsNotDirtyAfterFullFetch() { + // Fetch a model from a row that contains all the columns in + // storedDatabaseDictionary: An update statement, which only saves the + // columns in storedDatabaseDictionary would perform no change. So the + // model is not dirty. + assertNoError { + try dbQueue.inDatabase { db in + try Person(name: "Arthur", age: 41).insert(db) + let person = db.fetchOne(Person.self, "SELECT * FROM persons")! + XCTAssertFalse(person.isDirty) + } + } + } + + func testRowModelIsDirtyAfterPartialFetch() { + // Fetch a model from a row that does not contain all the columns in + // storedDatabaseDictionary: An update statement, which only saves the + // columns in storedDatabaseDictionary may perform unpredictable change. + // So the model is dirty. + assertNoError { + try dbQueue.inDatabase { db in + try Person(name: "Arthur", age: 41).insert(db) + let person = db.fetchOne(Person.self, "SELECT name FROM persons")! + XCTAssertTrue(person.isDirty) + } + } + } + + func testRowModelIsNotDirtyAfterInsert() { + // After insertion, a model is not dirty since an update would update + // nothing. + assertNoError { + try dbQueue.inDatabase { db in + let person = Person(name: "Arthur", age: 41) + try person.insert(db) + XCTAssertFalse(person.isDirty) + } + } + } + + func testRowModelIsDirtyAfterValueChange() { + // Any change in a value exposed in storedDatabaseDictionary yields a + // dirty row model. + assertNoError { + try dbQueue.inDatabase { db in + let person = Person(name: "Arthur", age: 41) + try person.insert(db) + + person.name = "Bobby" // non-nil vs. non-nil + XCTAssertTrue(person.isDirty) + try person.reload(db) + + person.name = nil // non-nil vs. nil + XCTAssertTrue(person.isDirty) + try person.reload(db) + + person.creationDate = NSDate() // nil vs. non-nil + XCTAssertTrue(person.isDirty) + try person.reload(db) + } + } + } + + func testRowModelIsNotDirtyAfterUpdate() { + // After update, a model is not dirty since another update would update + // nothing. + assertNoError { + try dbQueue.inDatabase { db in + let person = Person(name: "Arthur", age: 41) + try person.insert(db) + person.name = "Bobby" + try person.update(db) + XCTAssertFalse(person.isDirty) + } + } + } + + func testNotDirtyModelPreventsSQLUpdateFromBothUpdateAndSaveMethods() { + // Updating a non-dirty model is a no-op + + assertNoError { + try dbQueue.inDatabase { db in + let person = Person(name: "Arthur", age: 41) + try person.insert(db) + try person.update(db) + try person.save(db) + try person.delete(db) + + let insertQueries = self.sqlQueries.filter { sql in sql.rangeOfString("INSERT INTO .*persons", options: [.CaseInsensitiveSearch, .RegularExpressionSearch]) != nil } + XCTAssertEqual(insertQueries.count, 1) + + let updateQueries = self.sqlQueries.filter { sql in sql.rangeOfString("UPDATE .*persons", options: [.CaseInsensitiveSearch, .RegularExpressionSearch]) != nil } + XCTAssertEqual(updateQueries.count, 0) + + // This is the only use of self.sqlQueries. So let's test it as well by making sure the DELETE has been recorded. + let deleteQueries = self.sqlQueries.filter { sql in sql.rangeOfString("DELETE FROM .*persons", options: [.CaseInsensitiveSearch, .RegularExpressionSearch]) != nil } + XCTAssertEqual(deleteQueries.count, 1) + } + } + } + + func testRowModelIsDirtyAfterReload() { + assertNoError { + try dbQueue.inDatabase { db in + let person = Person(name: "Arthur", age: 41) + try person.insert(db) + + person.name = "Bobby" + XCTAssertTrue(person.isDirty) + + try person.reload(db) + XCTAssertFalse(person.isDirty) + } + } + } +} diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 3259f04be..0707a1dd1 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 56105B121B4F18CC002CD224 /* RowModelDirtyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56105B111B4F18CC002CD224 /* RowModelDirtyTests.swift */; }; + 56105B131B4F18CC002CD224 /* RowModelDirtyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56105B111B4F18CC002CD224 /* RowModelDirtyTests.swift */; }; 564E0B141B4D8FC100EBC9F6 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E0B131B4D8FC100EBC9F6 /* DatabaseError.swift */; }; 564E0B161B4D901300EBC9F6 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E0B151B4D901300EBC9F6 /* DatabaseValue.swift */; }; 565E191E1B42B2B600D32814 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565E191D1B42B2B600D32814 /* Database.swift */; }; @@ -102,6 +104,7 @@ /* Begin PBXFileReference section */ 560DB28F1B4AD49300B14958 /* RowModelInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowModelInitializersTests.swift; sourceTree = ""; }; + 56105B111B4F18CC002CD224 /* RowModelDirtyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowModelDirtyTests.swift; sourceTree = ""; }; 5610C2081B483AA500F8B4EC /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = ""; }; 5610C20D1B4852D600F8B4EC /* RowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowTests.swift; sourceTree = ""; }; 5623E0891B494A8A00B20B7F /* RawRepresentableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentableTests.swift; sourceTree = ""; }; @@ -237,6 +240,7 @@ 56C9E6561B468EB200DDC541 /* PrimaryKeyRowIDTests.swift */, 56C9E6551B468EB200DDC541 /* PrimaryKeySingleTests.swift */, 5623E08B1B49970E00B20B7F /* RowModelDescriptionTests.swift */, + 56105B111B4F18CC002CD224 /* RowModelDirtyTests.swift */, 56CC3CA41B48289200A9A534 /* RowModelFetchTests.swift */, 560DB28F1B4AD49300B14958 /* RowModelInitializersTests.swift */, 56C9E6571B468EB200DDC541 /* RowModelSubClassTests.swift */, @@ -560,6 +564,7 @@ 56E5D81E1B4D435D00430942 /* PrimaryKeyNoneTests.swift in Sources */, 56E5D8261B4D435D00430942 /* CustomSQLiteValueConvertibleTests.swift in Sources */, 56E5D8231B4D435D00430942 /* RowModelInitializersTests.swift in Sources */, + 56105B131B4F18CC002CD224 /* RowModelDirtyTests.swift in Sources */, 56E5D8211B4D435D00430942 /* RowModelDescriptionTests.swift in Sources */, 56E5D8251B4D435D00430942 /* RowModelTestCase.swift in Sources */, 56E5D8201B4D435D00430942 /* PrimaryKeySingleTests.swift in Sources */, @@ -587,6 +592,7 @@ 56E5D8101B4D424400430942 /* RowModelSubClassTests.swift in Sources */, 56E5D8061B4D424400430942 /* InMemoryDatabaseTests.swift in Sources */, 56E5D80F1B4D424400430942 /* RowModelInitializersTests.swift in Sources */, + 56105B121B4F18CC002CD224 /* RowModelDirtyTests.swift in Sources */, 56E5D80C1B4D424400430942 /* PrimaryKeySingleTests.swift in Sources */, 56E5D8151B4D424400430942 /* SQLiteErrorTests.swift in Sources */, 56E5D8161B4D424400430942 /* UpdateStatementTests.swift in Sources */, diff --git a/GRDB/DatabaseValue.swift b/GRDB/DatabaseValue.swift index 07edab518..89db97908 100644 --- a/GRDB/DatabaseValue.swift +++ b/GRDB/DatabaseValue.swift @@ -28,7 +28,7 @@ DatabaseValue is the intermediate type between SQLite and your values. It has five cases that match the SQLite "storage classes": https://www.sqlite.org/datatype3.html */ -public enum DatabaseValue { +public enum DatabaseValue : Equatable { /// The NULL storage class. case Null @@ -98,3 +98,21 @@ public enum DatabaseValue { return Value(databaseValue: self) } } + +/// Equatable implementation for DatabaseValue +public func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { + switch (lhs, rhs) { + case (.Null, .Null): + return true + case (.Integer(let lhs), .Integer(let rhs)): + return lhs == rhs + case (.Real(let lhs), .Real(let rhs)): + return lhs == rhs + case (.Text(let lhs), .Text(let rhs)): + return lhs == rhs + case (.Blob(let lhs), .Blob(let rhs)): + return lhs.data.isEqualToData(rhs.data) + default: + return false + } +} diff --git a/GRDB/Row.swift b/GRDB/Row.swift index 164ca1e3c..41ce20c88 100644 --- a/GRDB/Row.swift +++ b/GRDB/Row.swift @@ -392,7 +392,7 @@ public struct RowIndex: ForwardIndexType, BidirectionalIndexType, RandomAccessIn public func advancedBy(n: Int) -> RowIndex { return RowIndex(index + n) } } -// Equatable implementation for RowIndex +/// Equatable implementation for RowIndex public func ==(lhs: RowIndex, rhs: RowIndex) -> Bool { return lhs.index == rhs.index } diff --git a/GRDB/RowModel.swift b/GRDB/RowModel.swift index c9c9c9c4a..575a8d1aa 100644 --- a/GRDB/RowModel.swift +++ b/GRDB/RowModel.swift @@ -91,12 +91,55 @@ public class RowModel { // the simple init() from init(row: Row), and perform distinct // initialization for fetched models. - updateWithRow(row) + for (column, databaseValue) in row { + setDatabaseValue(databaseValue, forColumn: column) + } + + // Not dirty + cleanVersion = Version(self, knownColumns: row.map { $0.0 }) } // MARK: - CRUD + /// Return true if the stored database dictionary has been modified since + /// last synchronization with the database. + public var isDirty: Bool { + guard let cleanVersion = cleanVersion else { + return true + } + + let cleanDictionary = cleanVersion.storedDatabaseDictionary + let currentDictionary = storedDatabaseDictionary + + guard cleanDictionary.count == currentDictionary.count else { + return true + } + + for (key, cleanValue) in cleanDictionary { + guard let currentValue = currentDictionary[key] else { + return true + } + + // Compare databaseValues, not values. + // This avoid forcing Equatable on to DatabaseValueConvertible. + // And nobody wants to force a protocol with Self requirement because + // everything may break. + switch (cleanValue?.databaseValue, currentValue?.databaseValue) { + case (.None, .None): + break; + case (.Some(let cleanDatabaseValue), .Some(let currentDatabaseValue)): + if cleanDatabaseValue != currentDatabaseValue { + return true + } + default: + return true + } + } + + return false + } + /// An enum that specifies an alternative constraint conflict resolution /// algorithm to use during INSERT and UPDATE commands. /// See https://www.sqlite.org/lang_insert.html & https://www.sqlite.org/lang_update.html @@ -108,27 +151,33 @@ public class RowModel { case Ignore } - /// Updates the RowModel from a Row. - /// Calls setDatabaseValue(_:forColumn:) for each (column, databaseValue) in the row - public final func updateWithRow(row: Row) { - for (column, databaseValue) in row { - setDatabaseValue(databaseValue, forColumn: column) - } - } - /// Inserts public func insert(db: Database, conflictResolution: ConflictResolution? = nil) throws { - let insertionResult = try Version(self).insert(db, conflictResolution: conflictResolution) + let version = Version(self) + let insertionResult = try version.insert(db, conflictResolution: conflictResolution) + + // Update RowID column if needed if let (rowIDColumn, insertedRowID) = insertionResult { setDatabaseValue(DatabaseValue.Integer(insertedRowID), forColumn: rowIDColumn) } + + // Not dirty any longer + cleanVersion = Version(self) } /// Throws an error if the model has no table name, or no primary key. /// Returns true if the model still exists in the database and has been updated. /// See https://www.sqlite.org/lang_update.html public func update(db: Database, conflictResolution: ConflictResolution? = nil) throws { - return try Version(self).update(db, conflictResolution: conflictResolution) + guard isDirty else { + return + } + + let version = Version(self) + try version.update(db, conflictResolution: conflictResolution) + + // Not dirty any longer + cleanVersion = version } /// Updates if model has a primary key with at least one non-nil value, @@ -137,6 +186,10 @@ public class RowModel { /// Returns true if the model has been inserted, or if it still exists in /// the database and has been updated. final public func save(db: Database, conflictResolution: ConflictResolution? = nil) throws { + guard isDirty else { + return + } + let insertionResult = try Version(self).save(db, conflictResolution: conflictResolution) if let (rowIDColumn, insertedRowID) = insertionResult { setDatabaseValue(DatabaseValue.Integer(insertedRowID), forColumn: rowIDColumn) @@ -146,18 +199,29 @@ public class RowModel { /// Throws an error if the model has no table name, or no primary key public func delete(db: Database) throws { try Version(self).delete(db) + + // Future calls to update and save MUST throw RowModelNotFound. + // A way to achieve this is to set rowModel dirty. + cleanVersion = nil } /// Throws an error if the model has no table name, or no primary key. /// Returns true if the model still exists in the database and has been reloaded. public func reload(db: Database) throws { if let row = try Version(self).fetchOneRow(db) { - updateWithRow(row) + for (column, databaseValue) in row { + setDatabaseValue(databaseValue, forColumn: column) + } + + // Not dirty any longer + cleanVersion = Version(self) } else { throw RowModelError.RowModelNotFound(self) } } + private var cleanVersion: Version? + // MARK: - Version @@ -165,8 +229,9 @@ public class RowModel { /// Version will NEVER change the rowModel. let rowModel: RowModel + let storedDatabaseDictionary: [String: DatabaseValueConvertible?] + lazy var databaseTable: Table? = self.rowModel.dynamicType.databaseTable - lazy var storedDatabaseDictionary: [String: DatabaseValueConvertible?] = self.rowModel.storedDatabaseDictionary // A primary key dictionary. Its values may be nil. lazy var weakPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = { @@ -213,8 +278,17 @@ public class RowModel { return nil }() - init(_ rowModel: RowModel) { + // Only keep knownColumns + init(_ rowModel: RowModel, knownColumns: [String]? = nil) { self.rowModel = rowModel + var dictionary = rowModel.storedDatabaseDictionary + if let knownColumns = knownColumns { + let unknownKeys = dictionary.keys.filter { knownColumns.indexOf($0) == nil } + for column in unknownKeys { + dictionary.removeValueForKey(column) + } + } + storedDatabaseDictionary = dictionary } /// Returns an optional (rowIDColumn, insertedRowID) if and only if the @@ -261,14 +335,18 @@ public class RowModel { } switch primaryKey { case .RowID(let column): - if let optionalValue = storedDatabaseDictionary[column] { - if optionalValue == nil { // ID was not set - return (column, changes.insertedRowID!) - } else { - return nil - } + guard let currentID = storedDatabaseDictionary[column] else { + fatalError("\(rowModel.dynamicType).storedDatabaseDictionary must return the value for the primary key `(column)`") + } + if let _ = currentID { + // RowID is already set. + return nil } else { - fatalError("storedDatabaseDictionary must return the value for the primary key `(column)`") + // RowID is not set yet. + let insertedRowID = changes.insertedRowID! + + // Tell RowModel + return (column, insertedRowID) } default: return nil @@ -390,6 +468,7 @@ public class RowModel { // MARK: - CustomStringConvertible extension RowModel : CustomStringConvertible { + /// A textual representation of `self`. public var description: String { return "<\(reflect(self.dynamicType).summary)" + "".join(storedDatabaseDictionary.map { (key, value) in if let string = value as? String {