added ObjectSnapshot as foundation for datasources API

This commit is contained in:
John Estropia
2019-07-10 08:11:42 +09:00
parent cf46b45e8e
commit 79655ffde5
50 changed files with 434 additions and 81 deletions

View File

@@ -44,4 +44,5 @@ internal protocol AttributeProtocol: AnyObject {
var rawObject: CoreStoreManagedObject? { get set }
var getter: CoreStoreManagedObject.CustomGetter? { get }
var setter: CoreStoreManagedObject.CustomSetter? { get }
var valueForSnapshot: Any { get }
}

View File

@@ -80,7 +80,7 @@ extension BaseDataTransaction {
try autoreleasepool {
let entityType = cs_dynamicType(of: object)
let entityType = object.runtimeType()
guard entityType.shouldInsert(from: source, in: self) else {
return

View File

@@ -72,7 +72,7 @@ public final class CSAsynchronousDataTransaction: CSBaseDataTransaction, CoreSto
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -191,7 +191,7 @@ public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -64,7 +64,7 @@ public final class CSError: NSError, CoreStoreObjectiveCType {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}
@@ -274,7 +274,7 @@ extension Error {
case let error as CSError:
return error.bridgeToSwift
case let error as NSError where type(of: self) is NSError.Type:
case let error as NSError where Self.self is NSError.Type:
return .internalError(NSError: error)
default:

View File

@@ -137,7 +137,7 @@ public final class CSFrom: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -87,7 +87,7 @@ public final class CSGroupBy: NSObject, CSQueryClause {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -103,7 +103,7 @@ public final class CSInMemoryStore: NSObject, CSStorageInterface, CoreStoreObjec
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -104,7 +104,7 @@ public final class CSInto: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -526,7 +526,7 @@ public final class CSListMonitor: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -155,7 +155,7 @@ public final class CSMigrationResult: NSObject, CoreStoreObjectiveCType {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -101,7 +101,7 @@ public final class CSMigrationType: NSObject, CoreStoreObjectiveCType {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -119,7 +119,7 @@ public final class CSObjectMonitor: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -95,7 +95,7 @@ public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteCl
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -178,7 +178,7 @@ public final class CSSQLiteStore: NSObject, CSLocalStorage, CoreStoreObjectiveCT
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -68,7 +68,7 @@ public final class CSSectionBy: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -377,7 +377,7 @@ public final class CSSelect: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -146,7 +146,7 @@ public final class CSSetupResult: NSObject {
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -60,7 +60,7 @@ public final class CSSynchronousDataTransaction: CSBaseDataTransaction, CoreStor
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -63,7 +63,7 @@ public final class CSTweak: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -71,7 +71,7 @@ public final class CSUnsafeDataModelSchema: NSObject, CSDynamicSchema, CoreStore
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -181,7 +181,7 @@ public final class CSUnsafeDataTransaction: CSBaseDataTransaction, CoreStoreObje
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -134,7 +134,7 @@ public final class CSWhere: NSObject, CSFetchClause, CSQueryClause, CSDeleteClau
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -71,7 +71,7 @@ public final class CSXcodeDataModelSchema: NSObject, CSDynamicSchema, CoreStoreO
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
return "(\(String(reflecting: Self.self))) \(self.bridgeToSwift.coreStoreDumpString)"
}

View File

@@ -116,7 +116,7 @@ extension CoreStoreError: CustomDebugStringConvertible, CoreStoreDebugStringConv
let firstLine: String
var info: DumpInfo = [
("errorDomain", type(of: self).errorDomain),
("errorDomain", Self.errorDomain),
("errorCode", self.errorCode),
]
switch self {

View File

@@ -69,7 +69,10 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable {
self.isMeta = false
self.rawObject = (rawObject as! CoreStoreManagedObject)
self.initializeAttributes(Mirror(reflecting: self), self)
self.registerReceiver(
mirror: Mirror(reflecting: self),
object: self
)
}
/**
@@ -93,7 +96,7 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable {
}
if lhs.isMeta {
return cs_dynamicType(of: lhs) == cs_dynamicType(of: rhs)
return lhs.runtimeType() == rhs.runtimeType()
}
return lhs.rawObject!.isEqual(rhs.rawObject!)
}
@@ -117,18 +120,24 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable {
// MARK: Private
private func initializeAttributes(_ mirror: Mirror, _ parentObject: CoreStoreObject) {
private func registerReceiver(mirror: Mirror, object: CoreStoreObject) {
_ = mirror.superclassMirror.flatMap({ self.initializeAttributes($0, parentObject) })
if let superclassMirror = mirror.superclassMirror {
self.registerReceiver(
mirror: superclassMirror,
object: object
)
}
for child in mirror.children {
switch child.value {
case let property as AttributeProtocol:
property.rawObject = parentObject.rawObject
property.rawObject = object.rawObject
case let property as RelationshipProtocol:
property.rawObject = parentObject.rawObject
property.rawObject = object.rawObject
default:
continue
@@ -158,14 +167,14 @@ extension DynamicObject where Self: CoreStoreObject {
// MARK: Internal
internal static var meta: Self {
let key = ObjectIdentifier(self)
if case let meta as Self = Static.metaCache[key] {
let cacheKey = ObjectIdentifier(self)
if case let meta as Self = Static.metaCache[cacheKey] {
return meta
}
let meta = self.init(asMeta: ())
Static.metaCache[key] = meta
Static.metaCache[cacheKey] = meta
return meta
}
}
@@ -174,6 +183,8 @@ extension DynamicObject where Self: CoreStoreObject {
// MARK: - Static
fileprivate enum Static {
// MARK: FilePrivate
fileprivate static var metaCache: [ObjectIdentifier: Any] = [:]
}

View File

@@ -328,7 +328,6 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider {
return lhs.sourceVersion == rhs.sourceVersion
&& lhs.destinationVersion == rhs.destinationVersion
&& cs_dynamicType(of: lhs) == cs_dynamicType(of: rhs)
}
@@ -338,7 +337,7 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider {
hasher.combine(self.sourceVersion)
hasher.combine(self.destinationVersion)
hasher.combine(ObjectIdentifier(cs_dynamicType(of: self)))
hasher.combine(ObjectIdentifier(Self.self))
}

View File

@@ -60,6 +60,17 @@ public protocol DynamicObject: AnyObject {
func cs_toRaw() -> NSManagedObject
}
extension DynamicObject {
// MARK: Internal
internal func runtimeType() -> Self.Type {
// Self.self does not return runtime-created types
return object_getClass(self)! as! Self.Type
}
}
// MARK: - NSManagedObject
@@ -98,6 +109,16 @@ extension NSManagedObject: DynamicObject {
}
}
extension DynamicObject where Self: NSManagedObject {
// MARK: Public
public func createSnapshot() -> ObjectSnapshot<Self> {
return ObjectSnapshot(from: self)
}
}
// MARK: - CoreStoreObject
@@ -150,3 +171,13 @@ extension CoreStoreObject {
return self.rawObject!
}
}
extension DynamicObject where Self: CoreStoreObject {
// MARK: Public
public func createSnapshot() -> ObjectSnapshot<Self> {
return ObjectSnapshot(from: self)
}
}

View File

@@ -27,15 +27,6 @@ import Foundation
// MARK: Associated Objects
@inline(__always)
/// type(of:) doesn't return the dynamic type anymore, use this to guarantee correct dispatch of class methods
internal func cs_dynamicType<T: AnyObject>(of instance: T) -> T.Type {
return object_getClass(instance) as! T.Type
}
// MARK: Associated Objects
@inline(__always)
internal func cs_getAssociatedObjectForKey<T: AnyObject>(_ key: UnsafeRawPointer, inObject object: Any) -> T? {

View File

@@ -125,7 +125,7 @@ extension ImportableUniqueObject where UniqueIDType.QueryableNativeType: CoreDat
get {
return self.cs_toRaw().getValue(
forKvcKey: cs_dynamicType(of: self).uniqueIDKeyPath,
forKvcKey: Self.uniqueIDKeyPath,
didGetValue: { UniqueIDType.cs_fromQueryableNativeType($0 as! UniqueIDType.QueryableNativeType)! }
)
}
@@ -134,7 +134,7 @@ extension ImportableUniqueObject where UniqueIDType.QueryableNativeType: CoreDat
self.cs_toRaw()
.setValue(
newValue,
forKvcKey: cs_dynamicType(of: self).uniqueIDKeyPath,
forKvcKey: Self.uniqueIDKeyPath,
willSetValue: { ($0.cs_toQueryableNativeType() as CoreDataNativeType) }
)
}

View File

@@ -47,7 +47,7 @@ public final class InferredSchemaMappingProvider: Hashable, SchemaMappingProvide
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(type(of: self)))
hasher.combine(ObjectIdentifier(Self.self))
}

View File

@@ -62,7 +62,7 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource {
return object
}
return cs_dynamicType(of: object).cs_fromRaw(object: existingRawObject)
return object.runtimeType().cs_fromRaw(object: existingRawObject)
}
catch {

View File

@@ -0,0 +1,143 @@
//
// ObjectSnapshot.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - ObjectSnapshot
/**
An `ObjectSnapshot` contains "snapshot" values from a `DynamicObject` instance copied at a specific point in time.
*/
@dynamicMemberLookup
public struct ObjectSnapshot<O: DynamicObject> {
// MARK: FilePrivate
fileprivate var attributes: [KeyPathString: Any]
// MARK: Private
private init() {
self.attributes = [:]
}
}
// MARK: - ObjectSnapshot where O: NSManagedObject
extension ObjectSnapshot where O: NSManagedObject {
/**
Initializes an `ObjectSnapshot` instance by copying all attribute values from the given `NSManagedObject`.
*/
public init(from object: O) {
self.attributes = object.dictionaryWithValues(
forKeys: Array(object.entity.attributesByName.keys)
)
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: AllowedObjectiveCKeyPathValue>(dynamicMember member: KeyPath<O, V>) -> V {
get {
let key = String(keyPath: member)
return self.attributes[key]! as! V
}
set {
let key = String(keyPath: member)
self.attributes[key] = newValue
}
}
}
// MARK: - ObjectSnapshot where O: CoreStoreObject
extension ObjectSnapshot where O: CoreStoreObject {
/**
Initializes an `ObjectSnapshot` instance by copying all attribute values from the given `CoreStoreObject`.
*/
public init(from object: O) {
var attributes: [KeyPathString: Any] = [:]
Self.initializeAttributes(
mirror: Mirror(reflecting: object),
object: object,
into: &attributes
)
self.attributes = attributes
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<K: AttributeKeyPathStringConvertible>(dynamicMember member: KeyPath<O, K>) -> K.ReturnValueType {
get {
let key = String(keyPath: member)
return self.attributes[key]! as! K.ReturnValueType
}
set {
let key = String(keyPath: member)
self.attributes[key] = newValue
}
}
// MARK: Private
private static func initializeAttributes(mirror: Mirror, object: CoreStoreObject, into attributes: inout [KeyPathString: Any]) {
if let superClassMirror = mirror.superclassMirror {
self.initializeAttributes(
mirror: superClassMirror,
object: object,
into: &attributes
)
}
for child in mirror.children {
switch child.value {
case let property as AttributeProtocol:
attributes[property.keyPath] = property.valueForSnapshot
default:
continue
}
}
}
}

View File

@@ -223,7 +223,7 @@ public final class SQLiteStore: LocalStorage {
var storeOptions = self.storeOptions ?? [:]
storeOptions[NSSQLitePragmasOption] = ["journal_mode": "DELETE"]
try coordinator.addPersistentStore(
ofType: type(of: self).storeType,
ofType: Self.storeType,
configurationName: self.configuration,
at: fileURL,
options: storeOptions
@@ -289,7 +289,7 @@ public final class SQLiteStore: LocalStorage {
var storeOptions = self.storeOptions ?? [:]
storeOptions[NSSQLitePragmasOption] = ["journal_mode": "DELETE"]
let store = try journalUpdatingCoordinator.addPersistentStore(
ofType: type(of: self).storeType,
ofType: Self.storeType,
configurationName: self.configuration,
at: fileURL,
options: storeOptions

View File

@@ -156,7 +156,7 @@ extension LocalStorage {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
return persistentStore.type == type(of: self).storeType
return persistentStore.type == Self.storeType
&& persistentStore.configurationName == (self.configuration ?? DataStack.defaultConfigurationName)
&& persistentStore.url == self.fileURL
}
@@ -243,7 +243,7 @@ extension CloudStorage {
internal func matchesPersistentStore(_ persistentStore: NSPersistentStore) -> Bool {
guard persistentStore.type == type(of: self).storeType
guard persistentStore.type == Self.storeType
&& persistentStore.configurationName == (self.configuration ?? DataStack.defaultConfigurationName) else {
return false

View File

@@ -267,6 +267,10 @@ public enum TransformableContainer<O: CoreStoreObject> {
)
}
}
internal var valueForSnapshot: Any {
return self.value
}
// MARK: Private
@@ -480,6 +484,10 @@ public enum TransformableContainer<O: CoreStoreObject> {
)
}
}
internal var valueForSnapshot: Any {
return self.value as Any
}
// MARK: Private

View File

@@ -263,6 +263,10 @@ public enum ValueContainer<O: CoreStoreObject> {
}
}
internal var valueForSnapshot: Any {
return self.value
}
// MARK: Private
@@ -476,6 +480,10 @@ public enum ValueContainer<O: CoreStoreObject> {
}
}
internal var valueForSnapshot: Any {
return self.value as Any
}
// MARK: Private