mirror of
https://github.com/JohnEstropia/CoreStore.git
synced 2026-01-17 06:27:02 +01:00
relationships done!
This commit is contained in:
@@ -33,9 +33,17 @@ infix operator .= : AssignmentPrecedence
|
||||
postfix operator *
|
||||
|
||||
|
||||
// MARK: - ManagedObjectProtocol
|
||||
|
||||
public extension ManagedObjectProtocol where Self: ManagedObject {
|
||||
|
||||
public typealias Attribute = AttributeContainer<Self>
|
||||
}
|
||||
|
||||
|
||||
// MARK: - AttributeContainer
|
||||
|
||||
public enum AttributeContainer<O: ManagedObjectProtocol> {
|
||||
public enum AttributeContainer<O: ManagedObject> {
|
||||
|
||||
// MARK: - Required
|
||||
|
||||
@@ -51,12 +59,11 @@ public enum AttributeContainer<O: ManagedObjectProtocol> {
|
||||
return attribute.value
|
||||
}
|
||||
|
||||
public let keyPath: String
|
||||
|
||||
public init(_ keyPath: String, `default`: V = V.cs_emptyValue()) {
|
||||
public init(_ keyPath: String, `default`: V = V.cs_emptyValue(), isIndexed: Bool = false) {
|
||||
|
||||
self.keyPath = keyPath
|
||||
self.defaultValue = `default`.cs_toImportableNativeType()
|
||||
self.isIndexed = isIndexed
|
||||
}
|
||||
|
||||
public var value: V {
|
||||
@@ -76,19 +83,23 @@ public enum AttributeContainer<O: ManagedObjectProtocol> {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Internal
|
||||
|
||||
// MARK: AttributeProtocol
|
||||
|
||||
internal static var attributeType: NSAttributeType {
|
||||
|
||||
return V.cs_rawAttributeType
|
||||
}
|
||||
|
||||
internal let defaultValue: Any?
|
||||
public let keyPath: String
|
||||
|
||||
internal let isOptional = false
|
||||
internal let isIndexed: Bool
|
||||
internal let defaultValue: Any?
|
||||
|
||||
internal var accessRawObject: () -> NSManagedObject = {
|
||||
|
||||
fatalError("\(O.self) property values should not be accessed")
|
||||
fatalError("\(O.self) attribute values should not be accessed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +118,6 @@ public enum AttributeContainer<O: ManagedObjectProtocol> {
|
||||
return attribute.value
|
||||
}
|
||||
|
||||
public let keyPath: String
|
||||
|
||||
public init(_ keyPath: String, `default`: V? = nil) {
|
||||
|
||||
self.keyPath = keyPath
|
||||
@@ -136,18 +145,21 @@ public enum AttributeContainer<O: ManagedObjectProtocol> {
|
||||
}
|
||||
|
||||
|
||||
// MARK: Internal
|
||||
// MARK: AttributeProtocol
|
||||
|
||||
internal static var attributeType: NSAttributeType {
|
||||
|
||||
return V.cs_rawAttributeType
|
||||
}
|
||||
|
||||
internal let defaultValue: Any?
|
||||
public let keyPath: String
|
||||
internal let isOptional = true
|
||||
internal let isIndexed = false
|
||||
internal let defaultValue: Any?
|
||||
|
||||
internal var accessRawObject: () -> NSManagedObject = {
|
||||
|
||||
fatalError("\(O.self) property values should not be accessed")
|
||||
fatalError("\(O.self) attribute values should not be accessed")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,6 +173,7 @@ internal protocol AttributeProtocol: class {
|
||||
|
||||
var keyPath: String { get }
|
||||
var isOptional: Bool { get }
|
||||
var isIndexed: Bool { get }
|
||||
var defaultValue: Any? { get }
|
||||
var accessRawObject: () -> NSManagedObject { get set }
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ import ObjectiveC
|
||||
|
||||
public protocol EntityProtocol {
|
||||
|
||||
var entityDescription: NSEntityDescription { get }
|
||||
var type: ManagedObject.Type { get }
|
||||
var entityName: EntityName { get }
|
||||
}
|
||||
|
||||
|
||||
@@ -40,74 +41,16 @@ public protocol EntityProtocol {
|
||||
|
||||
public struct Entity<O: ManagedObject>: EntityProtocol {
|
||||
|
||||
public let entityDescription: NSEntityDescription
|
||||
internal var dynamicClass: AnyClass {
|
||||
|
||||
return NSClassFromString(self.entityDescription.managedObjectClassName!)!
|
||||
}
|
||||
|
||||
public init(_ entityName: String) {
|
||||
|
||||
let dynamicClassName = String(reflecting: O.self)
|
||||
.appending("__\(entityName)")
|
||||
.replacingOccurrences(of: ".", with: "_")
|
||||
.replacingOccurrences(of: "<", with: "_")
|
||||
.replacingOccurrences(of: ">", with: "_")
|
||||
// TODO: assign entityName through ModelVersion and
|
||||
// TODO: set NSEntityDescription.userInfo AnyEntity
|
||||
let newClass: AnyClass?
|
||||
|
||||
if NSClassFromString(dynamicClassName) == nil {
|
||||
|
||||
newClass = objc_allocateClassPair(NSManagedObject.self, dynamicClassName, 0)
|
||||
}
|
||||
else {
|
||||
|
||||
newClass = nil
|
||||
}
|
||||
|
||||
defer {
|
||||
|
||||
if let newClass = newClass {
|
||||
|
||||
objc_registerClassPair(newClass)
|
||||
}
|
||||
}
|
||||
|
||||
let entityDescription = NSEntityDescription()
|
||||
entityDescription.userInfo = [
|
||||
EntityIdentifier.UserInfoKey.CoreStoreManagedObjectName: String(reflecting: O.self)
|
||||
]
|
||||
entityDescription.name = entityName
|
||||
entityDescription.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
|
||||
// entityDescription.managedObjectClassName = dynamicClassName // TODO: return to NSManagedObject
|
||||
entityDescription.properties = type(of: self).initializeAttributes(Mirror(reflecting: O.meta))
|
||||
|
||||
self.entityDescription = entityDescription
|
||||
self.type = O.self
|
||||
self.entityName = entityName
|
||||
}
|
||||
|
||||
private static func initializeAttributes(_ mirror: Mirror) -> [NSAttributeDescription] {
|
||||
|
||||
var attributeDescriptions: [NSAttributeDescription] = []
|
||||
for child in mirror.children {
|
||||
|
||||
guard case let property as AttributeProtocol = child.value else {
|
||||
|
||||
continue
|
||||
}
|
||||
let attributeDescription = NSAttributeDescription()
|
||||
attributeDescription.name = property.keyPath
|
||||
attributeDescription.attributeType = type(of: property).attributeType
|
||||
attributeDescription.isOptional = property.isOptional
|
||||
attributeDescription.defaultValue = property.defaultValue
|
||||
attributeDescriptions.append(attributeDescription)
|
||||
}
|
||||
if let baseEntityAttributeDescriptions = mirror.superclassMirror.flatMap(self.initializeAttributes) {
|
||||
|
||||
attributeDescriptions.append(contentsOf: baseEntityAttributeDescriptions)
|
||||
}
|
||||
return attributeDescriptions
|
||||
}
|
||||
// MARK: EntityProtocol
|
||||
|
||||
public let type: ManagedObject.Type
|
||||
public let entityName: EntityName
|
||||
}
|
||||
|
||||
|
||||
@@ -158,10 +101,10 @@ internal struct EntityIdentifier: Hashable {
|
||||
|
||||
internal init(_ entityDescription: NSEntityDescription) {
|
||||
|
||||
if let coreStoreManagedObjectName = entityDescription.userInfo?[EntityIdentifier.UserInfoKey.CoreStoreManagedObjectName] as! String? {
|
||||
if let entity = entityDescription.anyEntity {
|
||||
|
||||
self.category = .coreStore
|
||||
self.interfacedClassName = coreStoreManagedObjectName
|
||||
self.interfacedClassName = NSStringFromClass(entity.type)
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -187,12 +130,53 @@ internal struct EntityIdentifier: Hashable {
|
||||
return self.category.hashValue
|
||||
^ self.interfacedClassName.hashValue
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - NSEntityDescription
|
||||
|
||||
internal extension NSEntityDescription {
|
||||
|
||||
@nonobjc
|
||||
internal var anyEntity: ObjectModel.AnyEntity? {
|
||||
|
||||
get {
|
||||
|
||||
guard let userInfo = self.userInfo,
|
||||
let typeName = userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] as! String?,
|
||||
let entityName = userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] as! String? else {
|
||||
|
||||
return nil
|
||||
}
|
||||
return ObjectModel.AnyEntity(
|
||||
type: NSClassFromString(typeName) as! ManagedObject.Type,
|
||||
entityName: entityName
|
||||
)
|
||||
}
|
||||
set {
|
||||
|
||||
if let newValue = newValue {
|
||||
|
||||
self.userInfo = [
|
||||
UserInfoKey.CoreStoreManagedObjectTypeName: NSStringFromClass(newValue.type),
|
||||
UserInfoKey.CoreStoreManagedObjectEntityName: newValue.entityName
|
||||
]
|
||||
}
|
||||
else {
|
||||
|
||||
self.userInfo = [:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: FilePrivate
|
||||
// MARK: Private
|
||||
|
||||
// MARK: - UserInfoKey
|
||||
|
||||
fileprivate enum UserInfoKey {
|
||||
|
||||
fileprivate static let CoreStoreManagedObjectName = "CoreStoreManagedObjectName"
|
||||
fileprivate static let CoreStoreManagedObjectTypeName = "CoreStoreManagedObjectTypeName"
|
||||
fileprivate static let CoreStoreManagedObjectEntityName = "CoreStoreManagedObjectEntityName"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ import Foundation
|
||||
|
||||
// MARK: - ManagedObject
|
||||
|
||||
open class ManagedObject: ManagedObjectProtocol {
|
||||
open class ManagedObject: ManagedObjectProtocol, Hashable {
|
||||
|
||||
public required init(_ object: NSManagedObject) {
|
||||
|
||||
@@ -45,6 +45,31 @@ open class ManagedObject: ManagedObjectProtocol {
|
||||
}
|
||||
|
||||
|
||||
// MARK: Equatable
|
||||
|
||||
public static func == (lhs: ManagedObject, rhs: ManagedObject) -> Bool {
|
||||
|
||||
guard lhs.isMeta == rhs.isMeta else {
|
||||
|
||||
return false
|
||||
}
|
||||
if lhs.isMeta {
|
||||
|
||||
return type(of: lhs) == type(of: rhs)
|
||||
}
|
||||
return lhs.rawObject!.isEqual(rhs.rawObject!)
|
||||
}
|
||||
|
||||
|
||||
// MARK: Hashable
|
||||
|
||||
public var hashValue: Int {
|
||||
|
||||
return ObjectIdentifier(self).hashValue
|
||||
^ (self.isMeta ? 0 : self.rawObject!.hashValue)
|
||||
}
|
||||
|
||||
|
||||
// MARK: Internal
|
||||
|
||||
internal let rawObject: NSManagedObject?
|
||||
@@ -58,11 +83,17 @@ open class ManagedObject: ManagedObjectProtocol {
|
||||
_ = mirror.superclassMirror.flatMap({ self.initializeAttributes($0, accessRawObject) })
|
||||
for child in mirror.children {
|
||||
|
||||
guard case let property as AttributeProtocol = child.value else {
|
||||
switch child.value {
|
||||
|
||||
case let property as AttributeProtocol:
|
||||
property.accessRawObject = accessRawObject
|
||||
|
||||
case let property as RelationshipProtocol:
|
||||
property.accessRawObject = accessRawObject
|
||||
|
||||
default:
|
||||
continue
|
||||
}
|
||||
property.accessRawObject = accessRawObject
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,6 @@ public protocol ManagedObjectProtocol: class {
|
||||
|
||||
public extension ManagedObjectProtocol where Self: ManagedObject {
|
||||
|
||||
public typealias Attribute = AttributeContainer<Self>
|
||||
|
||||
@inline(__always)
|
||||
public static func keyPath<O: ManagedObject, V: ImportableAttributeType>(_ attribute: (Self) -> AttributeContainer<O>.Required<V>) -> String {
|
||||
|
||||
@@ -73,7 +71,7 @@ extension NSManagedObject: ManagedObjectProtocol {
|
||||
|
||||
// MARK: ManagedObjectProtocol
|
||||
|
||||
public static func cs_from(object: NSManagedObject) -> Self {
|
||||
public class func cs_from(object: NSManagedObject) -> Self {
|
||||
|
||||
@inline(__always)
|
||||
func forceCast<T: NSManagedObject>(_ value: Any) -> T {
|
||||
@@ -83,7 +81,7 @@ extension NSManagedObject: ManagedObjectProtocol {
|
||||
return forceCast(object)
|
||||
}
|
||||
|
||||
public static func cs_forceCreate(entityDescription: NSEntityDescription, into context: NSManagedObjectContext, assignTo store: NSPersistentStore) -> Self {
|
||||
public class func cs_forceCreate(entityDescription: NSEntityDescription, into context: NSManagedObjectContext, assignTo store: NSPersistentStore) -> Self {
|
||||
|
||||
let object = self.init(entity: entityDescription, insertInto: context)
|
||||
defer {
|
||||
@@ -101,12 +99,12 @@ extension ManagedObject {
|
||||
|
||||
// MARK: ManagedObjectProtocol
|
||||
|
||||
public static func cs_from(object: NSManagedObject) -> Self {
|
||||
public class func cs_from(object: NSManagedObject) -> Self {
|
||||
|
||||
return self.init(object)
|
||||
}
|
||||
|
||||
public static func cs_forceCreate(entityDescription: NSEntityDescription, into context: NSManagedObjectContext, assignTo store: NSPersistentStore) -> Self {
|
||||
public class func cs_forceCreate(entityDescription: NSEntityDescription, into context: NSManagedObjectContext, assignTo store: NSPersistentStore) -> Self {
|
||||
|
||||
let type = NSClassFromString(entityDescription.managedObjectClassName!)! as! NSManagedObject.Type
|
||||
let object = type.init(entity: entityDescription, insertInto: context)
|
||||
|
||||
@@ -31,46 +31,315 @@ import Foundation
|
||||
|
||||
public final class ObjectModel {
|
||||
|
||||
public let version: String
|
||||
|
||||
public convenience init(version: String, entities: [EntityProtocol]) {
|
||||
|
||||
self.init(version: version, configurationEntities: [DataStack.defaultConfigurationName: entities])
|
||||
self.init(version: version, entitiesByConfiguration: [DataStack.defaultConfigurationName: entities])
|
||||
}
|
||||
|
||||
public required init(version: String, configurationEntities: [String: [EntityProtocol]]) {
|
||||
public required init(version: String, entitiesByConfiguration: [String: [EntityProtocol]]) {
|
||||
|
||||
var actualEntitiesByConfiguration: [String: Set<AnyEntity>] = [:]
|
||||
for (configuration, entities) in entitiesByConfiguration {
|
||||
|
||||
actualEntitiesByConfiguration[configuration] = Set(entities.map(AnyEntity.init))
|
||||
}
|
||||
let allEntities = Set(actualEntitiesByConfiguration.values.joined())
|
||||
actualEntitiesByConfiguration[DataStack.defaultConfigurationName] = allEntities
|
||||
|
||||
CoreStore.assert(
|
||||
autoreleasepool {
|
||||
|
||||
let expectedCount = allEntities.count
|
||||
return Set(allEntities.map({ ObjectIdentifier($0.type) })).count == expectedCount
|
||||
&& Set(allEntities.map({ $0.entityName })).count == expectedCount
|
||||
},
|
||||
"Ambiguous entity types or entity names were found in the model. Ensure that the entity types and entity names are unique to each other. Entities: \(allEntities)"
|
||||
)
|
||||
|
||||
self.version = version
|
||||
|
||||
var entityConfigurations: [String: Set<NSEntityDescription>] = [:]
|
||||
for (configuration, entities) in configurationEntities {
|
||||
|
||||
entityConfigurations[configuration] = Set(entities.map({ $0.entityDescription }))
|
||||
}
|
||||
let allEntities = Set(entityConfigurations.map({ $0.value }).joined())
|
||||
entityConfigurations[DataStack.defaultConfigurationName] = allEntities
|
||||
|
||||
self.entityConfigurations = entityConfigurations
|
||||
self.entities = allEntities
|
||||
self.entitiesByConfiguration = actualEntitiesByConfiguration
|
||||
self.allEntities = allEntities
|
||||
}
|
||||
|
||||
|
||||
// MARK: Internal
|
||||
|
||||
internal let entities: Set<NSEntityDescription>
|
||||
internal let entityConfigurations: [String: Set<NSEntityDescription>]
|
||||
// MARK: - AnyEntity
|
||||
|
||||
internal struct AnyEntity: EntityProtocol, Hashable {
|
||||
|
||||
internal init(_ entity: EntityProtocol) {
|
||||
|
||||
self.type = entity.type
|
||||
self.entityName = entity.entityName
|
||||
}
|
||||
|
||||
internal init(type: ManagedObject.Type, entityName: String) {
|
||||
|
||||
self.type = type
|
||||
self.entityName = entityName
|
||||
}
|
||||
|
||||
|
||||
// MARK: Equatable
|
||||
|
||||
static func == (lhs: AnyEntity, rhs: AnyEntity) -> Bool {
|
||||
|
||||
return lhs.type == rhs.type
|
||||
&& lhs.entityName == rhs.entityName
|
||||
}
|
||||
|
||||
// MARK: Hashable
|
||||
|
||||
var hashValue: Int {
|
||||
|
||||
return ObjectIdentifier(self.type).hashValue
|
||||
^ self.entityName.hashValue
|
||||
}
|
||||
|
||||
// MARK: EntityProtocol
|
||||
|
||||
internal let type: ManagedObject.Type
|
||||
internal let entityName: EntityName
|
||||
}
|
||||
|
||||
|
||||
// MARK: -
|
||||
|
||||
internal func createModel() -> NSManagedObjectModel {
|
||||
|
||||
let model = NSManagedObjectModel()
|
||||
model.entities = self.entities.sorted(by: { $0.name! < $1.name! })
|
||||
for (configuration, entities) in self.entityConfigurations {
|
||||
let entityDescriptionsByEntity: [AnyEntity: NSEntityDescription] = ModelCache.performUpdate {
|
||||
|
||||
var entityDescriptionsByEntity: [AnyEntity: NSEntityDescription] = [:]
|
||||
for entity in self.allEntities {
|
||||
|
||||
let entityDescription = ModelCache.entityDescription(
|
||||
for: entity,
|
||||
initializer: ObjectModel.firstPassCreateEntityDescription
|
||||
)
|
||||
entityDescriptionsByEntity[entity] = entityDescription
|
||||
}
|
||||
ObjectModel.secondPassConnectRelationshipAttributes(for: entityDescriptionsByEntity)
|
||||
ObjectModel.thirdPassConnectInheritanceTree(for: entityDescriptionsByEntity)
|
||||
return entityDescriptionsByEntity
|
||||
}
|
||||
model.entities = entityDescriptionsByEntity.values.sorted(by: { $0.name! < $1.name! })
|
||||
for (configuration, entities) in self.entitiesByConfiguration {
|
||||
|
||||
model.setEntities(
|
||||
entities.sorted(by: { $0.name! < $1.name! }),
|
||||
entities
|
||||
.map({ entityDescriptionsByEntity[$0]! })
|
||||
.sorted(by: { $0.name! < $1.name! }),
|
||||
forConfigurationName: configuration
|
||||
)
|
||||
}
|
||||
return model
|
||||
}
|
||||
|
||||
|
||||
// MARK: FilePrivate
|
||||
|
||||
fileprivate static func firstPassCreateEntityDescription(from entity: AnyEntity) -> NSEntityDescription {
|
||||
|
||||
let entityDescription = NSEntityDescription()
|
||||
entityDescription.anyEntity = entity
|
||||
entityDescription.name = entity.entityName
|
||||
entityDescription.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
|
||||
|
||||
func createProperties(for type: ManagedObject.Type) -> [NSPropertyDescription] {
|
||||
|
||||
var propertyDescriptions: [NSPropertyDescription] = []
|
||||
for child in Mirror(reflecting: type.meta).children {
|
||||
|
||||
switch child.value {
|
||||
|
||||
case let attribute as AttributeProtocol:
|
||||
let description = NSAttributeDescription()
|
||||
description.name = attribute.keyPath
|
||||
description.attributeType = type(of: attribute).attributeType
|
||||
description.isOptional = attribute.isOptional
|
||||
description.isIndexed = attribute.isIndexed
|
||||
description.defaultValue = attribute.defaultValue
|
||||
description.isTransient = false
|
||||
// TODO: versionHash, renamingIdentifier, etc
|
||||
// TODO: Separate attributes for Value, Transient, Relationship
|
||||
propertyDescriptions.append(description)
|
||||
|
||||
case let relationship as RelationshipProtocol:
|
||||
let description = NSRelationshipDescription()
|
||||
description.name = relationship.keyPath
|
||||
description.minCount = 0
|
||||
description.maxCount = relationship.isToMany ? 0 : 1
|
||||
description.isOrdered = relationship.isOrdered
|
||||
description.deleteRule = relationship.deleteRule
|
||||
// TODO: versionHash, renamingIdentifier, etc
|
||||
// TODO: Separate attributes for Value, Transient, Relationship
|
||||
propertyDescriptions.append(description)
|
||||
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
return propertyDescriptions
|
||||
}
|
||||
|
||||
entityDescription.properties = createProperties(for: entity.type)
|
||||
return entityDescription
|
||||
}
|
||||
|
||||
fileprivate static func secondPassConnectRelationshipAttributes(for entityDescriptionsByEntity: [AnyEntity: NSEntityDescription]) {
|
||||
|
||||
var relationshipsByNameByEntity: [AnyEntity: [String: NSRelationshipDescription]] = [:]
|
||||
for (entity, entityDescription) in entityDescriptionsByEntity {
|
||||
|
||||
relationshipsByNameByEntity[entity] = entityDescription.relationshipsByName
|
||||
}
|
||||
func findEntity(for type: ManagedObject.Type) -> AnyEntity {
|
||||
|
||||
var matchedEntities: Set<AnyEntity> = []
|
||||
for (entity, _) in entityDescriptionsByEntity where entity.type == type {
|
||||
|
||||
matchedEntities.insert(entity)
|
||||
}
|
||||
if matchedEntities.count == 1 {
|
||||
|
||||
return matchedEntities.first!
|
||||
}
|
||||
if matchedEntities.isEmpty {
|
||||
|
||||
CoreStore.abort(
|
||||
"No \(cs_typeName("Entity<\(type)>")) instance found in the \(cs_typeName(ObjectModel.self))."
|
||||
)
|
||||
}
|
||||
else {
|
||||
|
||||
CoreStore.abort(
|
||||
"Ambiguous entity types or entity names were found in the model. Ensure that the entity types and entity names are unique to each other. Entities: \(matchedEntities)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func findInverseRelationshipMatching(destinationEntity: AnyEntity, destinationKeyPath: String) -> NSRelationshipDescription {
|
||||
|
||||
for case (destinationKeyPath, let relationshipDescription) in relationshipsByNameByEntity[destinationEntity]! {
|
||||
|
||||
return relationshipDescription
|
||||
}
|
||||
CoreStore.abort(
|
||||
"The inverse relationship for \"\(destinationEntity.type).\(destinationKeyPath)\" could not be found. Make sure to set the `inverse:` initializer argument for one of the paired \(cs_typeName("Relationship.ToOne<T>")), \(cs_typeName("Relationship.ToManyOrdered<T>")), or \(cs_typeName("Relationship.ToManyUnozrdered<T>"))"
|
||||
)
|
||||
}
|
||||
|
||||
for (entity, entityDescription) in entityDescriptionsByEntity {
|
||||
|
||||
let relationshipsByName = relationshipsByNameByEntity[entity]!
|
||||
for child in Mirror(reflecting: entity.type.meta).children {
|
||||
|
||||
switch child.value {
|
||||
|
||||
case let relationship as RelationshipProtocol:
|
||||
let (destinationType, destinationKeyPath) = relationship.inverse
|
||||
let destinationEntity = findEntity(for: destinationType)
|
||||
let description = relationshipsByName[relationship.keyPath]!
|
||||
description.destinationEntity = entityDescriptionsByEntity[destinationEntity]!
|
||||
|
||||
if let destinationKeyPath = destinationKeyPath {
|
||||
|
||||
let inverseRelationshipDescription = findInverseRelationshipMatching(
|
||||
destinationEntity: destinationEntity,
|
||||
destinationKeyPath: destinationKeyPath
|
||||
)
|
||||
description.inverseRelationship = inverseRelationshipDescription
|
||||
|
||||
inverseRelationshipDescription.inverseRelationship = description
|
||||
inverseRelationshipDescription.destinationEntity = entityDescription
|
||||
|
||||
description.destinationEntity!.properties = description.destinationEntity!.properties
|
||||
}
|
||||
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
for (entity, entityDescription) in entityDescriptionsByEntity {
|
||||
|
||||
for (name, relationshipDescription) in entityDescription.relationshipsByName {
|
||||
|
||||
CoreStore.assert(
|
||||
relationshipDescription.destinationEntity != nil,
|
||||
"The destination entity for relationship \"\(entity.type).\(name)\" could not be resolved."
|
||||
)
|
||||
CoreStore.assert(
|
||||
relationshipDescription.inverseRelationship != nil,
|
||||
"The inverse relationship for \"\(entity.type).\(name)\" could not be found. Make sure to set the `inverse:` argument of the initializer for one of the paired \(cs_typeName("Relationship.ToOne<T>")), \(cs_typeName("Relationship.ToManyOrdered<T>")), or \(cs_typeName("Relationship.ToManyUnozrdered<T>"))"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate static func thirdPassConnectInheritanceTree(for entityDescriptionsByEntity: [AnyEntity: NSEntityDescription]) {
|
||||
|
||||
func connectBaseEntity(mirror: Mirror, entityDescription: NSEntityDescription) {
|
||||
|
||||
guard let superclassMirror = mirror.superclassMirror,
|
||||
let superType = superclassMirror.subjectType as? ManagedObject.Type,
|
||||
superType != ManagedObject.self else {
|
||||
|
||||
return
|
||||
}
|
||||
for (superEntity, superEntityDescription) in entityDescriptionsByEntity where superEntity.type == superType {
|
||||
|
||||
if !superEntityDescription.subentities.contains(entityDescription) {
|
||||
|
||||
superEntityDescription.subentities.append(entityDescription)
|
||||
}
|
||||
connectBaseEntity(mirror: superclassMirror, entityDescription: superEntityDescription)
|
||||
}
|
||||
}
|
||||
for (entity, entityDescription) in entityDescriptionsByEntity {
|
||||
|
||||
connectBaseEntity(
|
||||
mirror: Mirror(reflecting: entity.type.meta),
|
||||
entityDescription: entityDescription
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Private
|
||||
|
||||
private let version: String
|
||||
private let allEntities: Set<AnyEntity>
|
||||
private let entitiesByConfiguration: [String: Set<AnyEntity>]
|
||||
}
|
||||
|
||||
|
||||
// MARK: - ModelCache
|
||||
|
||||
fileprivate enum ModelCache {
|
||||
|
||||
fileprivate static func performUpdate<T>(_ closure: () -> T) -> T {
|
||||
|
||||
return self.barrierQueue.cs_barrierSync(closure)
|
||||
}
|
||||
|
||||
fileprivate static func entityDescription(for entity: ObjectModel.AnyEntity, initializer: (ObjectModel.AnyEntity) -> NSEntityDescription) -> NSEntityDescription {
|
||||
|
||||
if let cachedEntityDescription = self.entityDescriptionsByEntity[entity] {
|
||||
|
||||
return cachedEntityDescription
|
||||
}
|
||||
let entityDescription = withoutActuallyEscaping(initializer, do: { $0(entity) })
|
||||
self.entityDescriptionsByEntity[entity] = entityDescription
|
||||
return entityDescription
|
||||
}
|
||||
|
||||
|
||||
// MARK: Private
|
||||
|
||||
private static let barrierQueue = DispatchQueue.concurrent("com.coreStore.modelCacheBarrierQueue")
|
||||
|
||||
private static var entityDescriptionsByEntity: [ObjectModel.AnyEntity: NSEntityDescription] = [:]
|
||||
}
|
||||
|
||||
200
Sources/Setup/Dynamic Models/Relationship.swift
Normal file
200
Sources/Setup/Dynamic Models/Relationship.swift
Normal file
@@ -0,0 +1,200 @@
|
||||
//
|
||||
// Relationship.swift
|
||||
// CoreStore
|
||||
//
|
||||
// Copyright © 2017 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: - ManagedObjectProtocol
|
||||
|
||||
public extension ManagedObjectProtocol where Self: ManagedObject {
|
||||
|
||||
public typealias Relationship = RelationshipContainer<Self>
|
||||
}
|
||||
|
||||
|
||||
// MARK: - RelationshipContainer
|
||||
|
||||
public enum RelationshipContainer<O: ManagedObject> {
|
||||
|
||||
// MARK: - ToOne
|
||||
|
||||
public final class ToOne<D: ManagedObject>: RelationshipProtocol {
|
||||
|
||||
// MARK: -
|
||||
|
||||
public static func .= (_ relationship: RelationshipContainer<O>.ToOne<D>, _ value: D?) {
|
||||
|
||||
relationship.value = value
|
||||
}
|
||||
|
||||
public static postfix func * (_ relationship: RelationshipContainer<O>.ToOne<D>) -> D? {
|
||||
|
||||
return relationship.value
|
||||
}
|
||||
|
||||
public init(_ keyPath: String, deleteRule: DeleteRule = .nullify) {
|
||||
|
||||
self.keyPath = keyPath
|
||||
self.deleteRule = deleteRule.nativeValue
|
||||
self.inverse = (D.self, nil)
|
||||
}
|
||||
|
||||
public init(_ keyPath: String, inverse: (D) -> RelationshipContainer<D>.ToOne<O>, deleteRule: DeleteRule = .nullify) {
|
||||
|
||||
self.keyPath = keyPath
|
||||
self.deleteRule = deleteRule.nativeValue
|
||||
|
||||
let inverseRelationship = inverse(D.meta)
|
||||
self.inverse = (D.self, inverseRelationship.keyPath)
|
||||
}
|
||||
|
||||
public var value: D? {
|
||||
|
||||
get {
|
||||
|
||||
let object = self.accessRawObject()
|
||||
let key = self.keyPath
|
||||
return object.value(forKey: key)
|
||||
.flatMap({ D.cs_from(object: $0 as! NSManagedObject) })
|
||||
}
|
||||
set {
|
||||
|
||||
let object = self.accessRawObject()
|
||||
let key = self.keyPath
|
||||
object.setValue(newValue?.rawObject, forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: RelationshipProtocol
|
||||
|
||||
public let keyPath: String
|
||||
|
||||
internal let isToMany = false
|
||||
internal let isOrdered = false
|
||||
internal let deleteRule: NSDeleteRule
|
||||
internal let inverse: (type: ManagedObject.Type, keyPath: String?)
|
||||
|
||||
internal var accessRawObject: () -> NSManagedObject = {
|
||||
|
||||
fatalError("\(O.self) relationship values should not be accessed")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - ToManyOrdered
|
||||
|
||||
public final class ToManyOrdered<D: ManagedObject>: RelationshipProtocol {
|
||||
|
||||
// MARK: -
|
||||
|
||||
public static func .= (_ relationship: RelationshipContainer<O>.ToManyOrdered<D>, _ value: [D]) {
|
||||
|
||||
relationship.value = value
|
||||
}
|
||||
|
||||
public static postfix func * (_ relationship: RelationshipContainer<O>.ToManyOrdered<D>) -> [D] {
|
||||
|
||||
return relationship.value
|
||||
}
|
||||
|
||||
public init(_ keyPath: String, deleteRule: DeleteRule = .nullify) {
|
||||
|
||||
self.keyPath = keyPath
|
||||
self.deleteRule = deleteRule.nativeValue
|
||||
self.inverse = (D.self, nil)
|
||||
}
|
||||
|
||||
public var value: [D] {
|
||||
|
||||
get {
|
||||
|
||||
let object = self.accessRawObject()
|
||||
let key = self.keyPath
|
||||
guard let orderedSet = object.value(forKey: key) as! NSOrderedSet? else {
|
||||
|
||||
return []
|
||||
}
|
||||
return orderedSet.array as! [D]
|
||||
}
|
||||
set {
|
||||
|
||||
let object = self.accessRawObject()
|
||||
let key = self.keyPath
|
||||
object.setValue(NSOrderedSet(array: newValue), forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: RelationshipProtocol
|
||||
|
||||
public let keyPath: String
|
||||
|
||||
internal let isToMany = true
|
||||
internal let isOptional = true
|
||||
internal let isOrdered = true
|
||||
internal let deleteRule: NSDeleteRule
|
||||
internal let inverse: (type: ManagedObject.Type, keyPath: String?)
|
||||
|
||||
internal var accessRawObject: () -> NSManagedObject = {
|
||||
|
||||
fatalError("\(O.self) relationship values should not be accessed")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DeleteRule
|
||||
|
||||
public enum DeleteRule {
|
||||
|
||||
case nullify
|
||||
case cascade
|
||||
case deny
|
||||
|
||||
fileprivate var nativeValue: NSDeleteRule {
|
||||
|
||||
switch self {
|
||||
|
||||
case .nullify: return .nullifyDeleteRule
|
||||
case .cascade: return .cascadeDeleteRule
|
||||
case .deny: return .denyDeleteRule
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - RelationshipProtocol
|
||||
|
||||
internal protocol RelationshipProtocol: class {
|
||||
|
||||
var keyPath: String { get }
|
||||
var isToMany: Bool { get }
|
||||
var isOrdered: Bool { get }
|
||||
var deleteRule: NSDeleteRule { get }
|
||||
var inverse: (type: ManagedObject.Type, keyPath: String?) { get }
|
||||
var accessRawObject: () -> NSManagedObject { get set }
|
||||
}
|
||||
Reference in New Issue
Block a user