From 2cbfa16e53342877f2a3895d3b9cf3fdbd105377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Mar 2016 14:56:02 +0100 Subject: [PATCH] Base for comparing records according to their primary key, and avoid ad hoc adoption of Equatable --- GRDB/Record/Persistable.swift | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 9c4864f55..407e68790 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -303,6 +303,53 @@ public extension MutablePersistable { } +extension MutablePersistable { + /// Returns a function that return the primary key of a record + /// + /// struct Person: MutablePersistable { ... } + /// dbQueue.inDatabase { db in + /// let primaryKey = Person.primaryKeyExtractor + /// let person = Person(id: 1, name: "Arthur") + /// primaryKey(person) // ["id": 1] + /// } + /// + /// - throws: A DatabaseError if table does not exist. + static func primaryKeyExtractor(db: Database) throws -> (Self) -> [String: DatabaseValue] { + db.preconditionValidQueue() + let columns = try db.primaryKey(databaseTableName()).columns + return { record in + let dictionary = record.persistentDictionary + return Dictionary(keys: columns) { databaseValue(forColumn: $0, inDictionary: dictionary) } + } + } + + /// Returns a function that return true if and only if two records have the + /// same primary key and both primary keys contain at least one non-null + /// value. + /// + /// struct Person: MutablePersistable { ... } + /// dbQueue.inDatabase { db in + /// let comparator = Person.primaryKeyComparator + /// let unsaved = Person(id: nil, name: "Unsaved") + /// let arthur1 = Person(id: 1, name: "Arthur") + /// let arthur2 = Person(id: 1, name: "Arthur") + /// let barbara = Person(id: 2, name: "Barbara") + /// comparator(unsaved, unsaved) // false + /// comparator(arthur1, arthur2) // true + /// comparator(arthur1, barbara) // false + /// } + /// + /// - throws: A DatabaseError if table does not exist. + static func primaryKeyComparator(db: Database) throws -> (Self, Self) -> Bool { + let primaryKey = try Self.primaryKeyExtractor(db) + return { (lhs, rhs) in + let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs)) + guard lhs.contains({ !$1.isNull }) else { return false } + guard rhs.contains({ !$1.isNull }) else { return false } + return lhs == rhs + } + } +} // MARK: - Persistable