Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
helje5 committed Oct 7, 2023
2 parents 4b29c44 + a971db3 commit 1530d28
Show file tree
Hide file tree
Showing 14 changed files with 66 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,8 @@ extension ModelMacro {
/// - Parameters:
// - entity: An `NSEntityDescription` describing the object.
// - context: An `NSManagedObjectContext` the object should be inserted into.
@available(*, deprecated, renamed: "init(context:)",
message: "Use `init(context:)` or `init()` instead.")
\(raw: access)override init(entity: CoreData.NSEntityDescription, insertInto context: NSManagedObjectContext?)
{
assert(entity === Self._$entity, "Attempt to initialize PersistentModel w/ different entity?")
super.init(entity: entity, insertInto: context)
}
"""
Expand All @@ -67,7 +64,7 @@ extension ModelMacro {
/// - Parameters:
// - context: An `NSManagedObjectContext` the object should be inserted into.
\(raw: access)init(context: CoreData.NSManagedObjectContext?) {
super.init(entity: Self._$entity, insertInto: context)
super.init(entity: Self.entity(), insertInto: context)
}
"""
)
Expand All @@ -78,7 +75,7 @@ extension ModelMacro {
/// Initialize a `\(modelClassName)` object w/o inserting it into a
/// context.
\(raw: access)init() {
super.init(entity: Self._$entity, insertInto: nil)
super.init(entity: Self.entity(), insertInto: nil)
}
"""
)
Expand Down
22 changes: 0 additions & 22 deletions Sources/ManagedModelMacros/ModelMacro/ModelMembers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import SwiftDiagnostics
* @attached(member, names: // Those are the names we add
* named(init), // Initializers.
* named(schemaMetadata), // The metadata.
* named(entity), // Override the `entity()` function.
* named(_$entity), // The cached the Entity
* named(_$originalName),
* named(_$hashModifier)
* )
Expand Down Expand Up @@ -55,17 +53,6 @@ extension ModelMacro: MemberMacro { // @attached(member, names:...)
)
newMembers.append(DeclSyntax(metadata))

if classDecl.findFunctionWithName("entity", isStaticOrClass: true,
parameterCount: 0) == nil
{
newMembers.append(
"""
/// Returns the `NSEntityDescription` associated w/ the `PersistentModel`.
\(raw: access)override class func entity() -> NSEntityDescription { _$entity }
"""
)
}

// TODO: Lookup `originalName` parameter in `macroNode`
newMembers.append(
"""
Expand All @@ -77,15 +64,6 @@ extension ModelMacro: MemberMacro { // @attached(member, names:...)
\(raw: access)static let _$hashModifier : String? = nil
"""
)

newMembers.append(
"""
/// The shared `NSEntityDescription` for the `PersistentModel`.
/// Never modify the referred object!
\(raw: access)static let _$entity =
ManagedModels.SchemaBuilder.shared._entity(for: \(modelClassName).self)
"""
)

return newMembers
}
Expand Down
2 changes: 0 additions & 2 deletions Sources/ManagedModels/ModelMacroDefinition.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,6 @@ public macro _PersistedProperty() =
@attached(member, names: // Those are the names we add
named(init), // Initializers.
named(schemaMetadata), // The metadata.
named(entity), // Override the `entity()` function.
named(_$entity), // The cached the Entity
named(_$originalName),
named(_$hashModifier)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,6 @@ public extension PersistentModel {
func _setOptionalToOneValue<T>(forKey key: String, to model: T?)
where T: PersistentModel
{
#if DEBUG
let relship = Self._$entity.relationshipsByName[key]!
assert(!relship.isToMany, "relship: \(relship)")
#endif
if let model {
if model.modelContext != self.modelContext {
if let otherCtx = model.modelContext, self.modelContext == nil {
Expand Down
15 changes: 1 addition & 14 deletions Sources/ManagedModels/PersistentModel/PersistentModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,6 @@ public protocol PersistentModel: NSManagedObject, Hashable, Identifiable {
*/
static var schemaMetadata : [ NSManagedObjectModel.PropertyMetadata ] { get }

/**
* Reflection data for the model.
*
* This is considered private, use a Schema to access entities, and NEVER
* modify the schema objects after they got setup.
*
* API DIFF: SwiftData doesn't have that, always builds dynamically.
*/
static var _$entity : NSEntityDescription { get }
// Why have that? Cheap cache.

/// The `renamingIdentifier` of the model.
static var _$originalName : String? { get }
Expand All @@ -55,16 +45,13 @@ extension PersistentModel {
public static var schemaMetadata : [ NSManagedObjectModel.PropertyMetadata ] {
fatalError("Subclass needs to implement `schemaMetadata`")
}

@inlinable
public static var _$entity : NSEntityDescription { self.entity() }
}

public extension PersistentModel {

@inlinable
static func fetchRequest() -> NSFetchRequest<Self> {
NSFetchRequest<Self>(entityName: _$entity.name ?? NSStringFromClass(self))
NSFetchRequest<Self>(entityName: _typeName(Self.self, qualified: false))
}

@inlinable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public extension CoreData.NSAttributeDescription {
struct TypeConfiguration {
let attributeType : NSAttributeType
let isOptional : Bool
let attributeValueClassName : String
let attributeValueClassName : String?
}
}

Expand Down Expand Up @@ -37,35 +37,35 @@ extension Int: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .integer64AttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}
extension Int16: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .integer16AttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}
extension Int32: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .integer32AttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}
extension Int64: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .integer64AttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}
extension Int8: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .integer16AttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}

Expand All @@ -91,30 +91,30 @@ extension String: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .stringAttributeType,
isOptional : false,
attributeValueClassName : "NSString"
attributeValueClassName : nil
)
}

extension Bool: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .booleanAttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}

extension Double: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .doubleAttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}
extension Float: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .floatAttributeType,
isOptional : false,
attributeValueClassName : "NSNumber"
attributeValueClassName : nil
)
}

Expand All @@ -124,38 +124,38 @@ extension Date: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .dateAttributeType,
isOptional : false,
attributeValueClassName : "NSDate"
attributeValueClassName : nil
)
}

extension Data: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .binaryDataAttributeType,
isOptional : false,
attributeValueClassName : "NSDate"
attributeValueClassName : nil
)
}

extension Decimal: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .decimalAttributeType,
isOptional : false,
attributeValueClassName : "NSDecimalNumber"
attributeValueClassName : nil
)
}

extension UUID: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .UUIDAttributeType,
isOptional : false,
attributeValueClassName : "NSUUID"
attributeValueClassName : nil
)
}

extension URL: CoreDataPrimitiveValue {
public static let coreDataValue = NSAttributeDescription.TypeConfiguration(
attributeType : .URIAttributeType,
isOptional : false,
attributeValueClassName : "NSURL"
attributeValueClassName : nil
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ extension CoreData.NSAttributeDescription: SchemaProperty {
let config = primitiveType.coreDataValue
self.attributeType = config.attributeType
self.isOptional = config.isOptional
self.attributeValueClassName = config.attributeValueClassName
if let newClassName = config.attributeValueClassName {
self.attributeValueClassName = newClassName
}
return
}

Expand All @@ -55,7 +57,9 @@ extension CoreData.NSAttributeDescription: SchemaProperty {
let config = primitiveType.coreDataValue
self.attributeType = config.attributeType
self.isOptional = config.isOptional
self.attributeValueClassName = config.attributeValueClassName
if let newClassName = config.attributeValueClassName {
self.attributeValueClassName = newClassName
}
return true
}
else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@ public extension NSManagedObjectModel {
// - encodingVersion
// - version

@available(*, deprecated, renamed: "model(for:)", message:
"""
Entities can only be used in one NSManagedObjectModel, use the `model(for:)`
static function to get access to s ahred, cached model.
"""
)
@inlinable
convenience init(_ entities: NSEntityDescription...,
version: Schema.Version = Version(1, 0, 0))
Expand All @@ -25,25 +19,13 @@ public extension NSManagedObjectModel {
self.entities = entities
}

@available(*, deprecated, renamed: "model(for:)", message:
"""
Entities can only be used in one NSManagedObjectModel, use the `model(for:)`
static function to get access to s ahred, cached model.
"""
)
convenience init(_ types: [ any PersistentModel.Type ],
version: Schema.Version = Version(1, 0, 0))
{
self.init()
self.entities = SchemaBuilder.shared.lookupAllEntities(for: types)
self.entities = SchemaBuilder().lookupAllEntities(for: types)
}

@available(*, deprecated, renamed: "model(for:)", message:
"""
Entities can only be used in one NSManagedObjectModel, use the `model(for:)`
static function to get access to s ahred, cached model.
"""
)
@inlinable
convenience init(versionedSchema: any VersionedSchema.Type) {
self.init(versionedSchema.models,
Expand All @@ -56,9 +38,11 @@ public extension NSManagedObjectModel {

private let lock = NSLock()
private var map = [ Set<ObjectIdentifier> : NSManagedObjectModel ]()
private let sharedBuilder = SchemaBuilder()

public extension NSManagedObjectModel {

/// A cached version of the initializer.
static func model(for versionedSchema: VersionedSchema.Type)
-> NSManagedObjectModel
{
Expand Down Expand Up @@ -86,7 +70,7 @@ public extension NSManagedObjectModel {
if let cachedMOM { mom = cachedMOM }
else {
mom = NSManagedObjectModel()
mom.entities = SchemaBuilder.shared.lookupAllEntities(for: types)
mom.entities = sharedBuilder.lookupAllEntities(for: types)
map[typeIDs] = mom
}
lock.unlock()
Expand Down
10 changes: 2 additions & 8 deletions Sources/ManagedModels/SchemaGeneration/SchemaBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,11 @@ import CoreData
*/
public final class SchemaBuilder {
// Notes:
// - this MUST NOT call `.entity` on the model! might recurse w/ lock, this
// - this MUST NOT call `.entity()` on the model! might recurse w/ lock, this
// object is the authority!
// - there can be multiple entities that use the same name, this spans the
// whole type system. E.g. when versioned schemas are used.

/**
* A shared SchemaBuilder that caches `NSEntityDescription` values for
* ``PersistentModel`` `NSManagedObject`'s.
*/
public static let shared = SchemaBuilder()


private let lock = NSLock() // TODO: use better lock :-)

/// ObjectIdentifier of PersistentModel type to the associated schema.
Expand Down
1 change: 0 additions & 1 deletion Tests/ManagedModelTests/BasicModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ final class BasicModelTests: XCTestCase {

func testEntityName() throws {
let addressType = Fixtures.PersonAddressSchema.Address.self
XCTAssertEqual(addressType._$entity.name, "Address")
XCTAssertEqual(addressType.entity().name, "Address")
}

Expand Down
9 changes: 5 additions & 4 deletions Tests/ManagedModelTests/CoreDataAssumptionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ final class CoreDataAssumptionsTests: XCTestCase {
let relationship = NSRelationshipDescription()
relationship.name = "addresses"
//relationship.destinationEntity =
// Fixtures.PersonAddressSchema.Address._$entity
// Fixtures.PersonAddressSchema.Address.entity()
//relationship.inverseRelationship =
// Fixtures.PersonAddressSchema.Address._$entity.relationshipsByName["person"]
// Fixtures.PersonAddressSchema.Address.entity().relationshipsByName["person"]

// This just seems to be the default.
XCTAssertTrue(relationship.isToMany)
Expand All @@ -32,9 +32,10 @@ final class CoreDataAssumptionsTests: XCTestCase {
let relationship = NSRelationshipDescription()
relationship.name = "person"
relationship.maxCount = 1 // toOne marker!
#if false // old
relationship.destinationEntity =
Fixtures.PersonAddressSchema.Person._$entity
// Yes! This does not work at this point.
Fixtures.PersonAddressSchema.Person.entity()
#endif
XCTAssertFalse(relationship.isToMany)
}

Expand Down
Loading

0 comments on commit 1530d28

Please sign in to comment.