Base for comparing records according to their primary key, and avoid ad hoc adoption of Equatable

This commit is contained in:
Gwendal Roué committed 2016-03-06 14:56:02 +01:00
1 parent 0d5bed389f
commit 2cbfa16e53
1 file changed
+47
+47
View File
@@ -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<String, DatabaseValue>(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