From 5dcf29011a1f21f65e8745e4cec29dd16f525007 Mon Sep 17 00:00:00 2001 From: John Estropia Date: Tue, 10 Sep 2024 11:14:39 +0900 Subject: [PATCH] Support typed errors. Misc formatting --- Playground_macOS.playground/Contents.swift | 22 +- Sources/AsynchronousDataTransaction.swift | 43 +- Sources/BaseDataTransaction+Importing.swift | 307 +++++----- Sources/BaseDataTransaction+Querying.swift | 206 +++++-- Sources/BaseDataTransaction.swift | 70 ++- ...reStore+CustomDebugStringConvertible.swift | 29 +- Sources/CoreStore+Logging.swift | 31 +- Sources/CoreStoreLogger.swift | 46 +- Sources/CoreStoreObject+Observing.swift | 89 ++- Sources/CoreStoreObject+Querying.swift | 74 ++- Sources/CoreStoreObject.swift | 17 +- Sources/CoreStoreSchema.swift | 61 +- Sources/CustomSchemaMappingProvider.swift | 61 +- Sources/DataStack+Concurrency.swift | 42 +- Sources/DataStack+DataSources.swift | 38 +- Sources/DataStack+Migration.swift | 85 ++- Sources/DataStack+Observing.swift | 96 ++- Sources/DataStack+Querying.swift | 178 ++++-- Sources/DataStack+Reactive.swift | 14 +- Sources/DataStack+Transaction.swift | 34 +- Sources/DataStack.AddStoragePublisher.swift | 6 +- Sources/DataStack.swift | 21 +- Sources/DefaultLogger.swift | 39 +- Sources/DispatchQueue+CoreStore.swift | 63 +- Sources/DynamicObject.swift | 82 ++- Sources/Entity.swift | 47 +- Sources/FIeldRelationshipType.swift | 84 ++- Sources/FetchableSource.swift | 102 +++- Sources/Field.Coded.swift | 229 ++++++-- Sources/Field.Relationship.swift | 18 +- Sources/Field.Stored.swift | 58 +- Sources/Field.Virtual.swift | 67 ++- Sources/FieldProtocol.swift | 12 +- Sources/From+Querying.swift | 400 +++++++++---- Sources/From.swift | 100 +++- Sources/ImportableObject.swift | 19 +- Sources/ImportableUniqueObject.swift | 54 +- Sources/InferredSchemaMappingProvider.swift | 9 +- ...ls.CoreStoreFetchedResultsController.swift | 9 +- .../Internals.DiffableDataUIDispatcher.swift | 9 +- ...edDiffableDataSourceSnapshotDelegate.swift | 22 +- ...als.FetchedResultsControllerDelegate.swift | 23 +- Sources/Internals.MigrationManager.swift | 11 +- Sources/Internals.NotificationObserver.swift | 7 +- ...Internals.SharedNotificationObserver.swift | 17 +- Sources/Internals.swift | 45 +- Sources/Into.swift | 51 +- Sources/KeyPath+Querying.swift | 556 ++++++++++++++---- Sources/ListPublisher+Reactive.swift | 6 +- Sources/ListPublisher.SnapshotPublisher.swift | 6 +- Sources/ListPublisher.swift | 6 +- Sources/NSEntityDescription+Migration.swift | 28 +- ...FetchedResultsController+Convenience.swift | 68 ++- Sources/NSManagedObject+Convenience.swift | 45 +- Sources/NSManagedObjectContext+Querying.swift | 286 ++++++--- .../NSPersistentStoreCoordinator+Setup.swift | 54 +- Sources/ObjectProxy.swift | 42 +- Sources/ObjectPublisher+Reactive.swift | 28 +- .../ObjectPublisher.SnapshotPublisher.swift | 6 +- Sources/QueryableSource.swift | 38 +- Sources/SQLiteStore.swift | 58 +- Sources/SchemaHistory.swift | 27 +- Sources/SchemaMappingProvider.swift | 9 +- Sources/Select.swift | 236 ++++++-- Sources/StorageInterface.swift | 17 +- Sources/SynchronousDataTransaction.swift | 45 +- Sources/UnsafeDataModelSchema.swift | 7 +- Sources/UnsafeDataTransaction+Observing.swift | 90 ++- Sources/UnsafeDataTransaction.swift | 16 +- Sources/Where.Expression.swift | 95 ++- Sources/Where.swift | 420 +++++++++---- Sources/WhereClauseType.swift | 48 +- Sources/XcodeDataModelSchema.swift | 25 +- Sources/XcodeSchemaMappingProvider.swift | 19 +- 74 files changed, 3987 insertions(+), 1441 deletions(-) diff --git a/Playground_macOS.playground/Contents.swift b/Playground_macOS.playground/Contents.swift index 52228f6..05f6fa7 100644 --- a/Playground_macOS.playground/Contents.swift +++ b/Playground_macOS.playground/Contents.swift @@ -17,6 +17,12 @@ class Animal: CoreStoreObject { var master: Person? } +class Dog: Animal { + + @Field.Stored("name") + var name: String = "" +} + class Person: CoreStoreObject { @Field.Stored("name") @@ -33,16 +39,20 @@ let dataStack = DataStack( modelVersion: "V1", entities: [ Entity("Animal"), - Entity("Person") - ], + Entity("Person"), + Entity("Dog") + ]/*, versionLock: [ "Animal": [0x4a201cc685d53c0a, 0x16e6c3b561577875, 0xb032e2da61c792a0, 0xa133b801051acee4], "Person": [0xca938eea1af4bd56, 0xbca30994506356ad, 0x7a7cc655898816ef, 0x1a4551ffedc9b214] - ] + ]*/ ) ) dataStack.addStorage( - SQLiteStore(fileName: "data.sqlite"), + SQLiteStore( + fileName: "data.sqlite", + localStorageOptions: .recreateStoreOnModelMismatch + ), completion: { result in switch result { @@ -73,8 +83,8 @@ dataStack.addStorage( case .success: /// Accessing Objects ===== let bird = try! dataStack.fetchOne( - From() - .where(\.$species == "Sparrow") + From() + .where(\Dog.$species == "Sparrow") )! print(bird.species) print(bird.color as Any) diff --git a/Sources/AsynchronousDataTransaction.swift b/Sources/AsynchronousDataTransaction.swift index fd6f304..46e0891 100644 --- a/Sources/AsynchronousDataTransaction.swift +++ b/Sources/AsynchronousDataTransaction.swift @@ -41,7 +41,7 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { ``` - Important: Never use `try?` or `try!` on a `cancel()` call. Always use `try`. Using `try?` will swallow the cancellation and the transaction will proceed to commit as normal. Using `try!` will crash the app as `cancel()` will *always* throw an error. */ - public func cancel() throws -> Never { + public func cancel() throws(CoreStoreError) -> Never { throw CoreStoreError.userCancelled } @@ -66,8 +66,10 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter into: the `Into` clause indicating the destination `NSManagedObject` or `CoreStoreObject` entity type and the destination configuration - returns: a new `NSManagedObject` or `CoreStoreObject` instance of the specified entity type. */ - public override func create(_ into: Into) -> O { - + public override func create( + _ into: Into + ) -> O { + Internals.assert( !self.isCommitted, "Attempted to create an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))." @@ -82,8 +84,10 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter object: the `NSManagedObject` or `CoreStoreObject` to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public override func edit(_ object: O?) -> O? { - + public override func edit( + _ object: O? + ) -> O? { + Internals.assert( !self.isCommitted, "Attempted to update an entity of type \(Internals.typeName(object)) from an already committed \(Internals.typeName(self))." @@ -99,8 +103,11 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter objectID: the `NSManagedObjectID` for the object to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public override func edit(_ into: Into, _ objectID: NSManagedObjectID) -> O? { - + public override func edit( + _ into: Into, + _ objectID: NSManagedObjectID + ) -> O? { + Internals.assert( !self.isCommitted, "Attempted to update an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))." @@ -114,7 +121,9 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter objectIDs: the `NSManagedObjectID`s of the objects to delete */ - public override func delete(objectIDs: S) where S.Iterator.Element: NSManagedObjectID { + public override func delete( + objectIDs: S + ) where S.Iterator.Element: NSManagedObjectID { Internals.assert( !self.isCommitted, @@ -130,7 +139,10 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter object: the `ObjectRepresentation` representing an `NSManagedObject` or `CoreStoreObject` to be deleted - parameter objects: other `ObjectRepresentation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public override func delete(_ object: O?, _ objects: O?...) { + public override func delete( + _ object: O?, + _ objects: O?... + ) { Internals.assert( !self.isCommitted, @@ -145,7 +157,9 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { - parameter objects: the `ObjectRepresenation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public override func delete(_ objects: S) where S.Iterator.Element: ObjectRepresentation { + public override func delete( + _ objects: S + ) where S.Iterator.Element: ObjectRepresentation { Internals.assert( !self.isCommitted, @@ -173,8 +187,13 @@ public final class AsynchronousDataTransaction: BaseDataTransaction { ) } - internal func autoCommit(_ completion: @escaping (_ hasChanges: Bool, _ error: CoreStoreError?) -> Void) { - + internal func autoCommit( + _ completion: @escaping ( + _ hasChanges: Bool, + _ error: CoreStoreError? + ) -> Void + ) { + self.isCommitted = true let group = DispatchGroup() group.enter() diff --git a/Sources/BaseDataTransaction+Importing.swift b/Sources/BaseDataTransaction+Importing.swift index 93803d2..0a7a82c 100644 --- a/Sources/BaseDataTransaction+Importing.swift +++ b/Sources/BaseDataTransaction+Importing.swift @@ -41,25 +41,26 @@ extension BaseDataTransaction { */ public func importObject( _ into: Into, - source: O.ImportSource) throws -> O? { - - Internals.assert( - self.isRunningInAllowedQueue(), - "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." - ) - - return try autoreleasepool { - - let entityType = into.entityClass - guard entityType.shouldInsert(from: source, in: self) else { - - return nil - } - - let object = self.create(into) - try object.didInsert(from: source, in: self) - return object + source: O.ImportSource + ) throws(any Swift.Error) -> O? { + + Internals.assert( + self.isRunningInAllowedQueue(), + "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." + ) + + return try Internals.autoreleasepool { + + let entityType = into.entityClass + guard entityType.shouldInsert(from: source, in: self) else { + + return nil } + + let object = self.create(into) + try object.didInsert(from: source, in: self) + return object + } } /** @@ -71,22 +72,23 @@ extension BaseDataTransaction { */ public func importObject( _ object: O, - source: O.ImportSource) throws { - - Internals.assert( - self.isRunningInAllowedQueue(), - "Attempted to import an object of type \(Internals.typeName(object)) outside the transaction's designated queue." - ) - - try autoreleasepool { - - let entityType = object.runtimeType() - guard entityType.shouldInsert(from: source, in: self) else { - - return - } - try object.didInsert(from: source, in: self) + source: O.ImportSource + ) throws(any Swift.Error) { + + Internals.assert( + self.isRunningInAllowedQueue(), + "Attempted to import an object of type \(Internals.typeName(object)) outside the transaction's designated queue." + ) + + try Internals.autoreleasepool { + + let entityType = object.runtimeType() + guard entityType.shouldInsert(from: source, in: self) else { + + return } + try object.didInsert(from: source, in: self) + } } /** @@ -99,30 +101,31 @@ extension BaseDataTransaction { */ public func importObjects( _ into: Into, - sourceArray: S) throws -> [O] where S.Iterator.Element == O.ImportSource { - - Internals.assert( - self.isRunningInAllowedQueue(), - "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." - ) - - return try autoreleasepool { - - return try sourceArray.compactMap { (source) -> O? in - - let entityType = into.entityClass - guard entityType.shouldInsert(from: source, in: self) else { - - return nil - } - return try autoreleasepool { - - let object = self.create(into) - try object.didInsert(from: source, in: self) - return object - } + sourceArray: S + ) throws(any Swift.Error) -> [O] where S.Iterator.Element == O.ImportSource { + + Internals.assert( + self.isRunningInAllowedQueue(), + "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." + ) + + return try Internals.autoreleasepool { + + return try sourceArray.compactMap { (source) -> O? in + + let entityType = into.entityClass + guard entityType.shouldInsert(from: source, in: self) else { + + return nil + } + return try autoreleasepool { + + let object = self.create(into) + try object.didInsert(from: source, in: self) + return object } } + } } /** @@ -135,43 +138,44 @@ extension BaseDataTransaction { */ public func importUniqueObject( _ into: Into, - source: O.ImportSource) throws -> O? { - - Internals.assert( - self.isRunningInAllowedQueue(), - "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." - ) - - return try autoreleasepool { - - let entityType = into.entityClass - let uniqueIDKeyPath = entityType.uniqueIDKeyPath - guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else { - + source: O.ImportSource + ) throws(any Swift.Error) -> O? { + + Internals.assert( + self.isRunningInAllowedQueue(), + "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." + ) + + return try Internals.autoreleasepool { + + let entityType = into.entityClass + let uniqueIDKeyPath = entityType.uniqueIDKeyPath + guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else { + + return nil + } + + if let object = try self.fetchOne(From(entityType), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) { + + guard entityType.shouldUpdate(from: source, in: self) else { + return nil } - - if let object = try self.fetchOne(From(entityType), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) { - - guard entityType.shouldUpdate(from: source, in: self) else { - - return nil - } - try object.update(from: source, in: self) - return object - } - else { - - guard entityType.shouldInsert(from: source, in: self) else { - - return nil - } - let object = self.create(into) - object.uniqueIDValue = uniqueIDValue - try object.didInsert(from: source, in: self) - return object - } + try object.update(from: source, in: self) + return object } + else { + + guard entityType.shouldInsert(from: source, in: self) else { + + return nil + } + let object = self.create(into) + object.uniqueIDValue = uniqueIDValue + try object.didInsert(from: source, in: self) + return object + } + } } /** @@ -188,71 +192,74 @@ extension BaseDataTransaction { public func importUniqueObjects( _ into: Into, sourceArray: S, - preProcess: @escaping (_ mapping: [O.UniqueIDType: O.ImportSource]) throws -> [O.UniqueIDType: O.ImportSource] = { $0 }) throws -> [O] where S.Iterator.Element == O.ImportSource { - - Internals.assert( - self.isRunningInAllowedQueue(), - "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." - ) - - return try autoreleasepool { - - let entityType = into.entityClass - var importSourceByID = Dictionary() - let sortedIDs = try autoreleasepool { - - return try sourceArray.compactMap { (source) -> O.UniqueIDType? in - - guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else { - - return nil - } - importSourceByID[uniqueIDValue] = source // effectively replaces duplicate with the latest - return uniqueIDValue - } - } - - importSourceByID = try autoreleasepool { try preProcess(importSourceByID) } + preProcess: @escaping ( + _ mapping: [O.UniqueIDType: O.ImportSource] + ) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 } + ) throws(any Swift.Error) -> [O] where S.Iterator.Element == O.ImportSource { - var existingObjectsByID = Dictionary() - try self - .fetchAll(From(entityType), Where(entityType.uniqueIDKeyPath, isMemberOf: sortedIDs)) - .forEach { existingObjectsByID[$0.uniqueIDValue] = $0 } - - var processedObjectIDs = Set() - var result = [O]() - - for objectID in sortedIDs where !processedObjectIDs.contains(objectID) { - - guard let source = importSourceByID[objectID] else { - - continue - } - try autoreleasepool { + Internals.assert( + self.isRunningInAllowedQueue(), + "Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue." + ) - if let object = existingObjectsByID[objectID] - ?? self.context.insertedObjects - .compactMap({ O.cs_matches(object: $0) ? O.cs_fromRaw(object: $0) : nil }) - .first(where: { $0.uniqueIDValue == objectID }) { - - guard entityType.shouldUpdate(from: source, in: self) else { - - return - } - try object.update(from: source, in: self) - result.append(object) - } - else if entityType.shouldInsert(from: source, in: self) { - - let object = self.create(into) - object.uniqueIDValue = objectID - try object.didInsert(from: source, in: self) - result.append(object) - } - processedObjectIDs.insert(objectID) + return try Internals.autoreleasepool { + + let entityType = into.entityClass + var importSourceByID = Dictionary() + let sortedIDs = try Internals.autoreleasepool { + + return try sourceArray.compactMap { (source) -> O.UniqueIDType? in + + guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else { + + return nil } + importSourceByID[uniqueIDValue] = source // effectively replaces duplicate with the latest + return uniqueIDValue } - return result } + + importSourceByID = try Internals.autoreleasepool { try preProcess(importSourceByID) } + + var existingObjectsByID = Dictionary() + try self + .fetchAll(From(entityType), Where(entityType.uniqueIDKeyPath, isMemberOf: sortedIDs)) + .forEach { existingObjectsByID[$0.uniqueIDValue] = $0 } + + var processedObjectIDs = Set() + var result = [O]() + + for objectID in sortedIDs where !processedObjectIDs.contains(objectID) { + + guard let source = importSourceByID[objectID] else { + + continue + } + try Internals.autoreleasepool { + + if let object = existingObjectsByID[objectID] + ?? self.context.insertedObjects + .compactMap({ O.cs_matches(object: $0) ? O.cs_fromRaw(object: $0) : nil }) + .first(where: { $0.uniqueIDValue == objectID }) { + + guard entityType.shouldUpdate(from: source, in: self) else { + + return + } + try object.update(from: source, in: self) + result.append(object) + } + else if entityType.shouldInsert(from: source, in: self) { + + let object = self.create(into) + object.uniqueIDValue = objectID + try object.didInsert(from: source, in: self) + result.append(object) + } + processedObjectIDs.insert(objectID) + } + } + return result + } } } diff --git a/Sources/BaseDataTransaction+Querying.swift b/Sources/BaseDataTransaction+Querying.swift index 7345acf..c74eaa0 100644 --- a/Sources/BaseDataTransaction+Querying.swift +++ b/Sources/BaseDataTransaction+Querying.swift @@ -39,8 +39,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s deleted */ @discardableResult - public func deleteAll(_ from: From, _ deleteClauses: DeleteClause...) throws -> Int { - + public func deleteAll( + _ from: From, + _ deleteClauses: DeleteClause... + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to delete from a \(Internals.typeName(self)) outside its designated queue." @@ -56,8 +59,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s deleted */ @discardableResult - public func deleteAll(_ from: From, _ deleteClauses: [DeleteClause]) throws -> Int { - + public func deleteAll( + _ from: From, + _ deleteClauses: [DeleteClause] + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to delete from a \(Internals.typeName(self)) outside its designated queue." @@ -74,14 +80,18 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s deleted */ @discardableResult - public func deleteAll(_ clauseChain: B) throws -> Int { - + public func deleteAll( + _ clauseChain: B + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to delete from a \(Internals.typeName(self)) outside its designated queue." ) - - return try self.context.deleteAll(clauseChain.from, clauseChain.fetchClauses) + return try self.context.deleteAll( + clauseChain.from, + clauseChain.fetchClauses + ) } @@ -93,8 +103,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - parameter object: a reference to the object created/fetched outside the transaction - returns: the `DynamicObject` instance if the object exists in the transaction, or `nil` if not found. */ - public func fetchExisting(_ object: O) -> O? { - + public func fetchExisting( + _ object: O + ) -> O? { + return self.context.fetchExisting(object) } @@ -104,8 +116,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - parameter objectID: the `NSManagedObjectID` for the object - returns: the `DynamicObject` instance if the object exists in the transaction, or `nil` if not found. */ - public func fetchExisting(_ objectID: NSManagedObjectID) -> O? { - + public func fetchExisting( + _ objectID: NSManagedObjectID + ) -> O? { + return self.context.fetchExisting(objectID) } @@ -115,8 +129,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - parameter objects: an array of `DynamicObject`s created/fetched outside the transaction - returns: the `DynamicObject` array for objects that exists in the transaction */ - public func fetchExisting(_ objects: S) -> [O] where S.Iterator.Element == O { - + public func fetchExisting( + _ objects: S + ) -> [O] where S.Iterator.Element == O { + return self.context.fetchExisting(objects) } @@ -126,8 +142,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - parameter objectIDs: the `NSManagedObjectID` array for the objects - returns: the `DynamicObject` array for objects that exists in the transaction */ - public func fetchExisting(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID { - + public func fetchExisting( + _ objectIDs: S + ) -> [O] where S.Iterator.Element == NSManagedObjectID { + return self.context.fetchExisting(objectIDs) } @@ -139,8 +157,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ from: From, _ fetchClauses: FetchClause...) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> O? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -156,8 +177,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ from: From, _ fetchClauses: [FetchClause]) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> O? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -178,8 +202,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ clauseChain: B) throws -> B.ObjectType? { - + public func fetchOne( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ObjectType? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -195,8 +221,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ from: From, _ fetchClauses: FetchClause...) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [O] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -212,8 +241,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ from: From, _ fetchClauses: [FetchClause]) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [O] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -234,8 +266,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ clauseChain: B) throws -> [B.ObjectType] { - + public func fetchAll( + _ clauseChain: B + ) throws(CoreStoreError) -> [B.ObjectType] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -251,8 +285,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ from: From, _ fetchClauses: FetchClause...) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -268,8 +305,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ from: From, _ fetchClauses: [FetchClause]) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -290,8 +330,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ clauseChain: B) throws -> Int { - + public func fetchCount( + _ clauseChain: B + ) throws(CoreStoreError) -> Int { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -307,8 +349,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ from: From, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -324,8 +369,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ from: From, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -346,8 +394,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ clauseChain: B) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ clauseChain: B + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -363,8 +413,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ from: From, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -380,8 +433,11 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ from: From, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -402,8 +458,10 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ clauseChain: B) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ clauseChain: B + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to fetch from a \(Internals.typeName(self)) outside its designated queue." @@ -425,8 +483,12 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> U? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." @@ -445,8 +507,12 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> U? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." @@ -469,13 +535,19 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query as specified by the `QueryChainableBuilderType`, or `nil` if no match was found. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ clauseChain: B) throws -> B.ResultType? where B.ResultType: QueryableAttributeType { - + public func queryValue( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ResultType? where B.ResultType: QueryableAttributeType { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." ) - return try self.context.queryValue(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + return try self.context.queryValue( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } /** @@ -489,8 +561,12 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> [[String: Any]] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." @@ -509,8 +585,12 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> [[String: Any]] { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." @@ -542,13 +622,19 @@ extension BaseDataTransaction: FetchableSource, QueryableSource { - returns: the result of the the query as specified by the `QueryChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ clauseChain: B) throws -> [[String: Any]] where B.ResultType == NSDictionary { - + public func queryAttributes( + _ clauseChain: B + ) throws(CoreStoreError) -> [[String: Any]] where B.ResultType == NSDictionary { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to query from a \(Internals.typeName(self)) outside its designated queue." ) - return try self.context.queryAttributes(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + return try self.context.queryAttributes( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } diff --git a/Sources/BaseDataTransaction.swift b/Sources/BaseDataTransaction.swift index c89999c..e09bd9b 100644 --- a/Sources/BaseDataTransaction.swift +++ b/Sources/BaseDataTransaction.swift @@ -121,8 +121,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter object: the `NSManagedObject` or `CoreStoreObject` type to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public func edit(_ object: O?) -> O? { - + public func edit( + _ object: O? + ) -> O? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to update an entity of type \(Internals.typeName(object)) outside its designated queue." @@ -141,8 +143,11 @@ public /*abstract*/ class BaseDataTransaction { - parameter objectID: the `NSManagedObjectID` for the object to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public func edit(_ into: Into, _ objectID: NSManagedObjectID) -> O? { - + public func edit( + _ into: Into, + _ objectID: NSManagedObjectID + ) -> O? { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to update an entity of type \(Internals.typeName(into.entityClass)) outside its designated queue." @@ -160,7 +165,9 @@ public /*abstract*/ class BaseDataTransaction { - parameter objectIDs: the `NSManagedObjectID`s of the objects to delete */ - public func delete(objectIDs: S) where S.Iterator.Element: NSManagedObjectID { + public func delete( + objectIDs: S + ) where S.Iterator.Element: NSManagedObjectID { Internals.assert( self.isRunningInAllowedQueue(), @@ -179,8 +186,11 @@ public /*abstract*/ class BaseDataTransaction { - parameter object: the `ObjectRepresentation` representing an `NSManagedObject` or `CoreStoreObject` to be deleted - parameter objects: other `ObjectRepresentation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public func delete(_ object: O?, _ objects: O?...) { - + public func delete( + _ object: O?, + _ objects: O?... + ) { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to delete an entity outside its designated queue." @@ -193,8 +203,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter objects: the `ObjectRepresenation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public func delete(_ objects: S) where S.Iterator.Element: ObjectRepresentation { - + public func delete( + _ objects: S + ) where S.Iterator.Element: ObjectRepresentation { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to delete entities outside their designated queue." @@ -227,7 +239,9 @@ public /*abstract*/ class BaseDataTransaction { - parameter object: the `DynamicObject` instance - returns: `true` if the object has any property values changed. */ - public func objectHasPersistentChangedValues(_ object: O) -> Bool { + public func objectHasPersistentChangedValues( + _ object: O + ) -> Bool { Internals.assert( self.isRunningInAllowedQueue(), @@ -246,8 +260,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `DynamicObject`s of the specified type that were inserted to the transaction. */ - public func insertedObjects(_ entity: O.Type) -> Set { - + public func insertedObjects( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access inserted objects from a \(Internals.typeName(self)) outside its designated queue." @@ -283,8 +299,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction. */ - public func insertedObjectIDs(_ entity: O.Type) -> Set { - + public func insertedObjectIDs( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access inserted object IDs from a \(Internals.typeName(self)) outside its designated queue." @@ -302,8 +320,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `DynamicObject`s of the specified type that were updated in the transaction. */ - public func updatedObjects(_ entity: O.Type) -> Set { - + public func updatedObjects( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access updated objects from a \(Internals.typeName(self)) outside its designated queue." @@ -339,8 +359,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction. */ - public func updatedObjectIDs(_ entity: O.Type) -> Set { - + public func updatedObjectIDs( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access updated object IDs from a \(Internals.typeName(self)) outside its designated queue." @@ -358,8 +380,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `DynamicObject`s of the specified type that were deleted from the transaction. */ - public func deletedObjects(_ entity: O.Type) -> Set { - + public func deletedObjects( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access deleted objects from a \(Internals.typeName(self)) outside its designated queue." @@ -396,8 +420,10 @@ public /*abstract*/ class BaseDataTransaction { - parameter entity: the `DynamicObject` subclass to filter - returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. */ - public func deletedObjectIDs(_ entity: O.Type) -> Set { - + public func deletedObjectIDs( + _ entity: O.Type + ) -> Set { + Internals.assert( self.isRunningInAllowedQueue(), "Attempted to access deleted object IDs from a \(Internals.typeName(self)) outside its designated queue." diff --git a/Sources/CoreStore+CustomDebugStringConvertible.swift b/Sources/CoreStore+CustomDebugStringConvertible.swift index 9fc00fc..e362e26 100644 --- a/Sources/CoreStore+CustomDebugStringConvertible.swift +++ b/Sources/CoreStore+CustomDebugStringConvertible.swift @@ -1073,13 +1073,21 @@ private func formattedDebugDescription(_ any: Any) -> String { return string } -private func createFormattedString(_ firstLine: String, _ lastLine: String, _ info: (key: String, value: Any)...) -> String { - +private func createFormattedString( + _ firstLine: String, + _ lastLine: String, + _ info: (key: String, value: Any)... +) -> String { + return createFormattedString(firstLine, lastLine, info) } -private func createFormattedString(_ firstLine: String, _ lastLine: String, _ info: [(key: String, value: Any)]) -> String { - +private func createFormattedString( + _ firstLine: String, + _ lastLine: String, + _ info: [(key: String, value: Any)] +) -> String { + var string = firstLine for (key, value) in info { @@ -1102,8 +1110,11 @@ extension String { self = self.replacingOccurrences(of: "\n", with: "\n\(String.indention(level))") } - fileprivate mutating func appendDumpInfo(_ key: String, _ value: Any) { - + fileprivate mutating func appendDumpInfo( + _ key: String, + _ value: Any + ) { + self.append("\n.\(key) = \(formattedValue(value));") } } @@ -1189,8 +1200,9 @@ extension NSAttributeDescription: CoreStoreDebugStringConvertible { } } +extension NSAttributeType: @retroactive CustomDebugStringConvertible {} extension NSAttributeType: CoreStoreDebugStringConvertible { - + public var debugDescription: String { return formattedDebugDescription(self) @@ -1235,6 +1247,7 @@ extension Bundle: CoreStoreDebugStringConvertible { } } +extension NSDeleteRule: @retroactive CustomDebugStringConvertible {} extension NSDeleteRule: CoreStoreDebugStringConvertible { public var debugDescription: String { @@ -1399,6 +1412,7 @@ extension Optional: CoreStoreDebugStringConvertible { } } +extension Result: @retroactive CustomDebugStringConvertible {} extension Result: CoreStoreDebugStringConvertible { public var debugDescription: String { @@ -1425,6 +1439,7 @@ extension Result: CoreStoreDebugStringConvertible { } } +extension Selector: @retroactive CustomDebugStringConvertible {} extension Selector: CoreStoreDebugStringConvertible { public var debugDescription: String { diff --git a/Sources/CoreStore+Logging.swift b/Sources/CoreStore+Logging.swift index d984871..242cfcc 100644 --- a/Sources/CoreStore+Logging.swift +++ b/Sources/CoreStore+Logging.swift @@ -33,7 +33,13 @@ extension Internals { // MARK: Internal @inline(__always) - internal static func log(_ level: LogLevel, message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) { + internal static func log( + _ level: LogLevel, + message: String, + fileName: StaticString = #file, + lineNumber: Int = #line, + functionName: StaticString = #function + ) { CoreStoreDefaults.logger.log( level: level, @@ -45,7 +51,13 @@ extension Internals { } @inline(__always) - internal static func log(_ error: CoreStoreError, _ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) { + internal static func log( + _ error: CoreStoreError, + _ message: String, + fileName: StaticString = #file, + lineNumber: Int = #line, + functionName: StaticString = #function + ) { CoreStoreDefaults.logger.log( error: error, @@ -57,7 +69,13 @@ extension Internals { } @inline(__always) - internal static func assert( _ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) { + internal static func assert( + _ condition: @autoclosure () -> Bool, + _ message: @autoclosure () -> String, + fileName: StaticString = #file, + lineNumber: Int = #line, + functionName: StaticString = #function + ) { CoreStoreDefaults.logger.assert( condition(), @@ -69,7 +87,12 @@ extension Internals { } @inline(__always) - internal static func abort(_ message: String, fileName: StaticString = #file, lineNumber: Int = #line, functionName: StaticString = #function) -> Never { + internal static func abort( + _ message: String, + fileName: StaticString = #file, + lineNumber: Int = #line, + functionName: StaticString = #function + ) -> Never { CoreStoreDefaults.logger.abort( message, diff --git a/Sources/CoreStoreLogger.swift b/Sources/CoreStoreLogger.swift index fc28fe9..31e5946 100644 --- a/Sources/CoreStoreLogger.swift +++ b/Sources/CoreStoreLogger.swift @@ -56,8 +56,14 @@ public protocol CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - func log(level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) - + func log( + level: LogLevel, + message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) + /** Handles errors sent by the `CoreStore` framework. @@ -67,8 +73,14 @@ public protocol CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - func log(error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) - + func log( + error: CoreStoreError, + message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) + /** Handles assertions made throughout the `CoreStore` framework. @@ -78,8 +90,14 @@ public protocol CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - func assert(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) - + func assert( + _ condition: @autoclosure () -> Bool, + message: @autoclosure () -> String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) + /** Handles fatal errors made throughout the `CoreStore` framework. The app wil terminate after this method is called. - Important: Implementers may guarantee that the function doesn't return, either by calling another `Never` function such as `fatalError()` or `abort()`, or by raising an exception. If the implementation does not terminate the app, CoreStore will call an internal `fatalError()` to do so. @@ -89,13 +107,23 @@ public protocol CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) + func abort( + _ message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) } extension CoreStoreLogger { - public func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { - + public func abort( + _ message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) { + Swift.fatalError(message, file: fileName, line: UInt(lineNumber)) } } diff --git a/Sources/CoreStoreObject+Observing.swift b/Sources/CoreStoreObject+Observing.swift index ae46f59..46fd5b2 100644 --- a/Sources/CoreStoreObject+Observing.swift +++ b/Sources/CoreStoreObject+Observing.swift @@ -27,9 +27,17 @@ import Foundation import CoreData +// MARK: - DynamicObject where Self: CoreStoreObject + extension DynamicObject where Self: CoreStoreObject { - public func observe(_ keyPath: KeyPath.Stored>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (Self, CoreStoreObjectValueDiff) -> Void) -> CoreStoreObjectKeyValueObservation { + // MARK: Public + + public func observe( + _ keyPath: KeyPath.Stored>, + options: NSKeyValueObservingOptions = [], + changeHandler: @escaping (Self, CoreStoreObjectValueDiff) -> Void + ) -> CoreStoreObjectKeyValueObservation { let result = _CoreStoreObjectKeyValueObservation( object: self.rawObject!, @@ -186,7 +194,12 @@ public final class CoreStoreObjectObjectDiff { // MARK: FilePrivate - fileprivate init(kind: NSKeyValueChange, newNativeValue: CoreStoreManagedObject?, oldNativeValue: CoreStoreManagedObject?, isPrior: Bool) { + fileprivate init( + kind: NSKeyValueChange, + newNativeValue: CoreStoreManagedObject?, + oldNativeValue: CoreStoreManagedObject?, + isPrior: Bool + ) { self.kind = kind self.newNativeValue = newNativeValue @@ -232,7 +245,12 @@ public final class CoreStoreObjectUnorderedDiff { // MARK: FilePrivate - fileprivate init(kind: NSKeyValueChange, newNativeValue: NSOrderedSet?, oldNativeValue: NSOrderedSet?, isPrior: Bool) { + fileprivate init( + kind: NSKeyValueChange, + newNativeValue: NSOrderedSet?, + oldNativeValue: NSOrderedSet?, + isPrior: Bool + ) { self.kind = kind self.newNativeValue = newNativeValue ?? [] @@ -283,7 +301,13 @@ public final class CoreStoreObjectOrderedDiff { // MARK: FilePrivate - fileprivate init(kind: NSKeyValueChange, newNativeValue: NSArray?, oldNativeValue: NSArray?, indexes: IndexSet, isPrior: Bool) { + fileprivate init( + kind: NSKeyValueChange, + newNativeValue: NSArray?, + oldNativeValue: NSArray?, + indexes: IndexSet, + isPrior: Bool + ) { self.kind = kind self.newNativeValue = newNativeValue ?? [] @@ -362,7 +386,18 @@ fileprivate final class _CoreStoreObjectKeyValueObservation: NSObject, CoreStore // MARK: FilePrivate @nonobjc - fileprivate init(object: CoreStoreManagedObject, keyPath: KeyPathString, callback: @escaping (_ object: CoreStoreManagedObject, _ kind: NSKeyValueChange, _ newValue: Any?, _ oldValue: Any?, _ indexes: IndexSet?, _ isPrior: Bool) -> Void) { + fileprivate init( + object: CoreStoreManagedObject, + keyPath: KeyPathString, + callback: @escaping ( + _ object: CoreStoreManagedObject, + _ kind: NSKeyValueChange, + _ newValue: Any?, + _ oldValue: Any?, + _ indexes: IndexSet?, + _ isPrior: Bool + ) -> Void + ) { let _ = _CoreStoreObjectKeyValueObservation.swizzler self.keyPath = keyPath @@ -373,12 +408,19 @@ fileprivate final class _CoreStoreObjectKeyValueObservation: NSObject, CoreStore @nonobjc fileprivate func start(_ options: NSKeyValueObservingOptions) { - self.object?.addObserver(self, forKeyPath: self.keyPath, options: options, context: nil) + self.object? + .addObserver( + self, + forKeyPath: self.keyPath, + options: options, + context: nil + ) } deinit { - self.object?.removeObserver(self, forKeyPath: self.keyPath, context: nil) + self.object? + .removeObserver(self, forKeyPath: self.keyPath, context: nil) } @@ -387,7 +429,8 @@ fileprivate final class _CoreStoreObjectKeyValueObservation: NSObject, CoreStore @nonobjc public func invalidate() { - self.object?.removeObserver(self, forKeyPath: self.keyPath, context: nil) + self.object? + .removeObserver(self, forKeyPath: self.keyPath, context: nil) self.object = nil } @@ -401,11 +444,17 @@ fileprivate final class _CoreStoreObjectKeyValueObservation: NSObject, CoreStore let bridgeClass: AnyClass = _CoreStoreObjectKeyValueObservation.self let rootObserveImpl = class_getInstanceMethod( bridgeClass, - #selector(_CoreStoreObjectKeyValueObservation.observeValue(forKeyPath:of:change:context:)) + #selector( + _CoreStoreObjectKeyValueObservation + .observeValue(forKeyPath:of:change:context:) + ) )! let swapObserveImpl = class_getInstanceMethod( bridgeClass, - #selector(_CoreStoreObjectKeyValueObservation._cs_swizzle_me_observeValue(forKeyPath:of:change:context:)) + #selector( + _CoreStoreObjectKeyValueObservation + ._cs_swizzle_me_observeValue(forKeyPath:of:change:context:) + ) )! method_exchangeImplementations(rootObserveImpl, swapObserveImpl) return nil @@ -415,21 +464,33 @@ fileprivate final class _CoreStoreObjectKeyValueObservation: NSObject, CoreStore private weak var object: CoreStoreManagedObject? @nonobjc - private let callback: (_ object: CoreStoreManagedObject, _ kind: NSKeyValueChange, _ newValue: Any?, _ oldValue: Any?, _ indexes: IndexSet?, _ isPrior: Bool) -> Void + private let callback: ( + _ object: CoreStoreManagedObject, + _ kind: NSKeyValueChange, + _ newValue: Any?, + _ oldValue: Any?, + _ indexes: IndexSet?, + _ isPrior: Bool + ) -> Void @nonobjc private let keyPath: KeyPathString @objc - private dynamic func _cs_swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString: Any]?, context: UnsafeMutableRawPointer?) { + private dynamic func _cs_swizzle_me_observeValue( + forKeyPath keyPath: String?, + of object: Any?, + change: [NSString: Any]?, + context: UnsafeMutableRawPointer? + ) { guard let object = object as? CoreStoreManagedObject, object == self.object, let change = change - else { + else { - return + return } let rawKind: UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt self.callback( diff --git a/Sources/CoreStoreObject+Querying.swift b/Sources/CoreStoreObject+Querying.swift index 71063e9..55997ec 100644 --- a/Sources/CoreStoreObject+Querying.swift +++ b/Sources/CoreStoreObject+Querying.swift @@ -36,9 +36,15 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.nickname == "John" })) ``` */ - public static func == (_ attribute: Self, _ value: V) -> Where { + public static func == ( + _ attribute: Self, + _ value: V + ) -> Where { - return Where(attribute.keyPath, isEqualTo: value) + return Where( + attribute.keyPath, + isEqualTo: value + ) } /** @@ -47,9 +53,15 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.nickname != "John" })) ``` */ - public static func != (_ attribute: Self, _ value: V) -> Where { + public static func != ( + _ attribute: Self, + _ value: V + ) -> Where { - return !Where(attribute.keyPath, isEqualTo: value) + return !Where( + attribute.keyPath, + isEqualTo: value + ) } /** @@ -58,9 +70,16 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.age < 20 })) ``` */ - public static func < (_ attribute: Self, _ value: V) -> Where { + public static func < ( + _ attribute: Self, + _ value: V + ) -> Where { - return Where("%K < %@", attribute.keyPath, value.cs_toFieldStoredNativeType() as Any) + return Where( + "%K < %@", + attribute.keyPath, + value.cs_toFieldStoredNativeType() as Any + ) } /** @@ -69,9 +88,16 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.age > 20 })) ``` */ - public static func > (_ attribute: Self, _ value: V) -> Where { + public static func > ( + _ attribute: Self, + _ value: V + ) -> Where { - return Where("%K > %@", attribute.keyPath, value.cs_toFieldStoredNativeType() as Any) + return Where( + "%K > %@", + attribute.keyPath, + value.cs_toFieldStoredNativeType() as Any + ) } /** @@ -80,9 +106,16 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.age <= 20 })) ``` */ - public static func <= (_ attribute: Self, _ value: V) -> Where { + public static func <= ( + _ attribute: Self, + _ value: V + ) -> Where { - return Where("%K <= %@", attribute.keyPath, value.cs_toFieldStoredNativeType() as Any) + return Where( + "%K <= %@", + attribute.keyPath, + value.cs_toFieldStoredNativeType() as Any + ) } /** @@ -91,9 +124,16 @@ extension FieldContainer.Stored { let person = dataStack.fetchOne(From().where({ $0.age >= 20 })) ``` */ - public static func >= (_ attribute: Self, _ value: V) -> Where { + public static func >= ( + _ attribute: Self, + _ value: V + ) -> Where { - return Where("%K >= %@", attribute.keyPath, value.cs_toFieldStoredNativeType() as Any) + return Where( + "%K >= %@", + attribute.keyPath, + value.cs_toFieldStoredNativeType() as Any + ) } /** @@ -102,9 +142,15 @@ extension FieldContainer.Stored { let dog = dataStack.fetchOne(From().where({ ["Pluto", "Snoopy", "Scooby"] ~= $0.nickname })) ``` */ - public static func ~= (_ sequence: S, _ attribute: Self) -> Where where S.Iterator.Element == V { + public static func ~= ( + _ sequence: S, + _ attribute: Self + ) -> Where where S.Iterator.Element == V { - return Where(attribute.keyPath, isMemberOf: sequence) + return Where( + attribute.keyPath, + isMemberOf: sequence + ) } } diff --git a/Sources/CoreStoreObject.swift b/Sources/CoreStoreObject.swift index 001a646..8d84b25 100644 --- a/Sources/CoreStoreObject.swift +++ b/Sources/CoreStoreObject.swift @@ -129,7 +129,10 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable { internal class func metaProperties(includeSuperclasses: Bool) -> [PropertyProtocol] { - func keyPaths(_ allKeyPaths: inout [PropertyProtocol], for dynamicType: CoreStoreObject.Type) { + func keyPaths( + _ allKeyPaths: inout [PropertyProtocol], + for dynamicType: CoreStoreObject.Type + ) { allKeyPaths.append(contentsOf: dynamicType.meta.propertyProtocolsByName()) guard @@ -151,7 +154,10 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable { // MARK: Private - private func containsLegacyAttributes(mirror: Mirror, object: CoreStoreObject) -> Bool { + private func containsLegacyAttributes( + mirror: Mirror, + object: CoreStoreObject + ) -> Bool { if let superclassMirror = mirror.superclassMirror, self.containsLegacyAttributes(mirror: superclassMirror, object: object) { @@ -175,8 +181,11 @@ open /*abstract*/ class CoreStoreObject: DynamicObject, Hashable { return false } - private func registerReceiver(mirror: Mirror, object: CoreStoreObject) { - + private func registerReceiver( + mirror: Mirror, + object: CoreStoreObject + ) { + if let superclassMirror = mirror.superclassMirror { self.registerReceiver( diff --git a/Sources/CoreStoreSchema.swift b/Sources/CoreStoreSchema.swift index 2e842f9..7f5afb9 100644 --- a/Sources/CoreStoreSchema.swift +++ b/Sources/CoreStoreSchema.swift @@ -94,8 +94,12 @@ public final class CoreStoreSchema: DynamicSchema { - parameter entities: an array of `Entity` pertaining to all `CoreStoreObject` subclasses to be added to the schema version. - parameter versionLock: an optional list of `VersionLock` hashes for each entity name in the `entities` array. If any `DynamicEntity` doesn't match its version lock hash, an assertion will be raised. */ - public convenience init(modelVersion: ModelVersion, entities: [DynamicEntity], versionLock: VersionLock? = nil) { - + public convenience init( + modelVersion: ModelVersion, + entities: [DynamicEntity], + versionLock: VersionLock? = nil + ) { + var entityConfigurations: [DynamicEntity: Set] = [:] for entity in entities { @@ -138,8 +142,12 @@ public final class CoreStoreSchema: DynamicSchema { - parameter entityConfigurations: a dictionary with `Entity` pertaining to all `CoreStoreObject` subclasses and the corresponding list of "Configurations" they should be added to. To add an entity only to the default configuration, assign an empty set to its configurations list. Note that regardless of the set configurations, all entities will be added to the default configuration. - parameter versionLock: an optional list of `VersionLock` hashes for each entity name in the `entities` array. If any `DynamicEntity` doesn't match its version lock hash, an assertion will be raised. */ - public required init(modelVersion: ModelVersion, entityConfigurations: [DynamicEntity: Set], versionLock: VersionLock? = nil) { - + public required init( + modelVersion: ModelVersion, + entityConfigurations: [DynamicEntity: Set], + versionLock: VersionLock? = nil + ) { + var actualEntitiesByConfiguration: [String: Set] = [:] for (entity, configurations) in entityConfigurations { @@ -305,7 +313,10 @@ public final class CoreStoreSchema: DynamicSchema { ) } - private static func firstPassCreateEntityDescription(from entity: DynamicEntity, in modelVersion: ModelVersion) -> ( + private static func firstPassCreateEntityDescription( + from entity: DynamicEntity, + in modelVersion: ModelVersion + ) -> ( entity: NSEntityDescription, customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter], customInitializerByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer], @@ -323,8 +334,11 @@ public final class CoreStoreSchema: DynamicSchema { var customInitialValuesByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer] = [:] var customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter] = [:] var fieldCoders: [KeyPathString: Internals.AnyFieldCoder] = [:] - func createProperties(for type: CoreStoreObject.Type) -> [NSPropertyDescription] { - + + func createProperties( + for type: CoreStoreObject.Type + ) -> [NSPropertyDescription] { + var propertyDescriptions: [NSPropertyDescription] = [] for property in type.metaProperties(includeSuperclasses: false) { @@ -425,15 +439,20 @@ public final class CoreStoreSchema: DynamicSchema { ) } - private static func secondPassConnectRelationshipAttributes(for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription]) { - + private static func secondPassConnectRelationshipAttributes( + for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription] + ) { + var relationshipsByNameByEntity: [DynamicEntity: [String: NSRelationshipDescription]] = [:] for (entity, entityDescription) in entityDescriptionsByEntity { relationshipsByNameByEntity[entity] = entityDescription.relationshipsByName } - func findEntity(for type: CoreStoreObject.Type) -> DynamicEntity { - + + func findEntity( + for type: CoreStoreObject.Type + ) -> DynamicEntity { + var matchedEntities: Set = [] for (entity, _) in entityDescriptionsByEntity where entity.type == type { @@ -457,8 +476,11 @@ public final class CoreStoreSchema: DynamicSchema { } } - func findInverseRelationshipMatching(destinationEntity: DynamicEntity, destinationKeyPath: String) -> NSRelationshipDescription { - + func findInverseRelationshipMatching( + destinationEntity: DynamicEntity, + destinationKeyPath: String + ) -> NSRelationshipDescription { + for case (destinationKeyPath, let relationshipDescription) in relationshipsByNameByEntity[destinationEntity]! { return relationshipDescription @@ -537,10 +559,15 @@ public final class CoreStoreSchema: DynamicSchema { } } - private static func thirdPassConnectInheritanceTreeAndIndexes(for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription]) { - - func connectBaseEntity(mirror: Mirror, entityDescription: NSEntityDescription) { - + private static func thirdPassConnectInheritanceTreeAndIndexes( + for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription] + ) { + + func connectBaseEntity( + mirror: Mirror, + entityDescription: NSEntityDescription + ) { + guard let superclassMirror = mirror.superclassMirror, let superType = superclassMirror.subjectType as? CoreStoreObject.Type, superType != CoreStoreObject.self else { diff --git a/Sources/CustomSchemaMappingProvider.swift b/Sources/CustomSchemaMappingProvider.swift index d8b4525..d75f8db 100644 --- a/Sources/CustomSchemaMappingProvider.swift +++ b/Sources/CustomSchemaMappingProvider.swift @@ -51,8 +51,12 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { - parameter destinationVersion: the destination model version for the mapping - parameter entityMappings: a list of `CustomMapping`s. Mappings of entities with no `CustomMapping` provided will be automatically calculated if possible. Any conflicts or ambiguity will raise an assertion. */ - public required init(from sourceVersion: ModelVersion, to destinationVersion: ModelVersion, entityMappings: Set = []) { - + public required init( + from sourceVersion: ModelVersion, + to destinationVersion: ModelVersion, + entityMappings: Set = [] + ) { + Internals.assert( Internals.with { @@ -101,13 +105,19 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { - parameter sourceObject: a proxy object representing the source entity. The properties can be accessed via keyPath. - parameter createDestinationObject: the closure to create the object for the destination entity. The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight). The object is created lazily and executing the closure multiple times will return the same instance. The destination object's properties can be accessed and updated via keyPath. */ - public typealias Transformer = (_ sourceObject: UnsafeSourceObject, _ createDestinationObject: () -> UnsafeDestinationObject) throws -> Void - + public typealias Transformer = ( + _ sourceObject: UnsafeSourceObject, + _ createDestinationObject: () -> UnsafeDestinationObject + ) throws(any Swift.Error) -> Void + /** The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight). */ - public static func inferredTransformation(_ sourceObject: UnsafeSourceObject, _ createDestinationObject: () -> UnsafeDestinationObject) throws -> Void { - + public static func inferredTransformation( + _ sourceObject: UnsafeSourceObject, + _ createDestinationObject: () -> UnsafeDestinationObject + ) throws(any Swift.Error) { + let destinationObject = createDestinationObject() destinationObject.enumerateAttributes { (attribute, sourceAttribute) in @@ -343,8 +353,15 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { // MARK: SchemaMappingProvider - public func cs_createMappingModel(from sourceSchema: DynamicSchema, to destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) { - + public func cs_createMappingModel( + from sourceSchema: DynamicSchema, + to destinationSchema: DynamicSchema, + storage: LocalStorage + ) throws(CoreStoreError) -> ( + mappingModel: NSMappingModel, + migrationType: MigrationType + ) { + let sourceModel = sourceSchema.rawModel() let destinationModel = destinationSchema.rawModel() @@ -535,8 +552,12 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { // MARK: NSEntityMigrationPolicy - override func createDestinationInstances(forSource sInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { - + override func createDestinationInstances( + forSource sInstance: NSManagedObject, + in mapping: NSEntityMapping, + manager: NSMigrationManager + ) throws(any Swift.Error) { + let userInfo = mapping.userInfo! let transformer = userInfo[CustomEntityMigrationPolicy.UserInfoKey.transformer]! as! CustomMapping.Transformer let sourceAttributesByDestinationKey = userInfo[CustomEntityMigrationPolicy.UserInfoKey.sourceAttributesByDestinationKey] as! [KeyPathString: NSAttributeDescription] @@ -563,8 +584,12 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { } } - override func createRelationships(forDestination dInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { - + override func createRelationships( + forDestination dInstance: NSManagedObject, + in mapping: NSEntityMapping, + manager: NSMigrationManager + ) throws(any Swift.Error) { + try super.createRelationships(forDestination: dInstance, in: mapping, manager: manager) } @@ -583,8 +608,16 @@ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { private let entityMappings: Set - private func resolveEntityMappings(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel) -> (delete: Set, insert: Set, copy: Set, transform: Set) { - + private func resolveEntityMappings( + sourceModel: NSManagedObjectModel, + destinationModel: NSManagedObjectModel + ) -> ( + delete: Set, + insert: Set, + copy: Set, + transform: Set + ) { + var deleteMappings: Set = [] var insertMappings: Set = [] var copyMappings: Set = [] diff --git a/Sources/DataStack+Concurrency.swift b/Sources/DataStack+Concurrency.swift index 84b494b..4523712 100644 --- a/Sources/DataStack+Concurrency.swift +++ b/Sources/DataStack+Concurrency.swift @@ -85,13 +85,16 @@ extension DataStack.AsyncNamespace { */ public func addStorage( _ storage: T - ) async throws -> T { + ) async throws(any Swift.Error) -> T { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.addStorage( storage, - completion: continuation.resume(with:) + completion: { + + continuation.resume(with: $0) + } ) } } @@ -115,7 +118,7 @@ extension DataStack.AsyncNamespace { */ public func addStorage( _ storage: T - ) -> AsyncThrowingStream, Swift.Error> { + ) -> AsyncThrowingStream, any Swift.Error> { return .init( bufferingPolicy: .unbounded, @@ -178,9 +181,9 @@ extension DataStack.AsyncNamespace { public func importObject( _ into: Into, source: O.ImportSource - ) async throws -> O? { + ) async throws(any Swift.Error) -> O? { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.perform( asynchronous: { (transaction) -> O? in @@ -217,9 +220,9 @@ extension DataStack.AsyncNamespace { public func importObject( _ object: O, source: O.ImportSource - ) async throws -> O? { + ) async throws(any Swift.Error) -> O? { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.perform( asynchronous: { (transaction) -> O? in @@ -261,9 +264,9 @@ extension DataStack.AsyncNamespace { public func importUniqueObject( _ into: Into, source: O.ImportSource - ) async throws -> O? { + ) async throws(any Swift.Error) -> O? { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.perform( asynchronous: { (transaction) -> O? in @@ -306,11 +309,13 @@ extension DataStack.AsyncNamespace { public func importUniqueObjects( _ into: Into, sourceArray: S, - preProcess: @escaping @Sendable (_ mapping: [O.UniqueIDType: O.ImportSource]) throws -> [O.UniqueIDType: O.ImportSource] = { $0 } - ) async throws -> [O] + preProcess: @escaping @Sendable ( + _ mapping: [O.UniqueIDType: O.ImportSource] + ) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 } + ) async throws(any Swift.Error) -> [O] where S.Iterator.Element == O.ImportSource { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.perform( asynchronous: { (transaction) -> [O] in @@ -353,14 +358,17 @@ extension DataStack.AsyncNamespace { - throws: A `CoreStoreError` value indicating the failure reason */ public func perform( - _ asynchronous: @escaping @Sendable (AsynchronousDataTransaction) throws -> Output - ) async throws -> Output { + _ asynchronous: @escaping @Sendable (AsynchronousDataTransaction) throws(any Swift.Error) -> Output + ) async throws(any Swift.Error) -> Output { - return try await withCheckedThrowingContinuation { continuation in + return try await Internals.withCheckedThrowingContinuation { continuation in self.base.perform( asynchronous: asynchronous, - completion: continuation.resume(with:) + completion: { + + continuation.resume(with: $0) + } ) } } diff --git a/Sources/DataStack+DataSources.swift b/Sources/DataStack+DataSources.swift index 3c82eb2..617ef19 100644 --- a/Sources/DataStack+DataSources.swift +++ b/Sources/DataStack+DataSources.swift @@ -39,7 +39,9 @@ extension DataStack { - parameter object: the `DynamicObject` to observe changes from - returns: an `ObjectPublisher` that broadcasts changes to `object` */ - public func publishObject(_ object: O) -> ObjectPublisher { + public func publishObject( + _ object: O + ) -> ObjectPublisher { return self.publishObject(object.cs_id()) } @@ -50,7 +52,9 @@ extension DataStack { - parameter objectID: the `ObjectID` of the object to observe changes from - returns: an `ObjectPublisher` that broadcasts changes to `object` */ - public func publishObject(_ objectID: O.ObjectID) -> ObjectPublisher { + public func publishObject( + _ objectID: O.ObjectID + ) -> ObjectPublisher { let context = self.unsafeContext() return context.objectPublisher(objectID: objectID) @@ -74,7 +78,9 @@ extension DataStack { - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ clauseChain: B) -> ListPublisher { + public func publishList( + _ clauseChain: B + ) -> ListPublisher { return self.publishList( clauseChain.from, @@ -101,7 +107,9 @@ extension DataStack { - parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ clauseChain: B) -> ListPublisher { + public func publishList( + _ clauseChain: B + ) -> ListPublisher { return self.publishList( clauseChain.from, @@ -117,7 +125,10 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ from: From, _ fetchClauses: FetchClause...) -> ListPublisher { + public func publishList( + _ from: From, + _ fetchClauses: FetchClause... + ) -> ListPublisher { return self.publishList(from, fetchClauses) } @@ -129,7 +140,10 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ from: From, _ fetchClauses: [FetchClause]) -> ListPublisher { + public func publishList( + _ from: From, + _ fetchClauses: [FetchClause] + ) -> ListPublisher { return ListPublisher( dataStack: self, @@ -155,7 +169,11 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListPublisher { + public func publishList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) -> ListPublisher { return self.publishList( from, @@ -172,7 +190,11 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListPublisher` that broadcasts changes to the fetched results */ - public func publishList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListPublisher { + public func publishList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) -> ListPublisher { return ListPublisher( dataStack: self, diff --git a/Sources/DataStack+Migration.swift b/Sources/DataStack+Migration.swift index 6df0766..8f94f90 100644 --- a/Sources/DataStack+Migration.swift +++ b/Sources/DataStack+Migration.swift @@ -47,8 +47,11 @@ extension DataStack { - parameter storage: the storage - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration. */ - public func addStorage(_ storage: T, completion: @escaping (SetupResult) -> Void) { - + public func addStorage( + _ storage: T, + completion: @escaping (SetupResult) -> Void + ) { + self.coordinator.performAsynchronously { if let _ = self.persistentStoreForStorage(storage) { @@ -105,8 +108,11 @@ extension DataStack { - parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration. - returns: a `Progress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured. */ - public func addStorage(_ storage: T, completion: @escaping (SetupResult) -> Void) -> Progress? { - + public func addStorage( + _ storage: T, + completion: @escaping (SetupResult) -> Void + ) -> Progress? { + let fileURL = storage.fileURL Internals.assert( fileURL.isFileURL, @@ -256,8 +262,11 @@ extension DataStack { - throws: a `CoreStoreError` value indicating the failure - returns: a `Progress` instance if a migration has started, or `nil` is no migrations are required */ - public func upgradeStorageIfNeeded(_ storage: T, completion: @escaping (MigrationResult) -> Void) throws -> Progress? { - + public func upgradeStorageIfNeeded( + _ storage: T, + completion: @escaping (MigrationResult) -> Void + ) throws(CoreStoreError) -> Progress? { + return try self.coordinator.performSynchronously { let fileURL = storage.fileURL @@ -298,8 +307,10 @@ extension DataStack { - throws: a `CoreStoreError` value indicating the failure - returns: a `MigrationType` array indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, an error is thrown if either inspection of the store failed, or if no mapping model was found/inferred. */ - public func requiredMigrationsForStorage(_ storage: T) throws -> [MigrationType] { - + public func requiredMigrationsForStorage( + _ storage: T + ) throws(CoreStoreError) -> [MigrationType] { + return try self.coordinator.performSynchronously { let fileURL = storage.fileURL @@ -362,8 +373,12 @@ extension DataStack { // MARK: Private - private func upgradeStorageIfNeeded(_ storage: T, metadata: [String: Any], completion: @escaping (MigrationResult) -> Void) -> Progress? { - + private func upgradeStorageIfNeeded( + _ storage: T, + metadata: [String: Any], + completion: @escaping (MigrationResult) -> Void + ) -> Progress? { + guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else { let error = CoreStoreError.mappingModelNotFound( @@ -485,35 +500,38 @@ extension DataStack { return progress } - private func computeMigrationFromStorage(_ storage: T, metadata: [String: Any]) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? { - + private func computeMigrationFromStorage( + _ storage: T, + metadata: [String: Any] + ) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? { + let schemaHistory = self.schemaHistory if schemaHistory.rawModel.isConfiguration(withName: storage.configuration, compatibleWithStoreMetadata: metadata) { - + return [] } - + guard let initialSchema = schemaHistory.schema(for: metadata) else { - + return nil } var currentVersion = initialSchema.modelVersion let migrationChain: MigrationChain = schemaHistory.migrationChain.isEmpty ? [currentVersion: schemaHistory.currentModelVersion] : schemaHistory.migrationChain - + var migrationSteps = [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]() - + while let nextVersion = migrationChain.nextVersionFrom(currentVersion), let sourceSchema = schemaHistory.schema(for: currentVersion), sourceSchema.modelVersion != schemaHistory.currentModelVersion, let destinationSchema = schemaHistory.schema(for: nextVersion) { - + let mappingProviders = storage.migrationMappingProviders do { - + try withExtendedLifetime((sourceSchema.rawModel(), destinationSchema.rawModel())) { - + let (sourceModel, destinationModel) = $0 let mapping = try mappingProviders.findMapping( sourceSchema: sourceSchema, @@ -531,22 +549,29 @@ extension DataStack { } } catch { - + return nil } currentVersion = nextVersion } - + if migrationSteps.last?.destinationModel == schemaHistory.rawModel { - + return migrationSteps } - + return nil } - private func startMigrationForStorage(_ storage: T, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType, progress: Progress) throws { - + private func startMigrationForStorage( + _ storage: T, + sourceModel: NSManagedObjectModel, + destinationModel: NSManagedObjectModel, + mappingModel: NSMappingModel, + migrationType: MigrationType, + progress: Progress + ) throws(CoreStoreError) { + do { try storage.cs_finalizeStorageAndWait(soureModelHint: sourceModel) @@ -703,8 +728,12 @@ extension DataStack { extension Array where Element == SchemaMappingProvider { - func findMapping(sourceSchema: DynamicSchema, destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) { - + func findMapping( + sourceSchema: DynamicSchema, + destinationSchema: DynamicSchema, + storage: LocalStorage + ) throws(CoreStoreError) -> (mappingModel: NSMappingModel, migrationType: MigrationType) { + for element in self { switch element { diff --git a/Sources/DataStack+Observing.swift b/Sources/DataStack+Observing.swift index f4bc077..62bac1f 100644 --- a/Sources/DataStack+Observing.swift +++ b/Sources/DataStack+Observing.swift @@ -37,8 +37,10 @@ extension DataStack { - parameter object: the `DynamicObject` to observe changes from - returns: an `ObjectMonitor` that monitors changes to `object` */ - public func monitorObject(_ object: O) -> ObjectMonitor { - + public func monitorObject( + _ object: O + ) -> ObjectMonitor { + Internals.assert( Thread.isMainThread, "Attempted to observe objects from \(Internals.typeName(self)) outside the main thread." @@ -53,8 +55,11 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorList(_ from: From, _ fetchClauses: FetchClause...) -> ListMonitor { - + public func monitorList( + _ from: From, + _ fetchClauses: FetchClause... + ) -> ListMonitor { + return self.monitorList(from, fetchClauses) } @@ -65,8 +70,11 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorList(_ from: From, _ fetchClauses: [FetchClause]) -> ListMonitor { - + public func monitorList( + _ from: From, + _ fetchClauses: [FetchClause] + ) -> ListMonitor { + Internals.assert( Thread.isMainThread, "Attempted to observe objects from \(Internals.typeName(self)) outside the main thread." @@ -99,8 +107,10 @@ extension DataStack { - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` */ - public func monitorList(_ clauseChain: B) -> ListMonitor { - + public func monitorList( + _ clauseChain: B + ) -> ListMonitor { + return self.monitorList( clauseChain.from, clauseChain.fetchClauses @@ -114,8 +124,12 @@ extension DataStack { - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ fetchClauses: FetchClause...) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ fetchClauses: FetchClause... + ) { + self.monitorList( createAsynchronously: createAsynchronously, from, @@ -130,8 +144,12 @@ extension DataStack { - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ fetchClauses: [FetchClause]) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ fetchClauses: [FetchClause] + ) { + Internals.assert( Thread.isMainThread, "Attempted to observe objects from \(Internals.typeName(self)) outside the main thread." @@ -169,8 +187,11 @@ extension DataStack { - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ clauseChain: B) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ clauseChain: B + ) { + self.monitorList( createAsynchronously: createAsynchronously, clauseChain.from, @@ -186,8 +207,12 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorSectionedList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor { - + public func monitorSectionedList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) -> ListMonitor { + return self.monitorSectionedList( from, sectionBy, @@ -203,8 +228,12 @@ extension DataStack { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorSectionedList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor { - + public func monitorSectionedList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) -> ListMonitor { + Internals.assert( Thread.isMainThread, "Attempted to observe objects from \(Internals.typeName(self)) outside the main thread." @@ -239,8 +268,10 @@ extension DataStack { - parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses - returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `SectionMonitorBuilderType` */ - public func monitorSectionedList(_ clauseChain: B) -> ListMonitor { - + public func monitorSectionedList( + _ clauseChain: B + ) -> ListMonitor { + return self.monitorSectionedList( clauseChain.from, clauseChain.sectionBy, @@ -256,8 +287,13 @@ extension DataStack { - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) { - + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) { + self.monitorSectionedList( createAsynchronously: createAsynchronously, from, @@ -274,8 +310,13 @@ extension DataStack { - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) { - + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) { + Internals.assert( Thread.isMainThread, "Attempted to observe objects from \(Internals.typeName(self)) outside the main thread." @@ -314,8 +355,11 @@ extension DataStack { - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ clauseChain: B) { - + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ clauseChain: B + ) { + self.monitorSectionedList( createAsynchronously: createAsynchronously, clauseChain.from, diff --git a/Sources/DataStack+Querying.swift b/Sources/DataStack+Querying.swift index e885ee3..6c48c15 100644 --- a/Sources/DataStack+Querying.swift +++ b/Sources/DataStack+Querying.swift @@ -39,8 +39,10 @@ extension DataStack: FetchableSource, QueryableSource { - parameter object: a reference to the object created/fetched outside the `DataStack` - returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found. */ - public func fetchExisting(_ object: O) -> O? { - + public func fetchExisting( + _ object: O + ) -> O? { + return self.mainContext.fetchExisting(object) } @@ -50,8 +52,10 @@ extension DataStack: FetchableSource, QueryableSource { - parameter objectID: the `NSManagedObjectID` for the object - returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found. */ - public func fetchExisting(_ objectID: NSManagedObjectID) -> O? { - + public func fetchExisting( + _ objectID: NSManagedObjectID + ) -> O? { + return self.mainContext.fetchExisting(objectID) } @@ -61,8 +65,10 @@ extension DataStack: FetchableSource, QueryableSource { - parameter objects: an array of `DynamicObject`s created/fetched outside the `DataStack` - returns: the `DynamicObject` array for objects that exists in the `DataStack` */ - public func fetchExisting(_ objects: S) -> [O] where S.Iterator.Element == O { - + public func fetchExisting( + _ objects: S + ) -> [O] where S.Iterator.Element == O { + return self.mainContext.fetchExisting(objects) } @@ -72,8 +78,10 @@ extension DataStack: FetchableSource, QueryableSource { - parameter objectIDs: the `NSManagedObjectID` array for the objects - returns: the `DynamicObject` array for objects that exists in the `DataStack` */ - public func fetchExisting(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID { - + public func fetchExisting( + _ objectIDs: S + ) -> [O] where S.Iterator.Element == NSManagedObjectID { + return self.mainContext.fetchExisting(objectIDs) } @@ -85,8 +93,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ from: From, _ fetchClauses: FetchClause...) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> O? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -102,8 +113,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ from: From, _ fetchClauses: [FetchClause]) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> O? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -124,8 +138,10 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchOne(_ clauseChain: B) throws -> B.ObjectType? { - + public func fetchOne( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ObjectType? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -141,8 +157,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ from: From, _ fetchClauses: FetchClause...) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [O] { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -158,8 +177,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ from: From, _ fetchClauses: [FetchClause]) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [O] { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -180,7 +202,9 @@ extension DataStack: FetchableSource, QueryableSource { - returns: all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchAll(_ clauseChain: B) throws -> [B.ObjectType] { + public func fetchAll( + _ clauseChain: B + ) throws(CoreStoreError) -> [B.ObjectType] { Internals.assert( Thread.isMainThread, @@ -197,8 +221,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ from: From, _ fetchClauses: FetchClause...) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> Int { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -214,8 +241,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ from: From, _ fetchClauses: [FetchClause]) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> Int { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -236,8 +266,10 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchCount(_ clauseChain: B) throws -> Int { - + public func fetchCount( + _ clauseChain: B + ) throws(CoreStoreError) -> Int { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -253,8 +285,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ from: From, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -270,8 +305,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ from: From, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -292,8 +330,10 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectID(_ clauseChain: B) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ clauseChain: B + ) throws(CoreStoreError) -> NSManagedObjectID? { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -309,8 +349,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ from: From, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -326,8 +369,11 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ from: From, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -348,8 +394,10 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func fetchObjectIDs(_ clauseChain: B) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ clauseChain: B + ) throws(CoreStoreError) -> [NSManagedObjectID] { + Internals.assert( Thread.isMainThread, "Attempted to fetch from a \(Internals.typeName(self)) outside the main thread." @@ -371,8 +419,12 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> U? { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." @@ -391,8 +443,12 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> U? { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." @@ -415,13 +471,19 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query as specified by the `QueryChainableBuilderType`, or `nil` if no match was found. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryValue(_ clauseChain: B) throws -> B.ResultType? where B.ResultType: QueryableAttributeType { - + public func queryValue( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ResultType? where B.ResultType: QueryableAttributeType { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." ) - return try self.mainContext.queryValue(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + return try self.mainContext.queryValue( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } /** @@ -435,8 +497,12 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> [[String: Any]] { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." @@ -455,8 +521,12 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> [[String: Any]] { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." @@ -488,13 +558,19 @@ extension DataStack: FetchableSource, QueryableSource { - returns: the result of the the query as specified by the `QueryChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - public func queryAttributes(_ clauseChain: B) throws -> [[String: Any]] where B.ResultType == NSDictionary { - + public func queryAttributes( + _ clauseChain: B + ) throws(CoreStoreError) -> [[String: Any]] where B.ResultType == NSDictionary { + Internals.assert( Thread.isMainThread, "Attempted to query from a \(Internals.typeName(self)) outside the main thread." ) - return try self.mainContext.queryAttributes(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + return try self.mainContext.queryAttributes( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } diff --git a/Sources/DataStack+Reactive.swift b/Sources/DataStack+Reactive.swift index d771bb7..7ae01e4 100644 --- a/Sources/DataStack+Reactive.swift +++ b/Sources/DataStack+Reactive.swift @@ -139,8 +139,10 @@ extension DataStack.ReactiveNamespace { - parameter storage: the local storage - returns: A `DataStack.AddStoragePublisher` that emits a `MigrationProgress` value with metadata for migration progress. Note that the `LocalStorage` event value may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration. */ - public func addStorage(_ storage: T) -> DataStack.AddStoragePublisher { - + public func addStorage( + _ storage: T + ) -> DataStack.AddStoragePublisher { + return .init( dataStack: self.base, storage: storage @@ -317,7 +319,9 @@ extension DataStack.ReactiveNamespace { public func importUniqueObjects( _ into: Into, sourceArray: S, - preProcess: @escaping (_ mapping: [O.UniqueIDType: O.ImportSource]) throws -> [O.UniqueIDType: O.ImportSource] = { $0 } + preProcess: @escaping ( + _ mapping: [O.UniqueIDType: O.ImportSource] + ) throws(any Swift.Error) -> [O.UniqueIDType: O.ImportSource] = { $0 } ) -> Future<[O], CoreStoreError> where S.Iterator.Element == O.ImportSource { return .init { (promise) in @@ -367,7 +371,9 @@ extension DataStack.ReactiveNamespace { - returns: A `Future` whose event value be the value returned from the `task` closure. */ public func perform( - _ asynchronous: @escaping (AsynchronousDataTransaction) throws -> Output + _ asynchronous: @escaping ( + _ transaction: AsynchronousDataTransaction + ) throws(any Swift.Error) -> Output ) -> Future { return .init { (promise) in diff --git a/Sources/DataStack+Transaction.swift b/Sources/DataStack+Transaction.swift index 90497cf..e0e0988 100644 --- a/Sources/DataStack+Transaction.swift +++ b/Sources/DataStack+Transaction.swift @@ -39,7 +39,9 @@ extension DataStack { - parameter completion: the closure executed after the save completes. The `Result` argument of the closure will either wrap the return value of `task`, or any uncaught errors thrown from within `task`. Cancelled `task`s will be indicated by `.failure(error: CoreStoreError.userCancelled)`. Custom errors thrown by the user will be wrapped in `CoreStoreError.userError(error: Error)`. */ public func perform( - asynchronous task: @escaping (_ transaction: AsynchronousDataTransaction) throws -> T, + asynchronous task: @escaping ( + _ transaction: AsynchronousDataTransaction + ) throws(any Swift.Error) -> T, sourceIdentifier: Any? = nil, completion: @escaping (AsynchronousDataTransaction.Result) -> Void ) { @@ -61,7 +63,9 @@ extension DataStack { - parameter failure: the closure executed if the save fails or if any errors are thrown within `task`. Cancelled `task`s will be indicated by `CoreStoreError.userCancelled`. Custom errors thrown by the user will be wrapped in `CoreStoreError.userError(error: Error)`. */ public func perform( - asynchronous task: @escaping (_ transaction: AsynchronousDataTransaction) throws -> T, + asynchronous task: @escaping ( + _ transaction: AsynchronousDataTransaction + ) throws(any Swift.Error) -> T, sourceIdentifier: Any? = nil, success: @escaping (T) -> Void, failure: @escaping (CoreStoreError) -> Void @@ -117,41 +121,43 @@ extension DataStack { - returns: the value returned from `task` */ public func perform( - synchronous task: ((_ transaction: SynchronousDataTransaction) throws -> T), + synchronous task: ( + _ transaction: SynchronousDataTransaction + ) throws(any Swift.Error) -> T, waitForAllObservers: Bool = true, sourceIdentifier: Any? = nil - ) throws -> T { - + ) throws(CoreStoreError) -> T { + let transaction = SynchronousDataTransaction( mainContext: self.rootSavingContext, queue: self.childTransactionQueue, sourceIdentifier: sourceIdentifier ) - return try transaction.transactionQueue.cs_sync { - + return try transaction.transactionQueue.cs_sync { () throws(CoreStoreError) -> T in + defer { - + withExtendedLifetime((self, transaction), {}) } let userInfo: T do { - + userInfo = try withoutActuallyEscaping(task, do: { try $0(transaction) }) } catch let error as CoreStoreError { - - throw error + + throw error as CoreStoreError } catch let error { - + throw CoreStoreError.userError(error: error) } if case (_, let error?) = transaction.autoCommit(waitForMerge: waitForAllObservers) { - + throw error } else { - + return userInfo } } diff --git a/Sources/DataStack.AddStoragePublisher.swift b/Sources/DataStack.AddStoragePublisher.swift index 237be98..cc2ec73 100644 --- a/Sources/DataStack.AddStoragePublisher.swift +++ b/Sources/DataStack.AddStoragePublisher.swift @@ -52,8 +52,10 @@ extension DataStack { public typealias Output = CoreStore.MigrationProgress public typealias Failure = CoreStoreError - public func receive(subscriber: S) where S.Input == Output, S.Failure == Failure { - + public func receive( + subscriber: S + ) where S.Input == Output, S.Failure == Failure { + subscriber.receive( subscription: AddStorageSubscription( dataStack: self.dataStack, diff --git a/Sources/DataStack.swift b/Sources/DataStack.swift index 29c7945..0567b4d 100644 --- a/Sources/DataStack.swift +++ b/Sources/DataStack.swift @@ -241,8 +241,8 @@ public final class DataStack: Equatable { - returns: the local SQLite storage added to the stack */ @discardableResult - public func addStorageAndWait() throws -> SQLiteStore { - + public func addStorageAndWait() throws(CoreStoreError) -> SQLiteStore { + return try self.addStorageAndWait(SQLiteStore()) } @@ -258,8 +258,8 @@ public final class DataStack: Equatable { @discardableResult public func addStorageAndWait( _ storage: T - ) throws -> T { - + ) throws(CoreStoreError) -> T { + do { return try self.coordinator.performSynchronously { @@ -278,12 +278,11 @@ public final class DataStack: Equatable { } catch { - let storeError = CoreStoreError(error) Internals.log( - storeError, + error, "Failed to add \(Internals.typeName(storage)) to the stack." ) - throw storeError + throw error } } @@ -299,8 +298,8 @@ public final class DataStack: Equatable { @discardableResult public func addStorageAndWait( _ storage: T - ) throws -> T { - + ) throws(CoreStoreError) -> T { + return try self.coordinator.performSynchronously { let fileURL = storage.fileURL @@ -539,8 +538,8 @@ public final class DataStack: Equatable { _ storage: StorageInterface, finalURL: URL?, finalStoreOptions: [AnyHashable: Any]? - ) throws -> NSPersistentStore { - + ) throws(any Swift.Error) -> NSPersistentStore { + let persistentStore = try self.coordinator.addPersistentStore( ofType: type(of: storage).storeType, configurationName: storage.configuration, diff --git a/Sources/DefaultLogger.swift b/Sources/DefaultLogger.swift index dc11730..438f692 100644 --- a/Sources/DefaultLogger.swift +++ b/Sources/DefaultLogger.swift @@ -47,8 +47,14 @@ public final class DefaultLogger: CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - public func log(level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { - + public func log( + level: LogLevel, + message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) { + #if DEBUG let icon: String let levelString: String @@ -83,8 +89,14 @@ public final class DefaultLogger: CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - public func log(error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { - + public func log( + error: CoreStoreError, + message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) { + #if DEBUG Swift.print("⚠️ [CoreStore: Error] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n \(error)\n") #endif @@ -99,8 +111,14 @@ public final class DefaultLogger: CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - public func assert(_ condition: @autoclosure () -> Bool, message: @autoclosure () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { - + public func assert( + _ condition: @autoclosure () -> Bool, + message: @autoclosure () -> String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) { + #if DEBUG if condition() { @@ -120,8 +138,13 @@ public final class DefaultLogger: CoreStoreLogger { - parameter lineNumber: the source line number - parameter functionName: the source function name */ - public func abort(_ message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) { - + public func abort( + _ message: String, + fileName: StaticString, + lineNumber: Int, + functionName: StaticString + ) { + Swift.print("❗ [CoreStore: Fatal Error] \((String(describing: fileName) as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ \(message)\n") Swift.fatalError(file: fileName, line: UInt(lineNumber)) } diff --git a/Sources/DispatchQueue+CoreStore.swift b/Sources/DispatchQueue+CoreStore.swift index 195d05a..35fda01 100644 --- a/Sources/DispatchQueue+CoreStore.swift +++ b/Sources/DispatchQueue+CoreStore.swift @@ -31,8 +31,11 @@ import Foundation extension DispatchQueue { @nonobjc @inline(__always) - internal static func serial(_ label: String, qos: DispatchQoS) -> DispatchQueue { - + internal static func serial( + _ label: String, + qos: DispatchQoS + ) -> DispatchQueue { + return DispatchQueue( label: label, qos: qos, @@ -43,8 +46,11 @@ extension DispatchQueue { } @nonobjc @inline(__always) - internal static func concurrent(_ label: String, qos: DispatchQoS) -> DispatchQueue { - + internal static func concurrent( + _ label: String, + qos: DispatchQoS + ) -> DispatchQueue { + return DispatchQueue( label: label, qos: qos, @@ -69,26 +75,57 @@ extension DispatchQueue { } @nonobjc @inline(__always) - internal func cs_sync(_ closure: () throws -> T) rethrows -> T { - + internal func cs_sync( + _ closure: () -> T + ) -> T { + + return self.sync { autoreleasepool(invoking: closure) } + } + + @nonobjc @inline(__always) + internal func cs_sync( + _ closure: () throws(any Swift.Error) -> T + ) throws(any Swift.Error) -> T { + return try self.sync { try autoreleasepool(invoking: closure) } } - + @nonobjc @inline(__always) - internal func cs_async(_ closure: @escaping () -> Void) { - + internal func cs_sync( + _ closure: () throws(CoreStoreError) -> T + ) throws(CoreStoreError) -> T { + + do { + + return try self.sync { try autoreleasepool(invoking: closure) } + } + catch { + + throw CoreStoreError(error) + } + } + + @nonobjc @inline(__always) + internal func cs_async( + _ closure: @escaping () -> Void + ) { + self.async { autoreleasepool(invoking: closure) } } @nonobjc @inline(__always) - internal func cs_barrierSync(_ closure: () throws -> T) rethrows -> T { - + internal func cs_barrierSync( + _ closure: () throws(any Swift.Error) -> T + ) rethrows -> T { + return try self.sync(flags: .barrier) { try autoreleasepool(invoking: closure) } } @nonobjc @inline(__always) - internal func cs_barrierAsync(_ closure: @escaping () -> Void) { - + internal func cs_barrierAsync( + _ closure: @escaping () -> Void + ) { + self.async(flags: .barrier) { autoreleasepool(invoking: closure) } } diff --git a/Sources/DynamicObject.swift b/Sources/DynamicObject.swift index 605e1d1..d0e42a2 100644 --- a/Sources/DynamicObject.swift +++ b/Sources/DynamicObject.swift @@ -42,23 +42,34 @@ public protocol DynamicObject: AnyObject { /** Used internally by CoreStore. Do not call directly. */ - static func cs_forceCreate(entityDescription: NSEntityDescription, into context: NSManagedObjectContext, assignTo store: NSPersistentStore) -> Self - + static func cs_forceCreate( + entityDescription: NSEntityDescription, + into context: NSManagedObjectContext, + assignTo store: NSPersistentStore + ) -> Self + /** Used internally by CoreStore. Do not call directly. */ - static func cs_snapshotDictionary(id: ObjectID, context: NSManagedObjectContext) -> [String: Any]? - + static func cs_snapshotDictionary( + id: ObjectID, + context: NSManagedObjectContext + ) -> [String: Any]? + /** Used internally by CoreStore. Do not call directly. */ - static func cs_fromRaw(object: NSManagedObject) -> Self - + static func cs_fromRaw( + object: NSManagedObject + ) -> Self + /** Used internally by CoreStore. Do not call directly. */ - static func cs_matches(object: NSManagedObject) -> Bool - + static func cs_matches( + object: NSManagedObject + ) -> Bool + /** Used internally by CoreStore. Do not call directly. */ @@ -88,8 +99,12 @@ extension NSManagedObject: DynamicObject { // MARK: DynamicObject - public class 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 { @@ -98,7 +113,10 @@ extension NSManagedObject: DynamicObject { return object } - public class func cs_snapshotDictionary(id: ObjectID, context: NSManagedObjectContext) -> [String: Any]? { + public class func cs_snapshotDictionary( + id: ObjectID, + context: NSManagedObjectContext + ) -> [String: Any]? { guard let object = context.fetchExisting(id) as NSManagedObject? else { @@ -125,8 +143,10 @@ extension NSManagedObject: DynamicObject { #endif } - public static func cs_matches(object: NSManagedObject) -> Bool { - + public static func cs_matches( + object: NSManagedObject + ) -> Bool { + return object.isKind(of: self) } @@ -148,8 +168,12 @@ extension CoreStoreObject { // MARK: DynamicObject - public class 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) defer { @@ -159,12 +183,19 @@ extension CoreStoreObject { return self.cs_fromRaw(object: object) } - public class func cs_snapshotDictionary(id: ObjectID, context: NSManagedObjectContext) -> [String: Any]? { + public class func cs_snapshotDictionary( + id: ObjectID, + context: NSManagedObjectContext + ) -> [String: Any]? { var values: [KeyPathString: Any] = [:] if self.meta.needsReflection { - func initializeAttributes(mirror: Mirror, object: Self, into attributes: inout [KeyPathString: Any]) { + func initializeAttributes( + mirror: Mirror, + object: Self, + into attributes: inout [KeyPathString: Any] + ) { if let superClassMirror = mirror.superclassMirror { @@ -225,9 +256,9 @@ extension CoreStoreObject { let object = context.fetchExisting(id) as CoreStoreObject?, let rawObject = object.rawObject, !rawObject.isDeleted - else { + else { - return nil + return nil } for property in self.metaProperties(includeSuperclasses: true) { @@ -267,8 +298,11 @@ extension CoreStoreObject { return unsafeDowncast(coreStoreObject, to: self) } - func forceTypeCast(_ type: AnyClass, to: T.Type) -> T.Type { - + func forceTypeCast( + _ type: AnyClass, + to: T.Type + ) -> T.Type { + return type as! T.Type } let coreStoreObject = forceTypeCast(object.entity.dynamicObjectType!, to: self).init(rawObject: object) @@ -276,8 +310,10 @@ extension CoreStoreObject { return coreStoreObject } - public static func cs_matches(object: NSManagedObject) -> Bool { - + public static func cs_matches( + object: NSManagedObject + ) -> Bool { + guard let type = object.entity.coreStoreEntity?.type else { return false diff --git a/Sources/Entity.swift b/Sources/Entity.swift index fe7f787..0982efd 100644 --- a/Sources/Entity.swift +++ b/Sources/Entity.swift @@ -70,8 +70,14 @@ public final class Entity: DynamicEntity { - parameter indexes: the compound indexes for the entity as an array of arrays. The arrays contained in the returned array contain `KeyPath`s to properties of the entity. - parameter uniqueConstraints: sets uniqueness constraints for the entity. A uniqueness constraint is a set of one or more `KeyPath`s whose value must be unique over the set of instances of that entity. This value forms part of the entity's version hash. Uniqueness constraint violations can be computationally expensive to handle. It is highly suggested that there be only one uniqueness constraint per entity hierarchy. Uniqueness constraints must be defined at the highest level possible, and CoreStore will raise an assertion failure if unique constraints are added to a sub entity. */ - public convenience init(_ entityName: String, isAbstract: Bool = false, versionHashModifier: String? = nil, indexes: [[PartialKeyPath]] = [], uniqueConstraints: [[PartialKeyPath]]) { - + public convenience init( + _ entityName: String, + isAbstract: Bool = false, + versionHashModifier: String? = nil, + indexes: [[PartialKeyPath]] = [], + uniqueConstraints: [[PartialKeyPath]] + ) { + self.init( O.self, entityName, @@ -92,7 +98,12 @@ public final class Entity: DynamicEntity { - parameter versionHashModifier: the version hash modifier for the entity. Used to mark or denote an entity as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where, for example, the structure of an entity is unchanged but the format or content of data has changed.) - parameter indexes: the compound indexes for the entity as an array of arrays. The arrays contained in the returned array contain `KeyPath`s to properties of the entity. */ - public convenience init(_ entityName: String, isAbstract: Bool = false, versionHashModifier: String? = nil, indexes: [[PartialKeyPath]] = []) { + public convenience init( + _ entityName: String, + isAbstract: Bool = false, + versionHashModifier: String? = nil, + indexes: [[PartialKeyPath]] = [] + ) { self.init( O.self, @@ -115,8 +126,15 @@ public final class Entity: DynamicEntity { - parameter indexes: the compound indexes for the entity as an array of arrays. The arrays contained in the returned array contain KeyPath's to properties of the entity. - parameter uniqueConstraints: sets uniqueness constraints for the entity. A uniqueness constraint is a set of one or more `KeyPath`s whose value must be unique over the set of instances of that entity. This value forms part of the entity's version hash. Uniqueness constraint violations can be computationally expensive to handle. It is highly suggested that there be only one uniqueness constraint per entity hierarchy. Uniqueness constraints must be defined at the highest level possible, and CoreStore will raise an assertion failure if unique constraints are added to a sub entity. */ - public init(_ type: O.Type, _ entityName: String, isAbstract: Bool = false, versionHashModifier: String? = nil, indexes: [[PartialKeyPath]] = [], uniqueConstraints: [[PartialKeyPath]]) { - + public init( + _ type: O.Type, + _ entityName: String, + isAbstract: Bool = false, + versionHashModifier: String? = nil, + indexes: [[PartialKeyPath]] = [], + uniqueConstraints: [[PartialKeyPath]] + ) { + let meta = O.meta let toStringArray: ([PartialKeyPath]) -> [KeyPathString] = { @@ -147,7 +165,13 @@ public final class Entity: DynamicEntity { - parameter indexes: the compound indexes for the entity as an array of arrays. The arrays contained in the returned array contain KeyPath's to properties of the entity. - parameter uniqueConstraints: sets uniqueness constraints for the entity. A uniqueness constraint is a set of one or more `KeyPath`s whose value must be unique over the set of instances of that entity. This value forms part of the entity's version hash. Uniqueness constraint violations can be computationally expensive to handle. It is highly suggested that there be only one uniqueness constraint per entity hierarchy. Uniqueness constraints must be defined at the highest level possible, and CoreStore will raise an assertion failure if unique constraints are added to a sub entity. */ - public init(_ type: O.Type, _ entityName: String, isAbstract: Bool = false, versionHashModifier: String? = nil, indexes: [[PartialKeyPath]] = []) { + public init( + _ type: O.Type, + _ entityName: String, + isAbstract: Bool = false, + versionHashModifier: String? = nil, + indexes: [[PartialKeyPath]] = [] + ) { let meta = O.meta let toStringArray: ([PartialKeyPath]) -> [KeyPathString] = { @@ -232,8 +256,15 @@ public /*abstract*/ class DynamicEntity: Hashable { // MARK: Internal - internal init(type: DynamicObject.Type, entityName: String, isAbstract: Bool, versionHashModifier: String?, indexes: [[KeyPathString]], uniqueConstraints: [[KeyPathString]]) { - + internal init( + type: DynamicObject.Type, + entityName: String, + isAbstract: Bool, + versionHashModifier: String?, + indexes: [[KeyPathString]], + uniqueConstraints: [[KeyPathString]] + ) { + self.type = type self.entityName = entityName self.isAbstract = isAbstract diff --git a/Sources/FIeldRelationshipType.swift b/Sources/FIeldRelationshipType.swift index 8c09d85..6825db7 100644 --- a/Sources/FIeldRelationshipType.swift +++ b/Sources/FIeldRelationshipType.swift @@ -57,27 +57,38 @@ public protocol FieldRelationshipType { /** Used internally by CoreStore. Do not call directly. */ - static func cs_toReturnType(from value: NativeValueType?) -> Self + static func cs_toReturnType( + from value: NativeValueType? + ) -> Self /** Used internally by CoreStore. Do not call directly. */ - static func cs_toPublishedType(from value: SnapshotValueType, in context: NSManagedObjectContext) -> PublishedType + static func cs_toPublishedType( + from value: SnapshotValueType, + in context: NSManagedObjectContext + ) -> PublishedType /** Used internally by CoreStore. Do not call directly. */ - static func cs_toNativeType(from value: Self) -> NativeValueType? + static func cs_toNativeType( + from value: Self + ) -> NativeValueType? /** Used internally by CoreStore. Do not call directly. */ - static func cs_toSnapshotType(from value: PublishedType) -> SnapshotValueType + static func cs_toSnapshotType( + from value: PublishedType + ) -> SnapshotValueType /** Used internally by CoreStore. Do not call directly. */ - static func cs_valueForSnapshot(from objectIDs: [DestinationObjectType.ObjectID]) -> SnapshotValueType + static func cs_valueForSnapshot( + from objectIDs: [DestinationObjectType.ObjectID] + ) -> SnapshotValueType } @@ -115,27 +126,38 @@ extension Optional: FieldRelationshipType, FieldRelationshipToOneType where Wrap public typealias PublishedType = ObjectPublisher? - public static func cs_toReturnType(from value: NativeValueType?) -> Self { + public static func cs_toReturnType( + from value: NativeValueType? + ) -> Self { return value.map(Wrapped.cs_fromRaw(object:)) } - public static func cs_toPublishedType(from value: SnapshotValueType, in context: NSManagedObjectContext) -> PublishedType { + public static func cs_toPublishedType( + from value: SnapshotValueType, + in context: NSManagedObjectContext + ) -> PublishedType { return value.map(context.objectPublisher(objectID:)) } - public static func cs_toNativeType(from value: Self) -> NativeValueType? { + public static func cs_toNativeType( + from value: Self + ) -> NativeValueType? { return value?.cs_toRaw() } - public static func cs_toSnapshotType(from value: PublishedType) -> SnapshotValueType { + public static func cs_toSnapshotType( + from value: PublishedType + ) -> SnapshotValueType { return value?.objectID() } - public static func cs_valueForSnapshot(from objectIDs: [DestinationObjectType.ObjectID]) -> SnapshotValueType { + public static func cs_valueForSnapshot( + from objectIDs: [DestinationObjectType.ObjectID] + ) -> SnapshotValueType { return objectIDs.first } @@ -156,7 +178,9 @@ extension Array: FieldRelationshipType, FieldRelationshipToManyType, FieldRelati public typealias PublishedType = [ObjectPublisher] - public static func cs_toReturnType(from value: NativeValueType?) -> Self { + public static func cs_toReturnType( + from value: NativeValueType? + ) -> Self { guard let value = value else { @@ -165,22 +189,31 @@ extension Array: FieldRelationshipType, FieldRelationshipToManyType, FieldRelati return value.map({ Element.cs_fromRaw(object: $0 as! NSManagedObject) }) } - public static func cs_toPublishedType(from value: SnapshotValueType, in context: NSManagedObjectContext) -> PublishedType { + public static func cs_toPublishedType( + from value: SnapshotValueType, + in context: NSManagedObjectContext + ) -> PublishedType { return value.map(context.objectPublisher(objectID:)) } - public static func cs_toNativeType(from value: Self) -> NativeValueType? { + public static func cs_toNativeType( + from value: Self + ) -> NativeValueType? { return NSOrderedSet(array: value.map({ $0.rawObject! })) } - public static func cs_toSnapshotType(from value: PublishedType) -> SnapshotValueType { + public static func cs_toSnapshotType( + from value: PublishedType + ) -> SnapshotValueType { return value.map({ $0.objectID() }) } - public static func cs_valueForSnapshot(from objectIDs: [DestinationObjectType.ObjectID]) -> SnapshotValueType { + public static func cs_valueForSnapshot( + from objectIDs: [DestinationObjectType.ObjectID] + ) -> SnapshotValueType { return objectIDs } @@ -201,7 +234,9 @@ extension Set: FieldRelationshipType, FieldRelationshipToManyType, FieldRelation public typealias PublishedType = Set> - public static func cs_toReturnType(from value: NativeValueType?) -> Self { + public static func cs_toReturnType( + from value: NativeValueType? + ) -> Self { guard let value = value else { @@ -210,22 +245,31 @@ extension Set: FieldRelationshipType, FieldRelationshipToManyType, FieldRelation return Set(value.map({ Element.cs_fromRaw(object: $0 as! NSManagedObject) })) } - public static func cs_toPublishedType(from value: SnapshotValueType, in context: NSManagedObjectContext) -> PublishedType { + public static func cs_toPublishedType( + from value: SnapshotValueType, + in context: NSManagedObjectContext + ) -> PublishedType { return PublishedType(value.map(context.objectPublisher(objectID:))) } - public static func cs_toNativeType(from value: Self) -> NativeValueType? { + public static func cs_toNativeType( + from value: Self + ) -> NativeValueType? { return NSSet(array: value.map({ $0.rawObject! })) } - public static func cs_toSnapshotType(from value: PublishedType) -> SnapshotValueType { + public static func cs_toSnapshotType( + from value: PublishedType + ) -> SnapshotValueType { return SnapshotValueType(value.map({ $0.objectID() })) } - public static func cs_valueForSnapshot(from objectIDs: [DestinationObjectType.ObjectID]) -> SnapshotValueType { + public static func cs_valueForSnapshot( + from objectIDs: [DestinationObjectType.ObjectID] + ) -> SnapshotValueType { return .init(objectIDs) } diff --git a/Sources/FetchableSource.swift b/Sources/FetchableSource.swift index 1c9c60c..8b094bd 100644 --- a/Sources/FetchableSource.swift +++ b/Sources/FetchableSource.swift @@ -40,23 +40,29 @@ public protocol FetchableSource: AnyObject { - parameter object: a reference to the object created/fetched outside the `FetchableSource`'s context - returns: the `DynamicObject` instance if the object exists in the `FetchableSource`'s context, or `nil` if not found. */ - func fetchExisting(_ object: O) -> O? - + func fetchExisting( + _ object: O + ) -> O? + /** Fetches the `DynamicObject` instance in the `FetchableSource`'s context from an `NSManagedObjectID`. - parameter objectID: the `NSManagedObjectID` for the object - returns: the `DynamicObject` instance if the object exists in the `FetchableSource`, or `nil` if not found. */ - func fetchExisting(_ objectID: NSManagedObjectID) -> O? - + func fetchExisting( + _ objectID: NSManagedObjectID + ) -> O? + /** Fetches the `DynamicObject` instances in the `FetchableSource`'s context from references created from another managed object context. - parameter objects: an array of `DynamicObject`s created/fetched outside the `FetchableSource`'s context - returns: the `DynamicObject` array for objects that exists in the `FetchableSource` */ - func fetchExisting(_ objects: S) -> [O] where S.Iterator.Element == O + func fetchExisting( + _ objects: S + ) -> [O] where S.Iterator.Element == O /** Fetches the `DynamicObject` instances in the `FetchableSource`'s context from a list of `NSManagedObjectID`. @@ -64,7 +70,9 @@ public protocol FetchableSource: AnyObject { - parameter objectIDs: the `NSManagedObjectID` array for the objects - returns: the `DynamicObject` array for objects that exists in the `FetchableSource`'s context */ - func fetchExisting(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID + func fetchExisting( + _ objectIDs: S + ) -> [O] where S.Iterator.Element == NSManagedObjectID /** Fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -74,7 +82,10 @@ public protocol FetchableSource: AnyObject { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchOne(_ from: From, _ fetchClauses: FetchClause...) throws -> O? + func fetchOne( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> O? /** Fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -84,8 +95,11 @@ public protocol FetchableSource: AnyObject { - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchOne(_ from: From, _ fetchClauses: [FetchClause]) throws -> O? - + func fetchOne( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> O? + /** Fetches the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses. ``` @@ -99,7 +113,9 @@ public protocol FetchableSource: AnyObject { - returns: the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchOne(_ clauseChain: B) throws -> B.ObjectType? + func fetchOne( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ObjectType? /** Fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -109,7 +125,10 @@ public protocol FetchableSource: AnyObject { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchAll(_ from: From, _ fetchClauses: FetchClause...) throws -> [O] + func fetchAll( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [O] /** Fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -119,8 +138,11 @@ public protocol FetchableSource: AnyObject { - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchAll(_ from: From, _ fetchClauses: [FetchClause]) throws -> [O] - + func fetchAll( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [O] + /** Fetches all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` @@ -134,7 +156,9 @@ public protocol FetchableSource: AnyObject { - returns: all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchAll(_ clauseChain: B) throws -> [B.ObjectType] + func fetchAll( + _ clauseChain: B + ) throws(CoreStoreError) -> [B.ObjectType] /** Fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -144,7 +168,10 @@ public protocol FetchableSource: AnyObject { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchCount(_ from: From, _ fetchClauses: FetchClause...) throws -> Int + func fetchCount( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> Int /** Fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -154,8 +181,11 @@ public protocol FetchableSource: AnyObject { - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchCount(_ from: From, _ fetchClauses: [FetchClause]) throws -> Int - + func fetchCount( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> Int + /** Fetches the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` @@ -169,7 +199,9 @@ public protocol FetchableSource: AnyObject { - returns: the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchCount(_ clauseChain: B) throws -> Int + func fetchCount( + _ clauseChain: B + ) throws(CoreStoreError) -> Int /** Fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -179,7 +211,10 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectID(_ from: From, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? + func fetchObjectID( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> NSManagedObjectID? /** Fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -189,8 +224,11 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectID(_ from: From, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? - + func fetchObjectID( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> NSManagedObjectID? + /** Fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses. ``` @@ -204,7 +242,9 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectID(_ clauseChain: B) throws -> NSManagedObjectID? + func fetchObjectID( + _ clauseChain: B + ) throws(CoreStoreError) -> NSManagedObjectID? /** Fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -214,7 +254,10 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectIDs(_ from: From, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] + func fetchObjectIDs( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [NSManagedObjectID] /** Fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. @@ -224,8 +267,11 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectIDs(_ from: From, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] - + func fetchObjectIDs( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [NSManagedObjectID] + /** Fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` @@ -239,8 +285,10 @@ public protocol FetchableSource: AnyObject { - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func fetchObjectIDs(_ clauseChain: B) throws -> [NSManagedObjectID] - + func fetchObjectIDs( + _ clauseChain: B + ) throws(CoreStoreError) -> [NSManagedObjectID] + /** The internal `NSManagedObjectContext` managed by this `FetchableSource`. Using this context directly should typically be avoided, and is provided by CoreStore only for extremely specialized cases. */ diff --git a/Sources/Field.Coded.swift b/Sources/Field.Coded.swift index f2933b3..92a7c59 100644 --- a/Sources/Field.Coded.swift +++ b/Sources/Field.Coded.swift @@ -127,8 +127,19 @@ extension FieldContainer { versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, coder fieldCoderType: Coder.Type, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) where Coder.FieldStoredValue == V { @@ -172,8 +183,19 @@ extension FieldContainer { versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, coder fieldCoderType: Coder.Type, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) where Coder.FieldStoredValue == V { @@ -276,9 +298,23 @@ extension FieldContainer { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - coder: (encode: (V) -> Data?, decode: (Data?) -> V), - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + coder: ( + encode: (V) -> Data?, + decode: (Data?) -> V + ), + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) { @@ -328,9 +364,23 @@ extension FieldContainer { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - coder: (encode: (V) -> Data?, decode: (Data?) -> V), - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + coder: ( + encode: (V) -> Data?, + decode: (Data?) -> V + ), + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) { @@ -428,7 +478,10 @@ extension FieldContainer { return ObjectType.self } - internal static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { + internal static func read( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? { let field = field as! Self if let customGetter = field.customGetter { @@ -449,7 +502,11 @@ extension FieldContainer { } } - internal static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) { + internal static func modify( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject, + newValue: Any? + ) { Internals.assert( rawObject.isEditableInContext() == true, @@ -564,10 +621,22 @@ extension FieldContainer { versionHashModifier: @escaping () -> String?, renamingIdentifier: @escaping () -> String?, valueTransformer: @escaping () -> Internals.AnyFieldCoder?, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)?, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? , + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )?, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? , dynamicInitialValue: (() -> V)?, - affectedByKeyPaths: @escaping () -> Set) { + affectedByKeyPaths: @escaping () -> Set + ) { self.keyPath = keyPath self.entityDescriptionValues = { @@ -682,8 +751,19 @@ extension FieldContainer.Coded where V: FieldOptionalType { versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, coder: Coder.Type, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) where Coder.FieldStoredValue == V.Wrapped { @@ -727,8 +807,19 @@ extension FieldContainer.Coded where V: FieldOptionalType { versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, coder: Coder.Type, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) where Coder.FieldStoredValue == V.Wrapped { @@ -832,9 +923,23 @@ extension FieldContainer.Coded where V: FieldOptionalType { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - coder: (encode: (V) -> Data?, decode: (Data?) -> V), - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + coder: ( + encode: (V) -> Data?, + decode: (Data?) -> V + ), + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) { @@ -884,9 +989,23 @@ extension FieldContainer.Coded where V: FieldOptionalType { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - coder: (encode: (V) -> Data?, decode: (Data?) -> V), - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + coder: ( + encode: (V) -> Data?, + decode: (Data?) -> V + ), + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) { @@ -978,8 +1097,19 @@ extension FieldContainer.Coded where V: DefaultNSSecureCodable { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) { @@ -1020,8 +1150,19 @@ extension FieldContainer.Coded where V: DefaultNSSecureCodable { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) { @@ -1113,8 +1254,19 @@ extension FieldContainer.Coded where V: FieldOptionalType, V.Wrapped: DefaultNSS _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) { @@ -1155,8 +1307,19 @@ extension FieldContainer.Coded where V: FieldOptionalType, V.Wrapped: DefaultNSS _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) { diff --git a/Sources/Field.Relationship.swift b/Sources/Field.Relationship.swift index b79cf62..7e985d7 100644 --- a/Sources/Field.Relationship.swift +++ b/Sources/Field.Relationship.swift @@ -167,7 +167,10 @@ extension FieldContainer { return ObjectType.self } - internal static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { + internal static func read( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? { let field = field as! Self let keyPath = field.keyPath @@ -176,8 +179,12 @@ extension FieldContainer { ) } - internal static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) { - + internal static func modify( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject, + newValue: Any? + ) { + Internals.assert( rawObject.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." @@ -196,7 +203,10 @@ extension FieldContainer { internal let entityDescriptionValues: () -> FieldRelationshipProtocol.EntityDescriptionValues - internal static func valueForSnapshot(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { + internal static func valueForSnapshot( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? { Internals.assert( rawObject.isRunningInAllowedQueue() == true, diff --git a/Sources/Field.Stored.swift b/Sources/Field.Stored.swift index cb46db0..83184a1 100644 --- a/Sources/Field.Stored.swift +++ b/Sources/Field.Stored.swift @@ -116,8 +116,19 @@ extension FieldContainer { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [] ) { @@ -157,8 +168,19 @@ extension FieldContainer { _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, previousVersionKeyPath: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = [], dynamicInitialValue: @escaping () -> V ) { @@ -255,7 +277,10 @@ extension FieldContainer { return ObjectType.self } - internal static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { + internal static func read( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? { let field = field as! Self if let customGetter = field.customGetter { @@ -276,7 +301,10 @@ extension FieldContainer { } } - internal static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) { + internal static func modify( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject, newValue: Any? + ) { Internals.assert( rawObject.isEditableInContext() == true, @@ -379,7 +407,8 @@ extension FieldContainer { customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)?, customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)?, dynamicInitialValue: (() -> V)?, - affectedByKeyPaths: @escaping () -> Set) { + affectedByKeyPaths: @escaping () -> Set + ) { self.keyPath = keyPath self.entityDescriptionValues = { @@ -403,8 +432,19 @@ extension FieldContainer { // MARK: Private - private let customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? - private let customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? + private let customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? + private let customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? private let dynamicInitialValue: (() -> V)? } } diff --git a/Sources/Field.Virtual.swift b/Sources/Field.Virtual.swift index d9c9b7a..401d524 100644 --- a/Sources/Field.Virtual.swift +++ b/Sources/Field.Virtual.swift @@ -80,7 +80,13 @@ extension FieldContainer { public init( _ keyPath: KeyPathString, customGetter: @escaping (_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = []) { self.init( @@ -99,8 +105,19 @@ extension FieldContainer { wrappedValue initial: @autoclosure @escaping () -> V, _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = []) { fatalError() @@ -185,7 +202,10 @@ extension FieldContainer { return ObjectType.self } - internal static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { + internal static func read( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? { let field = field as! Self if let customGetter = field.customGetter { @@ -206,7 +226,11 @@ extension FieldContainer { } } - internal static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) { + internal static func modify( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject, + newValue: Any? + ) { Internals.assert( rawObject.isEditableInContext() == true, @@ -285,7 +309,8 @@ extension FieldContainer { keyPath: KeyPathString, customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)?, customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? , - affectedByKeyPaths: @escaping () -> Set) { + affectedByKeyPaths: @escaping () -> Set + ) { self.keyPath = keyPath self.entityDescriptionValues = { @@ -308,8 +333,19 @@ extension FieldContainer { // MARK: Private - private let customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? - private let customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? + private let customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? + private let customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? } } @@ -342,8 +378,19 @@ extension FieldContainer.Virtual where V: FieldOptionalType { */ public init( _ keyPath: KeyPathString, - customGetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy) -> V)? = nil, - customSetter: ((_ object: ObjectProxy, _ field: ObjectProxy.FieldProxy, _ newValue: V) -> Void)? = nil, + customGetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy + ) -> V + )? = nil, + customSetter: ( + ( + _ object: ObjectProxy, + _ field: ObjectProxy.FieldProxy, + _ newValue: V + ) -> Void + )? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set = []) { self.init( diff --git a/Sources/FieldProtocol.swift b/Sources/FieldProtocol.swift index 83d3aff..63a421f 100644 --- a/Sources/FieldProtocol.swift +++ b/Sources/FieldProtocol.swift @@ -33,6 +33,14 @@ internal protocol FieldProtocol: PropertyProtocol { static var dynamicObjectType: CoreStoreObject.Type { get } - static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? - static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) + static func read( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject + ) -> Any? + + static func modify( + field: FieldProtocol, + for rawObject: CoreStoreManagedObject, + newValue: Any? + ) } diff --git a/Sources/From+Querying.swift b/Sources/From+Querying.swift index 8d787c7..cc8e38f 100644 --- a/Sources/From+Querying.swift +++ b/Sources/From+Querying.swift @@ -37,8 +37,10 @@ extension From { - parameter clause: the `Where` clause to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that starts with the specified `Where` clause */ - public func `where`(_ clause: Where) -> FetchChainBuilder { - + public func `where`( + _ clause: Where + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause) } @@ -48,8 +50,10 @@ extension From { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses */ - public func `where`(combineByAnd clauses: Where...) -> FetchChainBuilder { - + public func `where`( + combineByAnd clauses: Where... + ) -> FetchChainBuilder { + return self.fetchChain(appending: clauses.combinedByAnd()) } @@ -59,8 +63,10 @@ extension From { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses */ - public func `where`(combineByOr clauses: Where...) -> FetchChainBuilder { - + public func `where`( + combineByOr clauses: Where... + ) -> FetchChainBuilder { + return self.fetchChain(appending: clauses.combinedByOr()) } @@ -100,7 +106,9 @@ extension From { - parameter clause: the `OrderBy` clause to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that starts with the specified `OrderBy` clause */ - public func orderBy(_ clause: OrderBy) -> FetchChainBuilder { + public func orderBy( + _ clause: OrderBy + ) -> FetchChainBuilder { return self.fetchChain(appending: clause) } @@ -126,7 +134,9 @@ extension From { - parameter sortKeys: a series of `SortKey`s - returns: a `FetchChainBuilder` with a series of `SortKey`s */ - public func orderBy(_ sortKeys: [OrderBy.SortKey]) -> FetchChainBuilder { + public func orderBy( + _ sortKeys: [OrderBy.SortKey] + ) -> FetchChainBuilder { return self.fetchChain(appending: OrderBy(sortKeys)) } @@ -137,8 +147,10 @@ extension From { - parameter fetchRequest: the block to customize the `NSFetchRequest` - returns: a `FetchChainBuilder` with closure where the `NSFetchRequest` may be configured */ - public func tweak(_ fetchRequest: @escaping (NSFetchRequest) -> Void) -> FetchChainBuilder { - + public func tweak( + _ fetchRequest: @escaping (NSFetchRequest) -> Void + ) -> FetchChainBuilder { + return self.fetchChain(appending: Tweak(fetchRequest)) } @@ -148,8 +160,10 @@ extension From { - parameter clause: the `FetchClause` to add to the `FetchChainBuilder` - returns: a `FetchChainBuilder` containing the specified `FetchClause` */ - public func appending(_ clause: FetchClause) -> FetchChainBuilder { - + public func appending( + _ clause: FetchClause + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause) } @@ -159,8 +173,10 @@ extension From { - parameter clauses: the `FetchClause`s to add to the `FetchChainBuilder` - returns: a `FetchChainBuilder` containing the specified `FetchClause`s */ - public func appending(contentsOf clauses: S) -> FetchChainBuilder where S.Element == FetchClause { - + public func appending( + contentsOf clauses: S + ) -> FetchChainBuilder where S.Element == FetchClause { + return self.fetchChain(appending: clauses) } @@ -170,8 +186,10 @@ extension From { - parameter clause: the `Select` clause to create a `QueryChainBuilder` with - returns: a `QueryChainBuilder` that starts with the specified `Select` clause */ - public func select(_ clause: Select) -> QueryChainBuilder { - + public func select( + _ clause: Select + ) -> QueryChainBuilder { + return .init( from: self, select: clause, @@ -221,8 +239,10 @@ extension From { - parameter clause: the `SectionBy` to be used by the `ListMonitor` - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ clause: SectionBy) -> SectionMonitorChainBuilder { - + public func sectionBy( + _ clause: SectionBy + ) -> SectionMonitorChainBuilder { + return .init( from: self, sectionBy: clause, @@ -236,8 +256,10 @@ extension From { - parameter sectionKeyPath: the key path to use to group the objects into sections - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ sectionKeyPath: KeyPathString) -> SectionMonitorChainBuilder { - + public func sectionBy( + _ sectionKeyPath: KeyPathString + ) -> SectionMonitorChainBuilder { + return self.sectionBy(sectionKeyPath, sectionIndexTransformer: { _ in nil }) } @@ -267,13 +289,17 @@ extension From { // MARK: Private - private func fetchChain(appending clause: FetchClause) -> FetchChainBuilder { - + private func fetchChain( + appending clause: FetchClause + ) -> FetchChainBuilder { + return .init(from: self, fetchClauses: [clause]) } - private func fetchChain(appending clauses: S) -> FetchChainBuilder where S.Element == FetchClause { - + private func fetchChain( + appending clauses: S + ) -> FetchChainBuilder where S.Element == FetchClause { + return .init(from: self, fetchClauses: Array(clauses)) } } @@ -289,8 +315,10 @@ extension From where O: NSManagedObject { - parameter keyPath: the keyPath to query the value for - returns: a `QueryChainBuilder` that starts with a `Select` clause created from the specified key path */ - public func select(_ keyPath: KeyPath) -> QueryChainBuilder { - + public func select( + _ keyPath: KeyPath + ) -> QueryChainBuilder { + return self.select(R.self, [SelectTerm.attribute(keyPath)]) } @@ -300,8 +328,10 @@ extension From where O: NSManagedObject { - parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ sectionKeyPath: KeyPath) -> SectionMonitorChainBuilder { - + public func sectionBy( + _ sectionKeyPath: KeyPath + ) -> SectionMonitorChainBuilder { + return self.sectionBy( sectionKeyPath._kvcKeyPathString!, sectionIndexTransformer: { _ in nil } @@ -339,8 +369,10 @@ extension From where O: CoreStoreObject { - parameter clause: a closure that returns a `Where` clause - returns: a `FetchChainBuilder` that starts with the specified `Where` clause */ - public func `where`(_ clause: (O) -> T) -> FetchChainBuilder { - + public func `where`( + _ clause: (O) -> T + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause(O.meta)) } @@ -350,8 +382,10 @@ extension From where O: CoreStoreObject { - parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ sectionKeyPath: KeyPath.Stored>) -> SectionMonitorChainBuilder { - + public func sectionBy( + _ sectionKeyPath: KeyPath.Stored> + ) -> SectionMonitorChainBuilder { + return self.sectionBy( O.meta[keyPath: sectionKeyPath].keyPath, sectionIndexTransformer: { _ in nil } @@ -364,8 +398,10 @@ extension From where O: CoreStoreObject { - parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ sectionKeyPath: KeyPath.Virtual>) -> SectionMonitorChainBuilder { - + public func sectionBy( + _ sectionKeyPath: KeyPath.Virtual> + ) -> SectionMonitorChainBuilder { + return self.sectionBy( O.meta[keyPath: sectionKeyPath].keyPath, sectionIndexTransformer: { _ in nil } @@ -378,7 +414,9 @@ extension From where O: CoreStoreObject { - parameter sectionKeyPath: the `KeyPath` to use to group the objects into sections - returns: a `SectionMonitorChainBuilder` that is sectioned by the specified key path */ - public func sectionBy(_ sectionKeyPath: KeyPath.Coded>) -> SectionMonitorChainBuilder { + public func sectionBy( + _ sectionKeyPath: KeyPath.Coded> + ) -> SectionMonitorChainBuilder { return self.sectionBy( O.meta[keyPath: sectionKeyPath].keyPath, @@ -455,8 +493,10 @@ extension FetchChainBuilder { - parameter clause: a `Where` clause to add to the fetch builder - returns: a new `FetchChainBuilder` containing the `Where` clause */ - public func `where`(_ clause: Where) -> FetchChainBuilder { - + public func `where`( + _ clause: Where + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause) } @@ -466,8 +506,10 @@ extension FetchChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses */ - public func `where`(combineByAnd clauses: Where...) -> FetchChainBuilder { - + public func `where`( + combineByAnd clauses: Where... + ) -> FetchChainBuilder { + return self.fetchChain(appending: clauses.combinedByAnd()) } @@ -477,8 +519,10 @@ extension FetchChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses */ - public func `where`(combineByOr clauses: Where...) -> FetchChainBuilder { - + public func `where`( + combineByOr clauses: Where... + ) -> FetchChainBuilder { + return self.fetchChain(appending: clauses.combinedByOr()) } @@ -489,8 +533,11 @@ extension FetchChainBuilder { - parameter args: the arguments for `format` - returns: a new `FetchChainBuilder` containing the `Where` clause */ - public func `where`(format: String, _ args: Any...) -> FetchChainBuilder { - + public func `where`( + format: String, + _ args: Any... + ) -> FetchChainBuilder { + return self.fetchChain(appending: Where(format, argumentArray: args)) } @@ -501,8 +548,11 @@ extension FetchChainBuilder { - parameter argumentArray: the arguments for `format` - returns: a new `FetchChainBuilder` containing the `Where` clause */ - public func `where`(format: String, argumentArray: [Any]?) -> FetchChainBuilder { - + public func `where`( + format: String, + argumentArray: [Any]? + ) -> FetchChainBuilder { + return self.fetchChain(appending: Where(format, argumentArray: argumentArray)) } @@ -512,7 +562,9 @@ extension FetchChainBuilder { - parameter clause: the `OrderBy` clause to add - returns: a new `FetchChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ clause: OrderBy) -> FetchChainBuilder { + public func orderBy( + _ clause: OrderBy + ) -> FetchChainBuilder { return self.fetchChain(appending: clause) } @@ -524,8 +576,11 @@ extension FetchChainBuilder { - parameter sortKeys: a series of other `SortKey`s - returns: a new `FetchChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKey: OrderBy.SortKey, _ sortKeys: OrderBy.SortKey...) -> FetchChainBuilder { - + public func orderBy( + _ sortKey: OrderBy.SortKey, + _ sortKeys: OrderBy.SortKey... + ) -> FetchChainBuilder { + return self.fetchChain(appending: OrderBy([sortKey] + sortKeys)) } @@ -535,7 +590,9 @@ extension FetchChainBuilder { - parameter sortKeys: a series of `SortKey`s - returns: a new `FetchChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKeys: [OrderBy.SortKey]) -> FetchChainBuilder { + public func orderBy( + _ sortKeys: [OrderBy.SortKey] + ) -> FetchChainBuilder { return self.fetchChain(appending: OrderBy(sortKeys)) } @@ -546,8 +603,10 @@ extension FetchChainBuilder { - parameter fetchRequest: the block to customize the `NSFetchRequest` - returns: a new `FetchChainBuilder` containing the `Tweak` clause */ - public func tweak(_ fetchRequest: @escaping (NSFetchRequest) -> Void) -> FetchChainBuilder { - + public func tweak( + _ fetchRequest: @escaping (NSFetchRequest) -> Void + ) -> FetchChainBuilder { + return self.fetchChain(appending: Tweak(fetchRequest)) } @@ -557,8 +616,10 @@ extension FetchChainBuilder { - parameter clause: the `FetchClause` to add to the `FetchChainBuilder` - returns: a new `FetchChainBuilder` containing the `FetchClause` */ - public func appending(_ clause: FetchClause) -> FetchChainBuilder { - + public func appending( + _ clause: FetchClause + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause) } @@ -568,24 +629,30 @@ extension FetchChainBuilder { - parameter clauses: the `FetchClause`s to add to the `FetchChainBuilder` - returns: a new `FetchChainBuilder` containing the `FetchClause`s */ - public func appending(contentsOf clauses: S) -> FetchChainBuilder where S.Element == FetchClause { - + public func appending( + contentsOf clauses: S + ) -> FetchChainBuilder where S.Element == FetchClause { + return self.fetchChain(appending: clauses) } // MARK: Private - private func fetchChain(appending clause: FetchClause) -> FetchChainBuilder { - + private func fetchChain( + appending clause: FetchClause + ) -> FetchChainBuilder { + return .init( from: self.from, fetchClauses: self.fetchClauses + [clause] ) } - private func fetchChain(appending clauses: S) -> FetchChainBuilder where S.Element == FetchClause { - + private func fetchChain( + appending clauses: S + ) -> FetchChainBuilder where S.Element == FetchClause { + return .init( from: self.from, fetchClauses: self.fetchClauses + Array(clauses) @@ -598,8 +665,10 @@ extension FetchChainBuilder { extension FetchChainBuilder where O: CoreStoreObject { - public func `where`(_ clause: (O) -> T) -> FetchChainBuilder { - + public func `where`( + _ clause: (O) -> T + ) -> FetchChainBuilder { + return self.fetchChain(appending: clause(O.meta)) } } @@ -615,8 +684,10 @@ extension QueryChainBuilder { - parameter clause: a `Where` clause to add to the query builder - returns: a new `QueryChainBuilder` containing the `Where` clause */ - public func `where`(_ clause: Where) -> QueryChainBuilder { - + public func `where`( + _ clause: Where + ) -> QueryChainBuilder { + return self.queryChain(appending: clause) } @@ -626,8 +697,10 @@ extension QueryChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses */ - public func `where`(combineByAnd clauses: Where...) -> QueryChainBuilder { - + public func `where`( + combineByAnd clauses: Where... + ) -> QueryChainBuilder { + return self.queryChain(appending: clauses.combinedByAnd()) } @@ -637,8 +710,10 @@ extension QueryChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses */ - public func `where`(combineByOr clauses: Where...) -> QueryChainBuilder { - + public func `where`( + combineByOr clauses: Where... + ) -> QueryChainBuilder { + return self.queryChain(appending: clauses.combinedByOr()) } @@ -649,8 +724,11 @@ extension QueryChainBuilder { - parameter args: the arguments for `format` - returns: a new `QueryChainBuilder` containing the `Where` clause */ - public func `where`(format: String, _ args: Any...) -> QueryChainBuilder { - + public func `where`( + format: String, + _ args: Any... + ) -> QueryChainBuilder { + return self.queryChain(appending: Where(format, argumentArray: args)) } @@ -661,8 +739,11 @@ extension QueryChainBuilder { - parameter argumentArray: the arguments for `format` - returns: a new `QueryChainBuilder` containing the `Where` clause */ - public func `where`(format: String, argumentArray: [Any]?) -> QueryChainBuilder { - + public func `where`( + format: String, + argumentArray: [Any]? + ) -> QueryChainBuilder { + return self.queryChain(appending: Where(format, argumentArray: argumentArray)) } @@ -672,7 +753,9 @@ extension QueryChainBuilder { - parameter clause: the `OrderBy` clause to add - returns: a new `QueryChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ clause: OrderBy) -> QueryChainBuilder { + public func orderBy( + _ clause: OrderBy + ) -> QueryChainBuilder { return self.queryChain(appending: clause) } @@ -684,8 +767,11 @@ extension QueryChainBuilder { - parameter sortKeys: a series of other `SortKey`s - returns: a new `QueryChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKey: OrderBy.SortKey, _ sortKeys: OrderBy.SortKey...) -> QueryChainBuilder { - + public func orderBy( + _ sortKey: OrderBy.SortKey, + _ sortKeys: OrderBy.SortKey... + ) -> QueryChainBuilder { + return self.queryChain(appending: OrderBy([sortKey] + sortKeys)) } @@ -695,7 +781,9 @@ extension QueryChainBuilder { - parameter sortKeys: a series of `SortKey`s - returns: a new `QueryChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKeys: [OrderBy.SortKey]) -> QueryChainBuilder { + public func orderBy( + _ sortKeys: [OrderBy.SortKey] + ) -> QueryChainBuilder { return self.queryChain(appending: OrderBy(sortKeys)) } @@ -706,8 +794,10 @@ extension QueryChainBuilder { - parameter fetchRequest: the block to customize the `NSFetchRequest` - returns: a new `QueryChainBuilder` containing the `Tweak` clause */ - public func tweak(_ fetchRequest: @escaping (NSFetchRequest) -> Void) -> QueryChainBuilder { - + public func tweak( + _ fetchRequest: @escaping (NSFetchRequest) -> Void + ) -> QueryChainBuilder { + return self.queryChain(appending: Tweak(fetchRequest)) } @@ -717,8 +807,10 @@ extension QueryChainBuilder { - parameter clause: a `GroupBy` clause to add to the query builder - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ clause: GroupBy) -> QueryChainBuilder { - + public func groupBy( + _ clause: GroupBy + ) -> QueryChainBuilder { + return self.queryChain(appending: clause) } @@ -729,8 +821,11 @@ extension QueryChainBuilder { - parameter keyPaths: other key paths to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPath: KeyPathString, _ keyPaths: KeyPathString...) -> QueryChainBuilder { - + public func groupBy( + _ keyPath: KeyPathString, + _ keyPaths: KeyPathString... + ) -> QueryChainBuilder { + return self.groupBy(GroupBy([keyPath] + keyPaths)) } @@ -740,8 +835,10 @@ extension QueryChainBuilder { - parameter keyPaths: a series of key paths to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPaths: [KeyPathString]) -> QueryChainBuilder { - + public func groupBy( + _ keyPaths: [KeyPathString] + ) -> QueryChainBuilder { + return self.queryChain(appending: GroupBy(keyPaths)) } @@ -751,8 +848,10 @@ extension QueryChainBuilder { - parameter clause: the `QueryClause` to add to the `QueryChainBuilder` - returns: a new `QueryChainBuilder` containing the `QueryClause` */ - public func appending(_ clause: QueryClause) -> QueryChainBuilder { - + public func appending( + _ clause: QueryClause + ) -> QueryChainBuilder { + return self.queryChain(appending: clause) } @@ -762,16 +861,20 @@ extension QueryChainBuilder { - parameter clauses: the `QueryClause`s to add to the `QueryChainBuilder` - returns: a new `QueryChainBuilder` containing the `QueryClause`s */ - public func appending(contentsOf clauses: S) -> QueryChainBuilder where S.Element == QueryClause { - + public func appending( + contentsOf clauses: S + ) -> QueryChainBuilder where S.Element == QueryClause { + return self.queryChain(appending: clauses) } // MARK: Private - private func queryChain(appending clause: QueryClause) -> QueryChainBuilder { - + private func queryChain( + appending clause: QueryClause + ) -> QueryChainBuilder { + return .init( from: self.from, select: self.select, @@ -779,8 +882,10 @@ extension QueryChainBuilder { ) } - private func queryChain(appending clauses: S) -> QueryChainBuilder where S.Element == QueryClause { - + private func queryChain( + appending clauses: S + ) -> QueryChainBuilder where S.Element == QueryClause { + return .init( from: self.from, select: self.select, @@ -800,8 +905,10 @@ extension QueryChainBuilder where O: NSManagedObject { - parameter keyPath: a key path to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPath: KeyPath) -> QueryChainBuilder { - + public func groupBy( + _ keyPath: KeyPath + ) -> QueryChainBuilder { + return self.groupBy(GroupBy(keyPath)) } } @@ -817,8 +924,10 @@ extension QueryChainBuilder where O: CoreStoreObject { - parameter clause: a `Where` clause to add to the query builder - returns: a new `QueryChainBuilder` containing the `Where` clause */ - public func `where`(_ clause: (O) -> T) -> QueryChainBuilder { - + public func `where`( + _ clause: (O) -> T + ) -> QueryChainBuilder { + return self.queryChain(appending: clause(O.meta)) } @@ -828,8 +937,10 @@ extension QueryChainBuilder where O: CoreStoreObject { - parameter keyPath: a key path to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPath: KeyPath.Stored>) -> QueryChainBuilder { - + public func groupBy( + _ keyPath: KeyPath.Stored> + ) -> QueryChainBuilder { + return self.groupBy(GroupBy(keyPath)) } @@ -839,8 +950,10 @@ extension QueryChainBuilder where O: CoreStoreObject { - parameter keyPath: a key path to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPath: KeyPath.Virtual>) -> QueryChainBuilder { - + public func groupBy( + _ keyPath: KeyPath.Virtual> + ) -> QueryChainBuilder { + return self.groupBy(GroupBy(keyPath)) } @@ -850,8 +963,10 @@ extension QueryChainBuilder where O: CoreStoreObject { - parameter keyPath: a key path to group the query results with - returns: a new `QueryChainBuilder` containing the `GroupBy` clause */ - public func groupBy(_ keyPath: KeyPath.Coded>) -> QueryChainBuilder { - + public func groupBy( + _ keyPath: KeyPath.Coded> + ) -> QueryChainBuilder { + return self.groupBy(GroupBy(keyPath)) } } @@ -867,8 +982,10 @@ extension SectionMonitorChainBuilder { - parameter clause: a `Where` clause to add to the fetch builder - returns: a new `SectionMonitorChainBuilder` containing the `Where` clause */ - public func `where`(_ clause: Where) -> SectionMonitorChainBuilder { - + public func `where`( + _ clause: Where + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: clause) } @@ -878,8 +995,10 @@ extension SectionMonitorChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `AND`s the specified `Where` clauses */ - public func `where`(combineByAnd clauses: Where...) -> SectionMonitorChainBuilder { - + public func `where`( + combineByAnd clauses: Where... + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: clauses.combinedByAnd()) } @@ -889,8 +1008,10 @@ extension SectionMonitorChainBuilder { - parameter clauses: the `Where` clauses to create a `FetchChainBuilder` with - returns: a `FetchChainBuilder` that `OR`s the specified `Where` clauses */ - public func `where`(combineByOr clauses: Where...) -> SectionMonitorChainBuilder { - + public func `where`( + combineByOr clauses: Where... + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: clauses.combinedByOr()) } @@ -901,8 +1022,11 @@ extension SectionMonitorChainBuilder { - parameter args: the arguments for `format` - returns: a new `SectionMonitorChainBuilder` containing the `Where` clause */ - public func `where`(format: String, _ args: Any...) -> SectionMonitorChainBuilder { - + public func `where`( + format: String, + _ args: Any... + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: Where(format, argumentArray: args)) } @@ -913,8 +1037,11 @@ extension SectionMonitorChainBuilder { - parameter argumentArray: the arguments for `format` - returns: a new `SectionMonitorChainBuilder` containing the `Where` clause */ - public func `where`(format: String, argumentArray: [Any]?) -> SectionMonitorChainBuilder { - + public func `where`( + format: String, + argumentArray: [Any]? + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: Where(format, argumentArray: argumentArray)) } @@ -924,7 +1051,9 @@ extension SectionMonitorChainBuilder { - parameter clause: the `OrderBy` clause to add - returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ clause: OrderBy) -> SectionMonitorChainBuilder { + public func orderBy( + _ clause: OrderBy + ) -> SectionMonitorChainBuilder { return self.sectionMonitorChain(appending: clause) } @@ -936,8 +1065,11 @@ extension SectionMonitorChainBuilder { - parameter sortKeys: a series of other `SortKey`s - returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKey: OrderBy.SortKey, _ sortKeys: OrderBy.SortKey...) -> SectionMonitorChainBuilder { - + public func orderBy( + _ sortKey: OrderBy.SortKey, + _ sortKeys: OrderBy.SortKey... + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: OrderBy([sortKey] + sortKeys)) } @@ -947,7 +1079,9 @@ extension SectionMonitorChainBuilder { - parameter sortKeys: a series of `SortKey`s - returns: a new `SectionMonitorChainBuilder` containing the `OrderBy` clause */ - public func orderBy(_ sortKeys: [OrderBy.SortKey]) -> SectionMonitorChainBuilder { + public func orderBy( + _ sortKeys: [OrderBy.SortKey] + ) -> SectionMonitorChainBuilder { return self.sectionMonitorChain(appending: OrderBy(sortKeys)) } @@ -958,8 +1092,10 @@ extension SectionMonitorChainBuilder { - parameter fetchRequest: the block to customize the `NSFetchRequest` - returns: a new `SectionMonitorChainBuilder` containing the `Tweak` clause */ - public func tweak(_ fetchRequest: @escaping (NSFetchRequest) -> Void) -> SectionMonitorChainBuilder { - + public func tweak( + _ fetchRequest: @escaping (NSFetchRequest) -> Void + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: Tweak(fetchRequest)) } @@ -969,8 +1105,10 @@ extension SectionMonitorChainBuilder { - parameter clause: the `QueryClause` to add to the `SectionMonitorChainBuilder` - returns: a new `SectionMonitorChainBuilder` containing the `QueryClause` */ - public func appending(_ clause: FetchClause) -> SectionMonitorChainBuilder { - + public func appending( + _ clause: FetchClause + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: clause) } @@ -980,16 +1118,20 @@ extension SectionMonitorChainBuilder { - parameter clauses: the `QueryClause`s to add to the `SectionMonitorChainBuilder` - returns: a new `SectionMonitorChainBuilder` containing the `QueryClause`s */ - public func appending(contentsOf clauses: S) -> SectionMonitorChainBuilder where S.Element == FetchClause { - + public func appending( + contentsOf clauses: S + ) -> SectionMonitorChainBuilder where S.Element == FetchClause { + return self.sectionMonitorChain(appending: clauses) } // MARK: Private - private func sectionMonitorChain(appending clause: FetchClause) -> SectionMonitorChainBuilder { - + private func sectionMonitorChain( + appending clause: FetchClause + ) -> SectionMonitorChainBuilder { + return .init( from: self.from, sectionBy: self.sectionBy, @@ -997,8 +1139,10 @@ extension SectionMonitorChainBuilder { ) } - private func sectionMonitorChain(appending clauses: S) -> SectionMonitorChainBuilder where S.Element == FetchClause { - + private func sectionMonitorChain( + appending clauses: S + ) -> SectionMonitorChainBuilder where S.Element == FetchClause { + return .init( from: self.from, sectionBy: self.sectionBy, @@ -1018,8 +1162,10 @@ extension SectionMonitorChainBuilder where O: CoreStoreObject { - parameter clause: a `Where` clause to add to the fetch builder - returns: a new `SectionMonitorChainBuilder` containing the `Where` clause */ - public func `where`(_ clause: (O) -> T) -> SectionMonitorChainBuilder { - + public func `where`( + _ clause: (O) -> T + ) -> SectionMonitorChainBuilder { + return self.sectionMonitorChain(appending: clause(O.meta)) } } diff --git a/Sources/From.swift b/Sources/From.swift index cc9de01..f00fb2e 100644 --- a/Sources/From.swift +++ b/Sources/From.swift @@ -60,7 +60,10 @@ public struct From { */ public init() { - self.init(entityClass: O.self, configurations: nil) + self.init( + entityClass: O.self, + configurations: nil + ) } /** @@ -70,9 +73,14 @@ public struct From { ``` - parameter entity: the associated `NSManagedObject` or `CoreStoreObject` type */ - public init(_ entity: O.Type) { - - self.init(entityClass: entity, configurations: nil) + public init( + _ entity: O.Type + ) { + + self.init( + entityClass: entity, + configurations: nil + ) } /** @@ -83,9 +91,15 @@ public struct From { - parameter configuration: the `NSPersistentStore` configuration name to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject` or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. - parameter otherConfigurations: an optional list of other configuration names to associate objects from (see `configuration` parameter) */ - public init(_ configuration: ModelConfiguration, _ otherConfigurations: ModelConfiguration...) { - - self.init(entityClass: O.self, configurations: [configuration] + otherConfigurations) + public init( + _ configuration: ModelConfiguration, + _ otherConfigurations: ModelConfiguration... + ) { + + self.init( + entityClass: O.self, + configurations: [configuration] + otherConfigurations + ) } /** @@ -95,9 +109,14 @@ public struct From { ``` - parameter configurations: a list of `NSPersistentStore` configuration names to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject` or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. */ - public init(_ configurations: [ModelConfiguration]) { - - self.init(entityClass: O.self, configurations: configurations) + public init( + _ configurations: [ModelConfiguration] + ) { + + self.init( + entityClass: O.self, + configurations: configurations + ) } /** @@ -109,9 +128,16 @@ public struct From { - parameter configuration: the `NSPersistentStore` configuration name to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject` or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. - parameter otherConfigurations: an optional list of other configuration names to associate objects from (see `configuration` parameter) */ - public init(_ entity: O.Type, _ configuration: ModelConfiguration, _ otherConfigurations: ModelConfiguration...) { - - self.init(entityClass: entity, configurations: [configuration] + otherConfigurations) + public init( + _ entity: O.Type, + _ configuration: ModelConfiguration, + _ otherConfigurations: ModelConfiguration... + ) { + + self.init( + entityClass: entity, + configurations: [configuration] + otherConfigurations + ) } /** @@ -122,9 +148,15 @@ public struct From { - parameter entity: the associated `NSManagedObject` or `CoreStoreObject` type - parameter configurations: a list of `NSPersistentStore` configuration names to associate objects from. This parameter is required if multiple configurations contain the created `NSManagedObject` or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. */ - public init(_ entity: O.Type, _ configurations: [ModelConfiguration]) { - - self.init(entityClass: entity, configurations: configurations) + public init( + _ entity: O.Type, + _ configurations: [ModelConfiguration] + ) { + + self.init( + entityClass: entity, + configurations: configurations + ) } @@ -132,14 +164,24 @@ public struct From { internal let findPersistentStores: (_ context: NSManagedObjectContext) -> [NSPersistentStore]? - internal init(entityClass: O.Type, configurations: [ModelConfiguration]?, findPersistentStores: @escaping (_ context: NSManagedObjectContext) -> [NSPersistentStore]?) { - + internal init( + entityClass: O.Type, + configurations: [ModelConfiguration]?, + findPersistentStores: @escaping ( + _ context: NSManagedObjectContext + ) -> [NSPersistentStore]? + ) { + self.entityClass = entityClass self.configurations = configurations self.findPersistentStores = findPersistentStores } - internal func applyToFetchRequest(_ fetchRequest: Internals.CoreStoreFetchRequest, context: NSManagedObjectContext, applyAffectedStores: Bool = true) throws { + internal func applyToFetchRequest( + _ fetchRequest: Internals.CoreStoreFetchRequest, + context: NSManagedObjectContext, + applyAffectedStores: Bool = true + ) throws(CoreStoreError) { guard let parentStack = context.parentStack else { @@ -158,7 +200,7 @@ public struct From { try self.applyAffectedStoresForFetchedRequest(fetchRequest, context: context) } - catch let error as CoreStoreError { + catch { Internals.log( error, @@ -166,14 +208,13 @@ public struct From { ) throw error } - catch { - - throw error - } } - internal func applyAffectedStoresForFetchedRequest(_ fetchRequest: Internals.CoreStoreFetchRequest, context: NSManagedObjectContext) throws { - + internal func applyAffectedStoresForFetchedRequest( + _ fetchRequest: Internals.CoreStoreFetchRequest, + context: NSManagedObjectContext + ) throws(CoreStoreError) { + let stores = self.findPersistentStores(context) fetchRequest.affectedStores = stores if stores?.isEmpty == false { @@ -186,8 +227,11 @@ public struct From { // MARK: Private - private init(entityClass: O.Type, configurations: [ModelConfiguration]?) { - + private init( + entityClass: O.Type, + configurations: [ModelConfiguration]? + ) { + self.entityClass = entityClass self.configurations = configurations diff --git a/Sources/ImportableObject.swift b/Sources/ImportableObject.swift index e447c5f..a34916c 100644 --- a/Sources/ImportableObject.swift +++ b/Sources/ImportableObject.swift @@ -66,15 +66,21 @@ public protocol ImportableObject: DynamicObject { - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. - returns: `true` if an object should be created from `source`. Return `false` to ignore. */ - static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool - + static func shouldInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool + /** Implements the actual importing of data from `source`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importObjects(:sourceArray:)` call to be cancelled. - parameter source: the object to import from - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. */ - func didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws + func didInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) throws(any Swift.Error) } @@ -82,8 +88,11 @@ public protocol ImportableObject: DynamicObject { extension ImportableObject { - public static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool { - + public static func shouldInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool { + return true } } diff --git a/Sources/ImportableUniqueObject.swift b/Sources/ImportableUniqueObject.swift index 65924c6..1ebd5cd 100644 --- a/Sources/ImportableUniqueObject.swift +++ b/Sources/ImportableUniqueObject.swift @@ -78,8 +78,11 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable { - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. - returns: `true` if an object should be created from `source`. Return `false` to ignore. */ - static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool - + static func shouldInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool + /** Return `true` if an object should be updated from `source`. Return `false` to ignore and skip `source`. The default implementation returns `true`. @@ -87,8 +90,11 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable { - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. - returns: `true` if an object should be updated from `source`. Return `false` to ignore. */ - static func shouldUpdate(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool - + static func shouldUpdate( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool + /** Return the unique ID as extracted from `source`. This method is called before `shouldInsert(from:in:)` or `shouldUpdate(from:in:)`. Return `nil` to skip importing from `source`. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled. @@ -96,23 +102,32 @@ public protocol ImportableUniqueObject: ImportableObject, Hashable { - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. - returns: the unique ID as extracted from `source`, or `nil` to skip importing from `source`. */ - static func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -> UniqueIDType? - + static func uniqueID( + from source: ImportSource, + in transaction: BaseDataTransaction + ) throws(any Swift.Error) -> UniqueIDType? + /** Implements the actual importing of data from `source`. This method is called just after the object is created and assigned its unique ID as returned from `uniqueID(from:in:)`. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled. The default implementation simply calls `update(from:in:)`. - parameter source: the object to import from - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. */ - func didInsert(from source: ImportSource, in transaction: BaseDataTransaction) throws - + func didInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) throws(any Swift.Error) + /** Implements the actual importing of data from `source`. This method is called just after the existing object is fetched using its unique ID. Implementers should pull values from `source` and assign them to the receiver's attributes. Note that throwing from this method will cause subsequent imports that are part of the same `importUniqueObjects(:sourceArray:)` call to be cancelled. - parameter source: the object to import from - parameter transaction: the transaction that invoked the import. Use the transaction to fetch or create related objects if needed. */ - func update(from source: ImportSource, in transaction: BaseDataTransaction) throws + func update( + from source: ImportSource, + in transaction: BaseDataTransaction + ) throws(any Swift.Error) } @@ -146,18 +161,27 @@ extension ImportableUniqueObject where UniqueIDType.QueryableNativeType: CoreDat extension ImportableUniqueObject { - public static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool { - + public static func shouldInsert( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool { + return Self.shouldUpdate(from: source, in: transaction) } - public static func shouldUpdate(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool{ - + public static func shouldUpdate( + from source: ImportSource, + in transaction: BaseDataTransaction + ) -> Bool { + return true } - public func didInsert(from source: Self.ImportSource, in transaction: BaseDataTransaction) throws { - + public func didInsert( + from source: Self.ImportSource, + in transaction: BaseDataTransaction + ) throws(any Swift.Error) { + try self.update(from: source, in: transaction) } } diff --git a/Sources/InferredSchemaMappingProvider.swift b/Sources/InferredSchemaMappingProvider.swift index eb79167..fb771fb 100644 --- a/Sources/InferredSchemaMappingProvider.swift +++ b/Sources/InferredSchemaMappingProvider.swift @@ -53,7 +53,14 @@ public final class InferredSchemaMappingProvider: Hashable, SchemaMappingProvide // MARK: SchemaMappingProvider - public func cs_createMappingModel(from sourceSchema: DynamicSchema, to destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) { + public func cs_createMappingModel( + from sourceSchema: DynamicSchema, + to destinationSchema: DynamicSchema, + storage: LocalStorage + ) throws(CoreStoreError) -> ( + mappingModel: NSMappingModel, + migrationType: MigrationType + ) { let sourceModel = sourceSchema.rawModel() let destinationModel = destinationSchema.rawModel() diff --git a/Sources/Internals.CoreStoreFetchedResultsController.swift b/Sources/Internals.CoreStoreFetchedResultsController.swift index bda6c6f..c0d8953 100644 --- a/Sources/Internals.CoreStoreFetchedResultsController.swift +++ b/Sources/Internals.CoreStoreFetchedResultsController.swift @@ -77,8 +77,8 @@ extension Internals { } @nonobjc - internal func performFetchFromSpecifiedStores() throws { - + internal func performFetchFromSpecifiedStores() throws(any Swift.Error) { + try self.reapplyAffectedStores(self.typedFetchRequest, self.managedObjectContext) try self.performFetch() @@ -103,6 +103,9 @@ extension Internals { // MARK: Private @nonobjc - private let reapplyAffectedStores: (_ fetchRequest: Internals.CoreStoreFetchRequest, _ context: NSManagedObjectContext) throws -> Void + private let reapplyAffectedStores: ( + _ fetchRequest: Internals.CoreStoreFetchRequest, + _ context: NSManagedObjectContext + ) throws(any Swift.Error) -> Void } } diff --git a/Sources/Internals.DiffableDataUIDispatcher.swift b/Sources/Internals.DiffableDataUIDispatcher.swift index 9c7f52c..f41ad16 100644 --- a/Sources/Internals.DiffableDataUIDispatcher.swift +++ b/Sources/Internals.DiffableDataUIDispatcher.swift @@ -106,11 +106,11 @@ extension Internals { } } - #if os(watchOS) - +#if os(watchOS) || !canImport(QuartzCore) + performDiffingUpdates() - #else +#else CATransaction.begin() @@ -122,8 +122,7 @@ extension Internals { CATransaction.commit() - - #endif +#endif } } diff --git a/Sources/Internals.FetchedDiffableDataSourceSnapshotDelegate.swift b/Sources/Internals.FetchedDiffableDataSourceSnapshotDelegate.swift index c8d6375..4e671c8 100644 --- a/Sources/Internals.FetchedDiffableDataSourceSnapshotDelegate.swift +++ b/Sources/Internals.FetchedDiffableDataSourceSnapshotDelegate.swift @@ -91,11 +91,14 @@ extension Internals { // MARK: NSFetchedResultsControllerDelegate @objc - dynamic func controllerDidChangeContent(_ controller: NSFetchedResultsController) { + dynamic func controllerDidChangeContent( + _ controller: NSFetchedResultsController + ) { var snapshot = Internals.DiffableDataSourceSnapshot( sections: controller.sections ?? [], - sectionIndexTransformer: self.handler.map({ $0.sectionIndexTransformer }) ?? { _ in nil }, + sectionIndexTransformer: self.handler + .map({ $0.sectionIndexTransformer }) ?? { _ in nil }, fetchOffset: controller.fetchRequest.fetchOffset, fetchLimit: controller.fetchRequest.fetchLimit ) @@ -117,13 +120,24 @@ extension Internals { } @objc - dynamic func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { + dynamic func controller( + _ controller: NSFetchedResultsController, + didChange anObject: Any, + at indexPath: IndexPath?, + for type: NSFetchedResultsChangeType, + newIndexPath: IndexPath? + ) { let object = anObject as! NSManagedObject self.reloadedItemIDs.append(object.objectID) } - func controller(_ controller: NSFetchedResultsController, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { + func controller( + _ controller: NSFetchedResultsController, + didChange sectionInfo: NSFetchedResultsSectionInfo, + atSectionIndex sectionIndex: Int, + for type: NSFetchedResultsChangeType + ) { self.reloadedSectionIDs.append(sectionInfo.name) } diff --git a/Sources/Internals.FetchedResultsControllerDelegate.swift b/Sources/Internals.FetchedResultsControllerDelegate.swift index 15da8a7..d7401bb 100644 --- a/Sources/Internals.FetchedResultsControllerDelegate.swift +++ b/Sources/Internals.FetchedResultsControllerDelegate.swift @@ -96,7 +96,9 @@ extension Internals { // MARK: NSFetchedResultsControllerDelegate @objc - dynamic func controllerWillChangeContent(_ controller: NSFetchedResultsController) { + dynamic func controllerWillChangeContent( + _ controller: NSFetchedResultsController + ) { self.taskGroup.enter() guard self.enabled else { @@ -107,7 +109,9 @@ extension Internals { } @objc - dynamic func controllerDidChangeContent(_ controller: NSFetchedResultsController) { + dynamic func controllerDidChangeContent( + _ controller: NSFetchedResultsController + ) { defer { @@ -121,7 +125,13 @@ extension Internals { } @objc - dynamic func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { + dynamic func controller( + _ controller: NSFetchedResultsController, + didChange anObject: Any, + at indexPath: IndexPath?, + for type: NSFetchedResultsChangeType, + newIndexPath: IndexPath? + ) { guard self.enabled else { @@ -137,7 +147,12 @@ extension Internals { } @objc - dynamic func controller(_ controller: NSFetchedResultsController, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { + dynamic func controller( + _ controller: NSFetchedResultsController, + didChange sectionInfo: NSFetchedResultsSectionInfo, + atSectionIndex sectionIndex: Int, + for type: NSFetchedResultsChangeType + ) { guard self.enabled else { diff --git a/Sources/Internals.MigrationManager.swift b/Sources/Internals.MigrationManager.swift index 4d630e9..055bfec 100644 --- a/Sources/Internals.MigrationManager.swift +++ b/Sources/Internals.MigrationManager.swift @@ -55,11 +55,18 @@ extension Internals { // MARK: NSMigrationManager - init(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, progress: Progress) { + init( + sourceModel: NSManagedObjectModel, + destinationModel: NSManagedObjectModel, + progress: Progress + ) { self.progress = progress - super.init(sourceModel: sourceModel, destinationModel: destinationModel) + super.init( + sourceModel: sourceModel, + destinationModel: destinationModel + ) } diff --git a/Sources/Internals.NotificationObserver.swift b/Sources/Internals.NotificationObserver.swift index 014a72e..42a4247 100644 --- a/Sources/Internals.NotificationObserver.swift +++ b/Sources/Internals.NotificationObserver.swift @@ -38,7 +38,12 @@ extension Internals { let observer: NSObjectProtocol - init(notificationName: Notification.Name, object: Any?, queue: OperationQueue? = nil, closure: @escaping (_ note: Notification) -> Void) { + init( + notificationName: Notification.Name, + object: Any?, + queue: OperationQueue? = nil, + closure: @escaping (_ note: Notification) -> Void + ) { self.observer = NotificationCenter.default.addObserver( forName: notificationName, diff --git a/Sources/Internals.SharedNotificationObserver.swift b/Sources/Internals.SharedNotificationObserver.swift index 7c4d177..ebdc3de 100644 --- a/Sources/Internals.SharedNotificationObserver.swift +++ b/Sources/Internals.SharedNotificationObserver.swift @@ -35,7 +35,12 @@ extension Internals { // MARK: Internal - internal init(notificationName: Notification.Name, object: Any?, queue: OperationQueue? = nil, sharedValue: @escaping (_ note: Notification) -> T) { + internal init( + notificationName: Notification.Name, + object: Any?, + queue: OperationQueue? = nil, + sharedValue: @escaping (_ note: Notification) -> T + ) { self.observer = NotificationCenter.default.addObserver( forName: notificationName, @@ -59,9 +64,15 @@ extension Internals { self.observers.removeAllObjects() } - internal func addObserver(_ observer: U, closure: @escaping (T) -> Void) { + internal func addObserver( + _ observer: U, + closure: @escaping (T) -> Void + ) { - self.observers.setObject(Closure(closure), forKey: observer) + self.observers.setObject( + Closure(closure), + forKey: observer + ) } internal func removeObserver(_ observer: U) { diff --git a/Sources/Internals.swift b/Sources/Internals.swift index 0c48a84..501f5e9 100644 --- a/Sources/Internals.swift +++ b/Sources/Internals.swift @@ -39,8 +39,6 @@ internal enum Internals { return object_getClass(instance) as! T.Type } - // MARK: Associated Objects - @inline(__always) internal static func getAssociatedObjectForKey(_ key: UnsafeRawPointer, inObject object: Any) -> T? { @@ -123,4 +121,47 @@ internal enum Internals { return closure() } + + @inline(__always) + internal static func autoreleasepool( + _ closure: () -> T + ) -> T { + + return ObjectiveC.autoreleasepool(invoking: closure) + } + + @inline(__always) + internal static func autoreleasepool( + _ closure: () throws(any Swift.Error) -> T + ) throws(any Swift.Error) -> T { + + return try ObjectiveC.autoreleasepool(invoking: closure) + } + + @inline(__always) + internal static func autoreleasepool( + _ closure: () throws(CoreStoreError) -> T + ) throws(CoreStoreError) -> T { + + do { + + return try ObjectiveC.autoreleasepool(invoking: closure) + } + catch { + + throw CoreStoreError(error) + } + } + + @inline(__always) + internal static func withCheckedThrowingContinuation( + function: String = #function, + _ body: (CheckedContinuation) -> Void + ) async throws(any Swift.Error) -> T { + + return try await _Concurrency.withCheckedThrowingContinuation( + function: function, + body + ) + } } diff --git a/Sources/Into.swift b/Sources/Into.swift index b3e97fd..10b675c 100644 --- a/Sources/Into.swift +++ b/Sources/Into.swift @@ -60,7 +60,11 @@ public struct Into: Hashable { */ public init() { - self.init(entityClass: O.self, configuration: nil, inferStoreIfPossible: true) + self.init( + entityClass: O.self, + configuration: nil, + inferStoreIfPossible: true + ) } /** @@ -70,9 +74,15 @@ public struct Into: Hashable { ``` - parameter entity: the `NSManagedObject` or `CoreStoreObject` type to be created */ - public init(_ entity: O.Type) { - - self.init(entityClass: entity, configuration: nil, inferStoreIfPossible: true) + public init( + _ entity: O.Type + ) { + + self.init( + entityClass: entity, + configuration: nil, + inferStoreIfPossible: true + ) } /** @@ -82,9 +92,15 @@ public struct Into: Hashable { ``` - parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. */ - public init(_ configuration: ModelConfiguration) { - - self.init(entityClass: O.self, configuration: configuration, inferStoreIfPossible: false) + public init( + _ configuration: ModelConfiguration + ) { + + self.init( + entityClass: O.self, + configuration: configuration, + inferStoreIfPossible: false + ) } /** @@ -95,9 +111,16 @@ public struct Into: Hashable { - parameter entity: the `NSManagedObject` or `CoreStoreObject` type to be created - parameter configuration: the `NSPersistentStore` configuration name to associate the object to. This parameter is required if multiple configurations contain the created `NSManagedObject`'s or `CoreStoreObject`'s entity type. Set to `nil` to use the default configuration. */ - public init(_ entity: O.Type, _ configuration: ModelConfiguration) { - - self.init(entityClass: entity, configuration: configuration, inferStoreIfPossible: false) + public init( + _ entity: O.Type, + _ configuration: ModelConfiguration + ) { + + self.init( + entityClass: entity, + configuration: configuration, + inferStoreIfPossible: false + ) } @@ -125,8 +148,12 @@ public struct Into: Hashable { internal let inferStoreIfPossible: Bool - internal init(entityClass: O.Type, configuration: ModelConfiguration, inferStoreIfPossible: Bool) { - + internal init( + entityClass: O.Type, + configuration: ModelConfiguration, + inferStoreIfPossible: Bool + ) { + self.entityClass = entityClass self.configuration = configuration self.inferStoreIfPossible = inferStoreIfPossible diff --git a/Sources/KeyPath+Querying.swift b/Sources/KeyPath+Querying.swift index e916213..6f67009 100644 --- a/Sources/KeyPath+Querying.swift +++ b/Sources/KeyPath+Querying.swift @@ -35,9 +35,15 @@ import Foundation let person = dataStack.fetchOne(From().where(\.nickname == "John")) ``` */ -public func == (_ keyPath: KeyPath, _ value: V) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: value) +public func == ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -46,9 +52,15 @@ public func == (_ key let person = dataStack.fetchOne(From().where(\.nickname != "John")) ``` */ -public func != (_ keyPath: KeyPath, _ value: V) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: value) +public func != ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -57,9 +69,15 @@ public func != (_ key let dog = dataStack.fetchOne(From().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath) -> Where where S.Iterator.Element == V { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath +) -> Where where S.Iterator.Element == V { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } @@ -71,9 +89,15 @@ public func ~= ().where(\.nickname == "John")) ``` */ -public func == (_ keyPath: KeyPath>, _ value: V?) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: value) +public func == ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -82,9 +106,15 @@ public func == (_ key let person = dataStack.fetchOne(From().where(\.nickname != "John")) ``` */ -public func != (_ keyPath: KeyPath>, _ value: V?) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: value) +public func != ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -93,9 +123,15 @@ public func != (_ key let dog = dataStack.fetchOne(From().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath>) -> Where where S.Iterator.Element == V { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath> +) -> Where where S.Iterator.Element == V { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } @@ -107,9 +143,16 @@ public func ~= ().where(\.age < 20)) ``` */ -public func < (_ keyPath: KeyPath, _ value: V) -> Where { - - return Where("%K < %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) +public func < ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return Where( + "%K < %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } /** @@ -118,9 +161,16 @@ public func < (_ key let person = dataStack.fetchOne(From().where(\.age > 20)) ``` */ -public func > (_ keyPath: KeyPath, _ value: V) -> Where { - - return Where("%K > %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) +public func > ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return Where( + "%K > %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } /** @@ -129,9 +179,16 @@ public func > (_ key let person = dataStack.fetchOne(From().where(\.age <= 20)) ``` */ -public func <= (_ keyPath: KeyPath, _ value: V) -> Where { - - return Where("%K <= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) +public func <= ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return Where( + "%K <= %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } /** @@ -140,9 +197,16 @@ public func <= (_ ke let person = dataStack.fetchOne(From().where(\.age >= 20)) ``` */ -public func >= (_ keyPath: KeyPath, _ value: V) -> Where { - - return Where("%K >= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) +public func >= ( + _ keyPath: KeyPath, + _ value: V +) -> Where { + + return Where( + "%K >= %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } @@ -154,15 +218,25 @@ public func >= (_ ke let person = dataStack.fetchOne(From().where(\.age < 20)) ``` */ -public func < (_ keyPath: KeyPath>, _ value: V?) -> Where { - +public func < ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + if let value = value { - return Where("%K < %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) + return Where( + "%K < %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } else { - return Where("%K < nil", keyPath._kvcKeyPathString!) + return Where( + "%K < nil", + keyPath._kvcKeyPathString! + ) } } @@ -172,15 +246,25 @@ public func < (_ key let person = dataStack.fetchOne(From().where(\.age > 20)) ``` */ -public func > (_ keyPath: KeyPath>, _ value: V?) -> Where { - +public func > ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + if let value = value { - return Where("%K > %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) + return Where( + "%K > %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } else { - return Where("%K > nil", keyPath._kvcKeyPathString!) + return Where( + "%K > nil", + keyPath._kvcKeyPathString! + ) } } @@ -190,15 +274,25 @@ public func > (_ key let person = dataStack.fetchOne(From().where(\.age <= 20)) ``` */ -public func <= (_ keyPath: KeyPath>, _ value: V?) -> Where { - +public func <= ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + if let value = value { - return Where("%K <= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) + return Where( + "%K <= %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } else { - return Where("%K <= nil", keyPath._kvcKeyPathString!) + return Where( + "%K <= nil", + keyPath._kvcKeyPathString! + ) } } @@ -208,15 +302,25 @@ public func <= (_ ke let person = dataStack.fetchOne(From().where(\.age >= 20)) ``` */ -public func >= (_ keyPath: KeyPath>, _ value: V?) -> Where { - +public func >= ( + _ keyPath: KeyPath>, + _ value: V? +) -> Where { + if let value = value { - return Where("%K >= %@", keyPath._kvcKeyPathString!, value.cs_toQueryableNativeType()) + return Where( + "%K >= %@", + keyPath._kvcKeyPathString!, + value.cs_toQueryableNativeType() + ) } else { - return Where("%K >= nil", keyPath._kvcKeyPathString!) + return Where( + "%K >= nil", + keyPath._kvcKeyPathString! + ) } } @@ -229,9 +333,15 @@ public func >= (_ ke let dog = dataStack.fetchOne(From().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath, _ object: D) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: object) +public func == ( + _ keyPath: KeyPath, + _ object: D +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: object + ) } /** @@ -240,9 +350,15 @@ public func == (_ keyPath: KeyPath let dog = dataStack.fetchOne(From().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath, _ object: D) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: object) +public func != ( + _ keyPath: KeyPath, + _ object: D +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: object + ) } /** @@ -251,9 +367,15 @@ public func != (_ keyPath: KeyPath let dog = dataStack.fetchOne(From().where([john, bob, joe] ~= \.master)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath) -> Where where S.Iterator.Element == D { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath +) -> Where where S.Iterator.Element == D { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } /** @@ -262,9 +384,15 @@ public func ~= (_ sequence: let dog = dataStack.fetchOne(From().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath, _ objectID: NSManagedObjectID) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: objectID) +public func == ( + _ keyPath: KeyPath, + _ objectID: NSManagedObjectID +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: objectID + ) } /** @@ -273,9 +401,15 @@ public func == (_ keyPath: KeyPath let dog = dataStack.fetchOne(From().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath, _ object: O) -> Where where O.ObjectType: NSManagedObject { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: object.cs_id()) +public func == ( + _ keyPath: KeyPath, + _ object: O +) -> Where where O.ObjectType: NSManagedObject { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: object.cs_id() + ) } /** @@ -284,9 +418,15 @@ public func == (_ keyPath: KeyPath< let dog = dataStack.fetchOne(From().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath, _ objectID: NSManagedObjectID) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: objectID) +public func != ( + _ keyPath: KeyPath, + _ objectID: NSManagedObjectID +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: objectID + ) } /** @@ -295,9 +435,15 @@ public func != (_ keyPath: KeyPath let dog = dataStack.fetchOne(From().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath, _ object: O) -> Where where O.ObjectType: NSManagedObject { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: object.cs_id()) +public func != ( + _ keyPath: KeyPath, + _ object: O +) -> Where where O.ObjectType: NSManagedObject { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: object.cs_id() + ) } /** @@ -306,9 +452,15 @@ public func != (_ keyPath: KeyPath< let dog = dataStack.fetchOne(From().where([john, bob, joe] ~= \.master)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath) -> Where where S.Iterator.Element == NSManagedObjectID { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath +) -> Where where S.Iterator.Element == NSManagedObjectID { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } @@ -320,9 +472,15 @@ public func ~= (_ sequence: let dog = dataStack.fetchOne(From().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath>, _ object: D?) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: object) +public func == ( + _ keyPath: KeyPath>, + _ object: D? +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: object + ) } /** @@ -331,9 +489,15 @@ public func == (_ keyPath: KeyPath().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath>, _ object: O?) -> Where where O.ObjectType: NSManagedObject { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: object?.cs_toRaw()) +public func == ( + _ keyPath: KeyPath>, + _ object: O? +) -> Where where O.ObjectType: NSManagedObject { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: object?.cs_toRaw() + ) } /** @@ -342,9 +506,15 @@ public func == (_ keyPath: KeyPath< let dog = dataStack.fetchOne(From().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath>, _ object: D?) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: object) +public func != ( + _ keyPath: KeyPath>, + _ object: D? +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: object + ) } /** @@ -353,9 +523,15 @@ public func != (_ keyPath: KeyPath().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath>, _ object: O?) -> Where where O.ObjectType: NSManagedObject { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: object?.cs_toRaw()) +public func != ( + _ keyPath: KeyPath>, + _ object: O? +) -> Where where O.ObjectType: NSManagedObject { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: object?.cs_toRaw() + ) } /** @@ -364,9 +540,15 @@ public func != (_ keyPath: KeyPath< let dog = dataStack.fetchOne(From().where([john, bob, joe] ~= \.master)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath>) -> Where where S.Iterator.Element == D { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath> +) -> Where where S.Iterator.Element == D { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } /** @@ -375,9 +557,15 @@ public func ~= (_ sequence: let dog = dataStack.fetchOne(From().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath>, _ objectID: NSManagedObjectID) -> Where { - - return Where(keyPath._kvcKeyPathString!, isEqualTo: objectID) +public func == ( + _ keyPath: KeyPath>, + _ objectID: NSManagedObjectID +) -> Where { + + return Where( + keyPath._kvcKeyPathString!, + isEqualTo: objectID + ) } /** @@ -386,9 +574,15 @@ public func == (_ keyPath: KeyPath().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath>, _ objectID: NSManagedObjectID) -> Where { - - return !Where(keyPath._kvcKeyPathString!, isEqualTo: objectID) +public func != ( + _ keyPath: KeyPath>, + _ objectID: NSManagedObjectID +) -> Where { + + return !Where( + keyPath._kvcKeyPathString!, + isEqualTo: objectID + ) } /** @@ -397,9 +591,15 @@ public func != (_ keyPath: KeyPath().where([john, bob, joe] ~= \.master)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath>) -> Where where S.Iterator.Element == NSManagedObjectID { - - return Where(keyPath._kvcKeyPathString!, isMemberOf: sequence) +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath> +) -> Where where S.Iterator.Element == NSManagedObjectID { + + return Where( + keyPath._kvcKeyPathString!, + isMemberOf: sequence + ) } @@ -411,9 +611,15 @@ public func ~= (_ sequence: let person = dataStack.fetchOne(From().where(\.$nickname == "John")) ``` */ -public func == (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func == ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return Where(keyPath, isEqualTo: value) + return Where( + keyPath, + isEqualTo: value + ) } /** @@ -422,9 +628,15 @@ public func == (_ keyPath: KeyPath.Stored>, _ valu let person = dataStack.fetchOne(From().where(\.$nickname != "John")) ``` */ -public func != (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func != ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return !Where(keyPath, isEqualTo: value) + return !Where( + keyPath, + isEqualTo: value + ) } /** @@ -433,9 +645,15 @@ public func != (_ keyPath: KeyPath.Stored>, _ valu let dog = dataStack.fetchOne(From().where(["Pluto", "Snoopy", "Scooby"] ~= \.nickname)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath.Stored>) -> Where where S.Iterator.Element == V { +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath.Stored> +) -> Where where S.Iterator.Element == V { - return Where(O.meta[keyPath: keyPath].keyPath, isMemberOf: sequence) + return Where( + O.meta[keyPath: keyPath].keyPath, + isMemberOf: sequence + ) } @@ -447,9 +665,16 @@ public func ~= (_ sequence: S, _ keyPath: KeyPath().where(\.$age < 20)) ``` */ -public func < (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func < ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return Where("%K < %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K < %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -458,9 +683,16 @@ public func < (_ keyPath: KeyPath.Stored< let person = dataStack.fetchOne(From().where(\.$age < 20)) ``` */ -public func < (_ keyPath: KeyPath.Stored>, _ value: V) -> Where where V.Wrapped: Comparable { +public func < ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where where V.Wrapped: Comparable { - return Where("%K < %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K < %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -469,9 +701,16 @@ public func < (_ keyPath: KeyPath. let person = dataStack.fetchOne(From().where(\.$age > 20)) ``` */ -public func > (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func > ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return Where("%K > %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K > %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -480,9 +719,16 @@ public func > (_ keyPath: KeyPath.Stored< let person = dataStack.fetchOne(From().where(\.$age > 20)) ``` */ -public func > (_ keyPath: KeyPath.Stored>, _ value: V) -> Where where V.Wrapped: Comparable { +public func > ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where where V.Wrapped: Comparable { - return Where("%K > %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K > %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -491,9 +737,16 @@ public func > (_ keyPath: KeyPath. let person = dataStack.fetchOne(From().where(\.$age <= 20)) ``` */ -public func <= (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func <= ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return Where("%K <= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K <= %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -502,9 +755,16 @@ public func <= (_ keyPath: KeyPath.Stored let person = dataStack.fetchOne(From().where(\.$age <= 20)) ``` */ -public func <= (_ keyPath: KeyPath.Stored>, _ value: V) -> Where where V.Wrapped: Comparable { +public func <= ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where where V.Wrapped: Comparable { - return Where("%K <= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K <= %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -513,9 +773,16 @@ public func <= (_ keyPath: KeyPath let person = dataStack.fetchOne(From().where(\.$age >= 20)) ``` */ -public func >= (_ keyPath: KeyPath.Stored>, _ value: V) -> Where { +public func >= ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where { - return Where("%K >= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K >= %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } /** @@ -524,9 +791,16 @@ public func >= (_ keyPath: KeyPath.Stored let person = dataStack.fetchOne(From().where(\.$age >= 20)) ``` */ -public func >= (_ keyPath: KeyPath.Stored>, _ value: V) -> Where where V.Wrapped: Comparable { +public func >= ( + _ keyPath: KeyPath.Stored>, + _ value: V +) -> Where where V.Wrapped: Comparable { - return Where("%K >= %@", O.meta[keyPath: keyPath].keyPath, value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType) + return Where( + "%K >= %@", + O.meta[keyPath: keyPath].keyPath, + value.cs_toFieldStoredNativeType() as! V.FieldStoredNativeType + ) } @@ -538,9 +812,15 @@ public func >= (_ keyPath: KeyPath let dog = dataStack.fetchOne(From().where(\.$master == john)) ``` */ -public func == (_ keyPath: KeyPath.Relationship>, _ object: D.DestinationObjectType?) -> Where { +public func == ( + _ keyPath: KeyPath.Relationship>, + _ object: D.DestinationObjectType? +) -> Where { - return Where(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) + return Where( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: object + ) } /** @@ -549,9 +829,15 @@ public func == (_ keyPath: KeyPath().where(\.master == john)) ``` */ -public func == (_ keyPath: KeyPath.Relationship>, _ object: R?) -> Where where D.DestinationObjectType == R.ObjectType { +public func == ( + _ keyPath: KeyPath.Relationship>, + _ object: R? +) -> Where where D.DestinationObjectType == R.ObjectType { - return Where(O.meta[keyPath: keyPath].keyPath, isEqualTo: object?.objectID()) + return Where( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: object?.objectID() + ) } /** @@ -560,9 +846,15 @@ public func == (_ key let dog = dataStack.fetchOne(From().where(\.$master != john)) ``` */ -public func != (_ keyPath: KeyPath.Relationship>, _ object: D.DestinationObjectType?) -> Where { +public func != ( + _ keyPath: KeyPath.Relationship>, + _ object: D.DestinationObjectType? +) -> Where { - return !Where(O.meta[keyPath: keyPath].keyPath, isEqualTo: object) + return !Where( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: object + ) } /** @@ -571,9 +863,15 @@ public func != (_ keyPath: KeyPath().where(\.master != john)) ``` */ -public func != (_ keyPath: KeyPath.Relationship>, _ object: R?) -> Where where D.DestinationObjectType == R.ObjectType { +public func != ( + _ keyPath: KeyPath.Relationship>, + _ object: R? +) -> Where where D.DestinationObjectType == R.ObjectType { - return !Where(O.meta[keyPath: keyPath].keyPath, isEqualTo: object?.objectID()) + return !Where( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: object?.objectID() + ) } /** @@ -582,9 +880,15 @@ public func != (_ key let dog = dataStack.fetchOne(From().where([john, bob, joe] ~= \.$master)) ``` */ -public func ~= (_ sequence: S, _ keyPath: KeyPath.Relationship>) -> Where where S.Iterator.Element == D.DestinationObjectType { +public func ~= ( + _ sequence: S, + _ keyPath: KeyPath.Relationship> +) -> Where where S.Iterator.Element == D.DestinationObjectType { - return Where(O.meta[keyPath: keyPath].keyPath, isMemberOf: sequence) + return Where( + O.meta[keyPath: keyPath].keyPath, + isMemberOf: sequence + ) } diff --git a/Sources/ListPublisher+Reactive.swift b/Sources/ListPublisher+Reactive.swift index 0dec65e..ee52497 100644 --- a/Sources/ListPublisher+Reactive.swift +++ b/Sources/ListPublisher+Reactive.swift @@ -95,8 +95,10 @@ extension ListPublisher.ReactiveNamespace { - parameter emitInitialValue: If `true`, the current value is immediately emitted to the first subscriber. If `false`, the event fires only starting the next `ListSnapshot` update. - returns: A `Publisher` that emits a `ListSnapshot` whenever changes occur in the `ListPublisher`. */ - public func snapshot(emitInitialValue: Bool = true) -> ListPublisher.SnapshotPublisher { - + public func snapshot( + emitInitialValue: Bool = true + ) -> ListPublisher.SnapshotPublisher { + return .init( listPublisher: self.base, emitInitialValue: emitInitialValue diff --git a/Sources/ListPublisher.SnapshotPublisher.swift b/Sources/ListPublisher.SnapshotPublisher.swift index 9793947..65e904f 100644 --- a/Sources/ListPublisher.SnapshotPublisher.swift +++ b/Sources/ListPublisher.SnapshotPublisher.swift @@ -52,8 +52,10 @@ extension ListPublisher { public typealias Output = ListSnapshot public typealias Failure = Never - public func receive(subscriber: S) where S.Input == Output, S.Failure == Failure { - + public func receive( + subscriber: S + ) where S.Input == Output, S.Failure == Failure { + subscriber.receive( subscription: ListSnapshotSubscription( publisher: self.listPublisher, diff --git a/Sources/ListPublisher.swift b/Sources/ListPublisher.swift index 4fedd23..ec9d435 100644 --- a/Sources/ListPublisher.swift +++ b/Sources/ListPublisher.swift @@ -186,7 +186,7 @@ public final class ListPublisher: Hashable { public func refetch( _ clauseChain: B, sourceIdentifier: Any? = nil - ) throws where B.ObjectType == O { + ) throws(any Swift.Error) where B.ObjectType == O { try self.refetch( from: clauseChain.from, @@ -215,7 +215,7 @@ public final class ListPublisher: Hashable { public func refetch( _ clauseChain: B, sourceIdentifier: Any? = nil - ) throws where B.ObjectType == O { + ) throws(any Swift.Error) where B.ObjectType == O { try self.refetch( from: clauseChain.from, @@ -343,7 +343,7 @@ public final class ListPublisher: Hashable { sectionBy: SectionBy?, applyFetchClauses: @escaping (_ fetchRequest: Internals.CoreStoreFetchRequest) -> Void, sourceIdentifier: Any? - ) throws { + ) throws(any Swift.Error) { let (newFetchedResultsController, newFetchedResultsControllerDelegate) = Self.recreateFetchedResultsController( context: self.fetchedResultsController.managedObjectContext, diff --git a/Sources/NSEntityDescription+Migration.swift b/Sources/NSEntityDescription+Migration.swift index d10aa4a..7f619da 100644 --- a/Sources/NSEntityDescription+Migration.swift +++ b/Sources/NSEntityDescription+Migration.swift @@ -32,7 +32,12 @@ import Foundation extension NSEntityDescription { @nonobjc - internal func cs_resolveAttributeNames() -> [String: (attribute: NSAttributeDescription, versionHash: Data)] { + internal func cs_resolveAttributeNames() -> [ + String: ( + attribute: NSAttributeDescription, + versionHash: Data + ) + ] { return self.attributesByName.reduce( into: [:], @@ -44,7 +49,12 @@ extension NSEntityDescription { } @nonobjc - internal func cs_resolveAttributeRenamingIdentities() -> [String: (attribute: NSAttributeDescription, versionHash: Data)] { + internal func cs_resolveAttributeRenamingIdentities() -> [ + String: ( + attribute: NSAttributeDescription, + versionHash: Data + ) + ] { return self.attributesByName.reduce( into: [:], @@ -56,7 +66,12 @@ extension NSEntityDescription { } @nonobjc - internal func cs_resolveRelationshipNames() -> [String: (relationship: NSRelationshipDescription, versionHash: Data)] { + internal func cs_resolveRelationshipNames() -> [ + String: ( + relationship: NSRelationshipDescription, + versionHash: Data + ) + ] { return self.relationshipsByName.reduce( into: [:], @@ -68,7 +83,12 @@ extension NSEntityDescription { } @nonobjc - internal func cs_resolveRelationshipRenamingIdentities() -> [String: (relationship: NSRelationshipDescription, versionHash: Data)] { + internal func cs_resolveRelationshipRenamingIdentities() -> [ + String: ( + relationship: NSRelationshipDescription, + versionHash: Data + ) + ] { return self.relationshipsByName.reduce( into: [:], diff --git a/Sources/NSFetchedResultsController+Convenience.swift b/Sources/NSFetchedResultsController+Convenience.swift index 7e53430..03d0ed4 100644 --- a/Sources/NSFetchedResultsController+Convenience.swift +++ b/Sources/NSFetchedResultsController+Convenience.swift @@ -41,8 +41,12 @@ extension DataStack { - returns: an `NSFetchedResultsController` that observes the `DataStack` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.mainContext, from: from, @@ -61,8 +65,12 @@ extension DataStack { - returns: an `NSFetchedResultsController` that observes the `DataStack` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.mainContext, from: from, @@ -80,8 +88,11 @@ extension DataStack { - returns: an `NSFetchedResultsController` that observes the `DataStack` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ fetchClauses: FetchClause...) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ fetchClauses: FetchClause... + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.mainContext, from: from, @@ -99,8 +110,12 @@ extension DataStack { - returns: an `NSFetchedResultsController` that observes the `DataStack` */ @nonobjc - public func createFetchedResultsController(forDataStack dataStack: DataStack, _ from: From, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController { - + public func createFetchedResultsController( + forDataStack dataStack: DataStack, + _ from: From, + _ fetchClauses: [FetchClause] + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.mainContext, from: from, @@ -125,8 +140,12 @@ extension UnsafeDataTransaction { - returns: an `NSFetchedResultsController` that observes the `UnsafeDataTransaction` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.context, from: from, @@ -145,8 +164,12 @@ extension UnsafeDataTransaction { - returns: an `NSFetchedResultsController` that observes the `UnsafeDataTransaction` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.context, from: from, @@ -164,8 +187,11 @@ extension UnsafeDataTransaction { - returns: an `NSFetchedResultsController` that observes the `UnsafeDataTransaction` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ fetchClauses: FetchClause...) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ fetchClauses: FetchClause... + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.context, from: from, @@ -183,8 +209,11 @@ extension UnsafeDataTransaction { - returns: an `NSFetchedResultsController` that observes the `UnsafeDataTransaction` */ @nonobjc - public func createFetchedResultsController(_ from: From, _ fetchClauses: [FetchClause]) -> NSFetchedResultsController { - + public func createFetchedResultsController( + _ from: From, + _ fetchClauses: [FetchClause] + ) -> NSFetchedResultsController { + return Internals.createFRC( fromContext: self.context, from: from, @@ -202,7 +231,12 @@ extension Internals { // MARK: FilePrivate - fileprivate static func createFRC(fromContext context: NSManagedObjectContext, from: From, sectionBy: SectionBy? = nil, fetchClauses: [FetchClause]) -> NSFetchedResultsController { + fileprivate static func createFRC( + fromContext context: NSManagedObjectContext, + from: From, + sectionBy: SectionBy? = nil, + fetchClauses: [FetchClause] + ) -> NSFetchedResultsController { let controller = Internals.CoreStoreFetchedResultsController( context: context, diff --git a/Sources/NSManagedObject+Convenience.swift b/Sources/NSManagedObject+Convenience.swift index c9ee8c7..3fce1a7 100644 --- a/Sources/NSManagedObject+Convenience.swift +++ b/Sources/NSManagedObject+Convenience.swift @@ -84,8 +84,10 @@ extension NSManagedObject { - returns: the primitive value for the KVC key */ @nonobjc @inline(__always) - public func getValue(forKvcKey kvcKey: KeyPathString) -> Any? { - + public func getValue( + forKvcKey kvcKey: KeyPathString + ) -> Any? { + self.willAccessValue(forKey: kvcKey) defer { @@ -102,8 +104,11 @@ extension NSManagedObject { - returns: the primitive value transformed by the `didGetValue` closure */ @nonobjc @inline(__always) - public func getValue(forKvcKey kvcKey: KeyPathString, didGetValue: (Any?) throws -> T) rethrows -> T { - + public func getValue( + forKvcKey kvcKey: KeyPathString, + didGetValue: (Any?) throws(any Swift.Error) -> T + ) rethrows -> T { + self.willAccessValue(forKey: kvcKey) defer { @@ -121,8 +126,12 @@ extension NSManagedObject { - returns: the primitive value transformed by the `didGetValue` closure */ @nonobjc @inline(__always) - public func getValue(forKvcKey kvcKey: KeyPathString, willGetValue: () throws -> Void, didGetValue: (Any?) throws -> T) rethrows -> T { - + public func getValue( + forKvcKey kvcKey: KeyPathString, + willGetValue: () throws(any Swift.Error) -> Void, + didGetValue: (Any?) throws(any Swift.Error) -> T + ) rethrows -> T { + self.willAccessValue(forKey: kvcKey) defer { @@ -139,8 +148,11 @@ extension NSManagedObject { - parameter KVCKey: the KVC key */ @nonobjc @inline(__always) - public func setValue(_ value: Any?, forKvcKey KVCKey: KeyPathString) { - + public func setValue( + _ value: Any?, + forKvcKey KVCKey: KeyPathString + ) { + self.willChangeValue(forKey: KVCKey) defer { @@ -157,8 +169,12 @@ extension NSManagedObject { - parameter didSetValue: called after executing `setPrimitiveValue(forKey:)`. */ @nonobjc @inline(__always) - public func setValue(_ value: Any?, forKvcKey KVCKey: KeyPathString, didSetValue: () -> Void) { - + public func setValue( + _ value: Any?, + forKvcKey KVCKey: KeyPathString, + didSetValue: () -> Void + ) { + self.willChangeValue(forKey: KVCKey) defer { @@ -177,8 +193,13 @@ extension NSManagedObject { - parameter didSetValue: called after executing `setPrimitiveValue(forKey:)`. */ @nonobjc @inline(__always) - public func setValue(_ value: T, forKvcKey KVCKey: KeyPathString, willSetValue: (T) throws -> Any?, didSetValue: (Any?) -> Void = { _ in }) rethrows { - + public func setValue( + _ value: T, + forKvcKey KVCKey: KeyPathString, + willSetValue: (T) throws(any Swift.Error) -> Any?, + didSetValue: (Any?) -> Void = { _ in } + ) rethrows { + self.willChangeValue(forKey: KVCKey) defer { diff --git a/Sources/NSManagedObjectContext+Querying.swift b/Sources/NSManagedObjectContext+Querying.swift index f54e9b6..6ddbeff 100644 --- a/Sources/NSManagedObjectContext+Querying.swift +++ b/Sources/NSManagedObjectContext+Querying.swift @@ -34,8 +34,10 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { // MARK: FetchableSource @nonobjc - public func fetchExisting(_ object: O) -> O? { - + public func fetchExisting( + _ object: O + ) -> O? { + let rawObject = object.cs_toRaw() if rawObject.objectID.isTemporaryID { @@ -75,8 +77,10 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchExisting(_ objectID: NSManagedObjectID) -> O? { - + public func fetchExisting( + _ objectID: NSManagedObjectID + ) -> O? { + do { let existingObject = try self.existingObject(with: objectID) @@ -89,26 +93,36 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchExisting(_ objects: S) -> [O] where S.Iterator.Element == O { - + public func fetchExisting( + _ objects: S + ) -> [O] where S.Iterator.Element == O { + return objects.compactMap({ self.fetchExisting($0.cs_id()) }) } @nonobjc - public func fetchExisting(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID { - + public func fetchExisting( + _ objectIDs: S + ) -> [O] where S.Iterator.Element == NSManagedObjectID { + return objectIDs.compactMap({ self.fetchExisting($0) }) } @nonobjc - public func fetchOne(_ from: From, _ fetchClauses: FetchClause...) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> O? { + return try self.fetchOne(from, fetchClauses) } @nonobjc - public func fetchOne(_ from: From, _ fetchClauses: [FetchClause]) throws -> O? { - + public func fetchOne( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> O? { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -120,20 +134,31 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchOne(_ clauseChain: B) throws -> B.ObjectType? { - - return try self.fetchOne(clauseChain.from, clauseChain.fetchClauses) + public func fetchOne( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ObjectType? { + + return try self.fetchOne( + clauseChain.from, + clauseChain.fetchClauses + ) } @nonobjc - public func fetchAll(_ from: From, _ fetchClauses: FetchClause...) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [O] { + return try self.fetchAll(from, fetchClauses) } @nonobjc - public func fetchAll(_ from: From, _ fetchClauses: [FetchClause]) throws -> [O] { - + public func fetchAll( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [O] { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -146,20 +171,31 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchAll(_ clauseChain: B) throws -> [B.ObjectType] { - - return try self.fetchAll(clauseChain.from, clauseChain.fetchClauses) + public func fetchAll( + _ clauseChain: B + ) throws(CoreStoreError) -> [B.ObjectType] { + + return try self.fetchAll( + clauseChain.from, + clauseChain.fetchClauses + ) } @nonobjc - public func fetchCount(_ from: From, _ fetchClauses: FetchClause...) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> Int { + return try self.fetchCount(from, fetchClauses) } @nonobjc - public func fetchCount(_ from: From, _ fetchClauses: [FetchClause]) throws -> Int { - + public func fetchCount( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> Int { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -170,20 +206,31 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchCount(_ clauseChain: B) throws -> Int { - - return try self.fetchCount(clauseChain.from, clauseChain.fetchClauses) + public func fetchCount( + _ clauseChain: B + ) throws(CoreStoreError) -> Int { + + return try self.fetchCount( + clauseChain.from, + clauseChain.fetchClauses + ) } @nonobjc - public func fetchObjectID(_ from: From, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> NSManagedObjectID? { + return try self.fetchObjectID(from, fetchClauses) } @nonobjc - public func fetchObjectID(_ from: From, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? { - + public func fetchObjectID( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> NSManagedObjectID? { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -195,19 +242,30 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchObjectID(_ clauseChain: B) throws -> NSManagedObjectID? { - - return try self.fetchObjectID(clauseChain.from, clauseChain.fetchClauses) + public func fetchObjectID( + _ clauseChain: B + ) throws(CoreStoreError) -> NSManagedObjectID? { + + return try self.fetchObjectID( + clauseChain.from, + clauseChain.fetchClauses + ) } @nonobjc - public func fetchObjectIDs(_ from: From, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] { - + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: FetchClause... + ) throws(CoreStoreError) -> [NSManagedObjectID] { + return try self.fetchObjectIDs(from, fetchClauses) } @nonobjc - public func fetchObjectIDs(_ from: From, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] { + public func fetchObjectIDs( + _ from: From, + _ fetchClauses: [FetchClause] + ) throws(CoreStoreError) -> [NSManagedObjectID] { let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -220,14 +278,21 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func fetchObjectIDs(_ clauseChain: B) throws -> [NSManagedObjectID] { - - return try self.fetchObjectIDs(clauseChain.from, clauseChain.fetchClauses) + public func fetchObjectIDs( + _ clauseChain: B + ) throws(CoreStoreError) -> [NSManagedObjectID] { + + return try self.fetchObjectIDs( + clauseChain.from, + clauseChain.fetchClauses + ) } @nonobjc - internal func fetchObjectIDs(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> [NSManagedObjectID] { - + internal func fetchObjectIDs( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> [NSManagedObjectID] { + var fetchResults: [NSManagedObjectID]? var fetchError: Error? self.performAndWait { @@ -257,14 +322,22 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { // MARK: QueryableSource @nonobjc - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> U? { + return try self.queryValue(from, selectClause, queryClauses) } @nonobjc - public func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> U? { - + public func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> U? { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -277,20 +350,34 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { } @nonobjc - public func queryValue(_ clauseChain: B) throws -> B.ResultType? where B: QueryChainableBuilderType, B.ResultType: QueryableAttributeType { - - return try self.queryValue(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + public func queryValue( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ResultType? where B: QueryChainableBuilderType, B.ResultType: QueryableAttributeType { + + return try self.queryValue( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } @nonobjc - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> [[String: Any]] { + return try self.queryAttributes(from, selectClause, queryClauses) } @nonobjc - public func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> [[String: Any]] { - + public func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> [[String: Any]] { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -302,9 +389,15 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { return try self.queryAttributes(fetchRequest) } - public func queryAttributes(_ clauseChain: B) throws -> [[String : Any]] where B : QueryChainableBuilderType, B.ResultType == NSDictionary { - - return try self.queryAttributes(clauseChain.from, clauseChain.select, clauseChain.queryClauses) + public func queryAttributes( + _ clauseChain: B + ) throws(CoreStoreError) -> [[String : Any]] where B : QueryChainableBuilderType, B.ResultType == NSDictionary { + + return try self.queryAttributes( + clauseChain.from, + clauseChain.select, + clauseChain.queryClauses + ) } @@ -320,8 +413,11 @@ extension NSManagedObjectContext: FetchableSource, QueryableSource { // MARK: Deleting @nonobjc - internal func deleteAll(_ from: From, _ deleteClauses: [FetchClause]) throws -> Int { - + internal func deleteAll( + _ from: From, + _ deleteClauses: [FetchClause] + ) throws(CoreStoreError) -> Int { + let fetchRequest = Internals.CoreStoreFetchRequest() try from.applyToFetchRequest(fetchRequest, context: self) @@ -343,10 +439,12 @@ extension NSManagedObjectContext { // MARK: Fetching @nonobjc - internal func fetchOne(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> O? { - + internal func fetchOne( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> O? { + var fetchResults: [O]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -371,10 +469,12 @@ extension NSManagedObjectContext { } @nonobjc - internal func fetchAll(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> [O] { - + internal func fetchAll( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> [O] { + var fetchResults: [O]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -399,10 +499,12 @@ extension NSManagedObjectContext { } @nonobjc - internal func fetchCount(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> Int { - + internal func fetchCount( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> Int { + var count = 0 - var countError: Error? + var countError: (any Swift.Error)? self.performAndWait { do { @@ -427,10 +529,12 @@ extension NSManagedObjectContext { } @nonobjc - internal func fetchObjectID(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> NSManagedObjectID? { - + internal func fetchObjectID( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> NSManagedObjectID? { + var fetchResults: [NSManagedObjectID]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -458,10 +562,13 @@ extension NSManagedObjectContext { // MARK: Querying @nonobjc - internal func queryValue(_ selectTerms: [SelectTerm], fetchRequest: Internals.CoreStoreFetchRequest) throws -> U? { - + internal func queryValue( + _ selectTerms: [SelectTerm], + fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> U? { + var fetchResults: [Any]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -491,10 +598,13 @@ extension NSManagedObjectContext { } @nonobjc - internal func queryValue(_ selectTerms: [SelectTerm], fetchRequest: Internals.CoreStoreFetchRequest) throws -> Any? { - + internal func queryValue( + _ selectTerms: [SelectTerm], + fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> Any? { + var fetchResults: [Any]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -524,10 +634,12 @@ extension NSManagedObjectContext { } @nonobjc - internal func queryAttributes(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> [[String: Any]] { - + internal func queryAttributes( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> [[String: Any]] { + var fetchResults: [Any]? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { do { @@ -555,14 +667,16 @@ extension NSManagedObjectContext { // MARK: Deleting @nonobjc - internal func deleteAll(_ fetchRequest: Internals.CoreStoreFetchRequest) throws -> Int { - + internal func deleteAll( + _ fetchRequest: Internals.CoreStoreFetchRequest + ) throws(CoreStoreError) -> Int { + var numberOfDeletedObjects: Int? - var fetchError: Error? + var fetchError: (any Swift.Error)? self.performAndWait { - autoreleasepool { - + Internals.autoreleasepool { + do { let fetchResults = try self.fetch(fetchRequest.staticCast()) diff --git a/Sources/NSPersistentStoreCoordinator+Setup.swift b/Sources/NSPersistentStoreCoordinator+Setup.swift index eee21f5..78a645f 100644 --- a/Sources/NSPersistentStoreCoordinator+Setup.swift +++ b/Sources/NSPersistentStoreCoordinator+Setup.swift @@ -32,14 +32,18 @@ import CoreData extension NSPersistentStoreCoordinator { @nonobjc - internal func performAsynchronously(_ closure: @escaping () -> Void) { - + internal func performAsynchronously( + _ closure: @escaping () -> Void + ) { + self.perform(closure) } @nonobjc - internal func performSynchronously(_ closure: @escaping () -> T) -> T { - + internal func performSynchronously( + _ closure: @escaping () -> T + ) -> T { + var result: T? self.performAndWait { @@ -49,9 +53,11 @@ extension NSPersistentStoreCoordinator { } @nonobjc - internal func performSynchronously(_ closure: @escaping () throws -> T) throws -> T { - - var closureError: Error? + internal func performSynchronously( + _ closure: @escaping () throws(any Swift.Error) -> T + ) throws(CoreStoreError) -> T { + + var closureError: (any Swift.Error)? var result: T? self.performAndWait { @@ -66,29 +72,27 @@ extension NSPersistentStoreCoordinator { } if let closureError = closureError { - throw closureError + throw CoreStoreError(closureError) } return result! } - + @nonobjc - internal func addPersistentStoreSynchronously(_ storeType: String, configuration: ModelConfiguration, URL storeURL: URL?, options: [AnyHashable: Any]?) throws -> NSPersistentStore { - + internal func addPersistentStoreSynchronously( + _ storeType: String, + configuration: ModelConfiguration, + URL storeURL: URL?, + options: [AnyHashable: Any]? + ) throws(CoreStoreError) -> NSPersistentStore { + return try self.performSynchronously { - - do { - - return try self.addPersistentStore( - ofType: storeType, - configurationName: configuration, - at: storeURL, - options: options - ) - } - catch { - - throw CoreStoreError(error) - } + + return try self.addPersistentStore( + ofType: storeType, + configurationName: configuration, + at: storeURL, + options: options + ) } } } diff --git a/Sources/ObjectProxy.swift b/Sources/ObjectProxy.swift index b8f3923..59e5032 100644 --- a/Sources/ObjectProxy.swift +++ b/Sources/ObjectProxy.swift @@ -38,7 +38,9 @@ public struct ObjectProxy { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Stored>) -> FieldProxy { + public subscript( + dynamicMember member: KeyPath.Stored> + ) -> FieldProxy { return .init(rawObject: self.rawObject, keyPath: member) } @@ -46,7 +48,9 @@ public struct ObjectProxy { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Virtual>) -> FieldProxy { + public subscript( + dynamicMember member: KeyPath.Virtual> + ) -> FieldProxy { return .init(rawObject: self.rawObject, keyPath: member) } @@ -54,7 +58,9 @@ public struct ObjectProxy { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Coded>) -> FieldProxy { + public subscript( + dynamicMember member: KeyPath.Coded> + ) -> FieldProxy { return .init(rawObject: self.rawObject, keyPath: member) } @@ -111,22 +117,34 @@ public struct ObjectProxy { // MARK: Internal - internal init(rawObject: CoreStoreManagedObject, keyPath: KeyPath.Stored>) { + internal init( + rawObject: CoreStoreManagedObject, + keyPath: KeyPath.Stored> + ) { self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath]) } - internal init(rawObject: CoreStoreManagedObject, keyPath: KeyPath.Virtual>) { + internal init( + rawObject: CoreStoreManagedObject, + keyPath: KeyPath.Virtual> + ) { self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath]) } - internal init(rawObject: CoreStoreManagedObject, keyPath: KeyPath.Coded>) { + internal init( + rawObject: CoreStoreManagedObject, + keyPath: KeyPath.Coded> + ) { self.init(rawObject: rawObject, field: O.meta[keyPath: keyPath]) } - internal init(rawObject: CoreStoreManagedObject, field: FieldContainer.Stored) { + internal init( + rawObject: CoreStoreManagedObject, + field: FieldContainer.Stored + ) { let keyPathString = field.keyPath self.getValue = { @@ -157,7 +175,10 @@ public struct ObjectProxy { } } - internal init(rawObject: CoreStoreManagedObject, field: FieldContainer.Virtual) { + internal init( + rawObject: CoreStoreManagedObject, + field: FieldContainer.Virtual + ) { let keyPathString = field.keyPath self.getValue = { @@ -190,7 +211,10 @@ public struct ObjectProxy { } } - internal init(rawObject: CoreStoreManagedObject, field: FieldContainer.Coded) { + internal init( + rawObject: CoreStoreManagedObject, + field: FieldContainer.Coded + ) { let keyPathString = field.keyPath self.getValue = { diff --git a/Sources/ObjectPublisher+Reactive.swift b/Sources/ObjectPublisher+Reactive.swift index ca469b6..65205a9 100644 --- a/Sources/ObjectPublisher+Reactive.swift +++ b/Sources/ObjectPublisher+Reactive.swift @@ -94,8 +94,10 @@ extension ObjectPublisher.ReactiveNamespace { - parameter emitInitialValue: If `true`, the current value is immediately emitted to the first subscriber. If `false`, the event fires only starting the next `ObjectSnapshot` update. - returns: A `Publisher` that emits an `ObjectSnapshot?` whenever changes occur in the `ObjectPublisher`. The event emits `nil` if the object has been deletd. */ - public func snapshot(emitInitialValue: Bool = true) -> ObjectPublisher.SnapshotPublisher { - + public func snapshot( + emitInitialValue: Bool = true + ) -> ObjectPublisher.SnapshotPublisher { + return .init( objectPublisher: self.base, emitInitialValue: emitInitialValue @@ -111,7 +113,9 @@ extension ObjectPublisher.ReactiveNamespace where O: NSManagedObject { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath) -> some Publisher { + public subscript( + dynamicMember member: KeyPath + ) -> some Publisher { return self .snapshot(emitInitialValue: true) @@ -127,8 +131,10 @@ extension ObjectPublisher.ReactiveNamespace where O: CoreStoreObject { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Stored>) -> some Publisher { - + public subscript( + dynamicMember member: KeyPath.Stored> + ) -> some Publisher { + return self .snapshot(emitInitialValue: true) .map({ $0?[dynamicMember: member] }) @@ -137,8 +143,10 @@ extension ObjectPublisher.ReactiveNamespace where O: CoreStoreObject { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Virtual>) -> some Publisher { - + public subscript( + dynamicMember member: KeyPath.Virtual> + ) -> some Publisher { + return self .snapshot(emitInitialValue: true) .map({ $0?[dynamicMember: member] }) @@ -147,8 +155,10 @@ extension ObjectPublisher.ReactiveNamespace where O: CoreStoreObject { /** Returns the value for the property identified by a given key. */ - public subscript(dynamicMember member: KeyPath.Coded>) -> some Publisher { - + public subscript( + dynamicMember member: KeyPath.Coded> + ) -> some Publisher { + return self .snapshot(emitInitialValue: true) .map({ $0?[dynamicMember: member] }) diff --git a/Sources/ObjectPublisher.SnapshotPublisher.swift b/Sources/ObjectPublisher.SnapshotPublisher.swift index 2feb2cf..2a78d24 100644 --- a/Sources/ObjectPublisher.SnapshotPublisher.swift +++ b/Sources/ObjectPublisher.SnapshotPublisher.swift @@ -52,8 +52,10 @@ extension ObjectPublisher { public typealias Output = ObjectSnapshot? public typealias Failure = Never - public func receive(subscriber: S) where S.Input == Output, S.Failure == Failure { - + public func receive( + subscriber: S + ) where S.Input == Output, S.Failure == Failure { + subscriber.receive( subscription: ObjectSnapshotSubscription( publisher: self.objectPublisher, diff --git a/Sources/QueryableSource.swift b/Sources/QueryableSource.swift index 2e53ed1..f5b190a 100644 --- a/Sources/QueryableSource.swift +++ b/Sources/QueryableSource.swift @@ -45,7 +45,11 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> U? + func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> U? /** Queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. @@ -58,8 +62,12 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryValue(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> U? - + func queryValue( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> U? + /** Queries a property value or aggregate as specified by the `QueryChainableBuilderType` built from a chain of clauses. @@ -75,7 +83,9 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query as specified by the `QueryChainableBuilderType`, or `nil` if no match was found. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryValue(_ clauseChain: B) throws -> B.ResultType? where B.ResultType: QueryableAttributeType + func queryValue( + _ clauseChain: B + ) throws(CoreStoreError) -> B.ResultType? where B.ResultType: QueryableAttributeType /** Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. @@ -88,7 +98,11 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: QueryClause...) throws -> [[String: Any]] + func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: QueryClause... + ) throws(CoreStoreError) -> [[String: Any]] /** Queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. @@ -101,8 +115,12 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryAttributes(_ from: From, _ selectClause: Select, _ queryClauses: [QueryClause]) throws -> [[String: Any]] - + func queryAttributes( + _ from: From, + _ selectClause: Select, + _ queryClauses: [QueryClause] + ) throws(CoreStoreError) -> [[String: Any]] + /** Queries a dictionary of attribute values or as specified by the `QueryChainableBuilderType` built from a chain of clauses. @@ -127,8 +145,10 @@ public protocol QueryableSource: AnyObject { - returns: the result of the the query as specified by the `QueryChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ - func queryAttributes(_ clauseChain: B) throws -> [[String: Any]] where B.ResultType == NSDictionary - + func queryAttributes( + _ clauseChain: B + ) throws(CoreStoreError) -> [[String: Any]] where B.ResultType == NSDictionary + /** The internal `NSManagedObjectContext` managed by this `QueryableSource`. Using this context directly should typically be avoided, and is provided by CoreStore only for extremely specialized cases. */ diff --git a/Sources/SQLiteStore.swift b/Sources/SQLiteStore.swift index f8d2abc..2e2e8e2 100644 --- a/Sources/SQLiteStore.swift +++ b/Sources/SQLiteStore.swift @@ -43,8 +43,13 @@ public final class SQLiteStore: LocalStorage { - parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array. - parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.none`. */ - public init(fileURL: URL, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) { - + public init( + fileURL: URL, + configuration: ModelConfiguration = nil, + migrationMappingProviders: [SchemaMappingProvider] = [], + localStorageOptions: LocalStorageOptions = nil + ) { + self.fileURL = fileURL self.configuration = configuration self.migrationMappingProviders = migrationMappingProviders @@ -60,8 +65,13 @@ public final class SQLiteStore: LocalStorage { - parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array. - parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`. */ - public init(fileName: String, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) { - + public init( + fileName: String, + configuration: ModelConfiguration = nil, + migrationMappingProviders: [SchemaMappingProvider] = [], + localStorageOptions: LocalStorageOptions = nil + ) { + self.fileURL = SQLiteStore.defaultRootDirectory .appendingPathComponent(fileName, isDirectory: false) self.configuration = configuration @@ -91,8 +101,13 @@ public final class SQLiteStore: LocalStorage { - parameter migrationMappingProviders: an array of `SchemaMappingProviders` that provides the complete mapping models for custom migrations. All lightweight inferred mappings and/or migration mappings provided by *xcmappingmodel files are automatically used as fallback (as `InferredSchemaMappingProvider`) and may be omitted from the array. - parameter localStorageOptions: When the `SQLiteStore` is passed to the `DataStack`'s `addStorage()` methods, tells the `DataStack` how to setup the persistent store. Defaults to `.None`. */ - public static func legacy(fileName: String, configuration: ModelConfiguration = nil, migrationMappingProviders: [SchemaMappingProvider] = [], localStorageOptions: LocalStorageOptions = nil) -> SQLiteStore { - + public static func legacy( + fileName: String, + configuration: ModelConfiguration = nil, + migrationMappingProviders: [SchemaMappingProvider] = [], + localStorageOptions: LocalStorageOptions = nil + ) -> SQLiteStore { + return SQLiteStore( fileURL: SQLiteStore.legacyDefaultRootDirectory .appendingPathComponent(fileName, isDirectory: false), @@ -192,8 +207,10 @@ public final class SQLiteStore: LocalStorage { /** The options dictionary for the specified `LocalStorageOptions` */ - public func dictionary(forOptions options: LocalStorageOptions) -> [AnyHashable: Any]? { - + public func dictionary( + forOptions options: LocalStorageOptions + ) -> [AnyHashable: Any]? { + if options == .none { return self.storeOptions @@ -211,8 +228,10 @@ public final class SQLiteStore: LocalStorage { /** Called by the `DataStack` to perform checkpoint operations on the storage. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE to force a checkpoint. */ - public func cs_finalizeStorageAndWait(soureModelHint: NSManagedObjectModel) throws { - + public func cs_finalizeStorageAndWait( + soureModelHint: NSManagedObjectModel + ) throws(any Swift.Error) { + _ = try withExtendedLifetime(NSPersistentStoreCoordinator(managedObjectModel: soureModelHint)) { (coordinator: NSPersistentStoreCoordinator) in var storeOptions = self.storeOptions ?? [:] @@ -230,10 +249,16 @@ public final class SQLiteStore: LocalStorage { /** Called by the `DataStack` to perform actual deletion of the store file from disk. Do not call directly! The `sourceModel` argument is a hint for the existing store's model version. For `SQLiteStore`, this converts the database's WAL journaling mode to DELETE before deleting the file. */ - public func cs_eraseStorageAndWait(metadata: [String: Any], soureModelHint: NSManagedObjectModel?) throws { - - func deleteFiles(storeURL: URL, extraFiles: [String] = []) throws { - + public func cs_eraseStorageAndWait( + metadata: [String: Any], + soureModelHint: NSManagedObjectModel? + ) throws(any Swift.Error) { + + func deleteFiles( + storeURL: URL, + extraFiles: [String] = [] + ) throws(any Swift.Error) { + let fileManager = FileManager.default let extraFiles: [String] = [ storeURL.path.appending("-wal"), @@ -263,7 +288,8 @@ public final class SQLiteStore: LocalStorage { return extraFile } DispatchQueue.global(qos: .background).async { - + + let fileManager = FileManager.default _ = try? fileManager.removeItem(at: temporaryFileURL) extraTemporaryFiles.forEach({ _ = try? fileManager.removeItem(atPath: $0) }) } @@ -276,7 +302,7 @@ public final class SQLiteStore: LocalStorage { } let fileURL = self.fileURL - try autoreleasepool { + try Internals.autoreleasepool { if let soureModel = soureModelHint ?? NSManagedObjectModel.mergedModel(from: nil, forStoreMetadata: metadata) { diff --git a/Sources/SchemaHistory.swift b/Sources/SchemaHistory.swift index 22cb42c..8432abc 100644 --- a/Sources/SchemaHistory.swift +++ b/Sources/SchemaHistory.swift @@ -57,8 +57,14 @@ public final class SchemaHistory: ExpressibleByArrayLiteral { - parameter xcodeDataModeld: a tuple returned from the `XcodeDataModelSchema.from(modelName:bundle:migrationChain:)` method. - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. */ - public convenience init(_ xcodeDataModeld: (allSchema: [XcodeDataModelSchema], currentModelVersion: ModelVersion), migrationChain: MigrationChain = nil) { - + public convenience init( + _ xcodeDataModeld: ( + allSchema: [XcodeDataModelSchema], + currentModelVersion: ModelVersion + ), + migrationChain: MigrationChain = nil + ) { + self.init( allSchema: xcodeDataModeld.allSchema, migrationChain: migrationChain, @@ -73,8 +79,13 @@ public final class SchemaHistory: ExpressibleByArrayLiteral { - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. - parameter exactCurrentModelVersion: an optional string to explicitly select the current model version string. This is useful if the `DataStack` should load a non-latest model version (usually to prepare data before migration). If not provided, the current model version will be computed from the `MigrationChain`. */ - public convenience init(_ schema: DynamicSchema, _ otherSchema: DynamicSchema..., migrationChain: MigrationChain = nil, exactCurrentModelVersion: String? = nil) { - + public convenience init( + _ schema: DynamicSchema, + _ otherSchema: DynamicSchema..., + migrationChain: MigrationChain = nil, + exactCurrentModelVersion: String? = nil + ) { + self.init( allSchema: [schema] + otherSchema, migrationChain: migrationChain, @@ -88,8 +99,12 @@ public final class SchemaHistory: ExpressibleByArrayLiteral { - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. - parameter exactCurrentModelVersion: an optional string to explicitly select the current model version string. This is useful if the `DataStack` should load a non-latest model version (usually to prepare data before migration). If not provided, the current model version will be computed from the `MigrationChain`. */ - public required init(allSchema: [DynamicSchema], migrationChain: MigrationChain = nil, exactCurrentModelVersion: String? = nil) { - + public required init( + allSchema: [DynamicSchema], + migrationChain: MigrationChain = nil, + exactCurrentModelVersion: String? = nil + ) { + if allSchema.isEmpty { Internals.abort("The \"allSchema\" argument of the \(Internals.typeName(SchemaHistory.self)) initializer cannot be empty.") diff --git a/Sources/SchemaMappingProvider.swift b/Sources/SchemaMappingProvider.swift index 37dbba4..420ef1c 100644 --- a/Sources/SchemaMappingProvider.swift +++ b/Sources/SchemaMappingProvider.swift @@ -37,5 +37,12 @@ public protocol SchemaMappingProvider { /** Do not call directly. */ - func cs_createMappingModel(from sourceSchema: DynamicSchema, to destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) + func cs_createMappingModel( + from sourceSchema: DynamicSchema, + to destinationSchema: DynamicSchema, + storage: LocalStorage + ) throws(CoreStoreError) -> ( + mappingModel: NSMappingModel, + migrationType: MigrationType + ) } diff --git a/Sources/Select.swift b/Sources/Select.swift index ca68559..ef4a229 100644 --- a/Sources/Select.swift +++ b/Sources/Select.swift @@ -43,7 +43,9 @@ public protocol SelectResultType {} */ public protocol SelectAttributesResultType: SelectResultType { - static func cs_fromQueryResultsNativeType(_ result: [Any]) -> [[String: Any]] + static func cs_fromQueryResultsNativeType( + _ result: [Any] + ) -> [[String: Any]] } @@ -74,8 +76,10 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter keyPath: the attribute name - returns: a `SelectTerm` to a `Select` clause for querying an entity attribute */ - public static func attribute(_ keyPath: KeyPathString) -> SelectTerm { - + public static func attribute( + _ keyPath: KeyPathString + ) -> SelectTerm { + return ._attribute(keyPath) } @@ -91,8 +95,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average()" is used - returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute */ - public static func average(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm { - + public static func average( + _ keyPath: KeyPathString, + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._aggregate( function: "average:", keyPath: keyPath, @@ -113,8 +120,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count()" is used - returns: a `SelectTerm` to a `Select` clause for a count query */ - public static func count(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm { - + public static func count( + _ keyPath: KeyPathString, + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._aggregate( function: "count:", keyPath: keyPath, @@ -135,8 +145,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max()" is used - returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute */ - public static func maximum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm { - + public static func maximum( + _ keyPath: KeyPathString, + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._aggregate( function: "max:", keyPath: keyPath, @@ -157,8 +170,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min()" is used - returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute */ - public static func minimum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm { - + public static func minimum( + _ keyPath: KeyPathString, + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._aggregate( function: "min:", keyPath: keyPath, @@ -179,8 +195,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum()" is used - returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute */ - public static func sum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm { - + public static func sum( + _ keyPath: KeyPathString, + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._aggregate( function: "sum:", keyPath: keyPath, @@ -202,8 +221,10 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "objecID" is used - returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute */ - public static func objectID(as alias: KeyPathString? = nil) -> SelectTerm { - + public static func objectID( + as alias: KeyPathString? = nil + ) -> SelectTerm { + return ._identity( alias: alias ?? "objectID", nativeType: .objectIDAttributeType @@ -231,8 +252,11 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { // MARK: Equatable - public static func == (lhs: SelectTerm, rhs: SelectTerm) -> Bool { - + public static func == ( + lhs: SelectTerm, + rhs: SelectTerm + ) -> Bool { + switch (lhs, rhs) { case (._attribute(let keyPath1), ._attribute(let keyPath2)): @@ -284,9 +308,19 @@ public enum SelectTerm: ExpressibleByStringLiteral, Hashable { // MARK: Internal case _attribute(KeyPathString) - case _aggregate(function: String, keyPath: KeyPathString, alias: String, nativeType: NSAttributeType) - case _identity(alias: String, nativeType: NSAttributeType) - + + case _aggregate( + function: String, + keyPath: KeyPathString, + alias: String, + nativeType: NSAttributeType + ) + + case _identity( + alias: String, + nativeType: NSAttributeType + ) + internal var keyPathString: String { switch self { @@ -308,8 +342,10 @@ extension SelectTerm where O: NSManagedObject { - parameter keyPath: the attribute name - returns: a `SelectTerm` to a `Select` clause for querying an entity attribute */ - public static func attribute(_ keyPath: KeyPath) -> SelectTerm { - + public static func attribute( + _ keyPath: KeyPath + ) -> SelectTerm { + return self.attribute(keyPath._kvcKeyPathString!) } @@ -319,9 +355,15 @@ extension SelectTerm where O: NSManagedObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average()" is used - returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute */ - public static func average(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm { - - return self.average(keyPath._kvcKeyPathString!, as: alias) + public static func average( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm { + + return self.average( + keyPath._kvcKeyPathString!, + as: alias + ) } /** @@ -330,9 +372,15 @@ extension SelectTerm where O: NSManagedObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count()" is used - returns: a `SelectTerm` to a `Select` clause for a count query */ - public static func count(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm { - - return self.count(keyPath._kvcKeyPathString!, as: alias) + public static func count( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm { + + return self.count( + keyPath._kvcKeyPathString!, + as: alias + ) } /** @@ -341,9 +389,15 @@ extension SelectTerm where O: NSManagedObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max()" is used - returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute */ - public static func maximum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm { - - return self.maximum(keyPath._kvcKeyPathString!, as: alias) + public static func maximum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm { + + return self.maximum( + keyPath._kvcKeyPathString!, + as: alias + ) } /** @@ -352,9 +406,15 @@ extension SelectTerm where O: NSManagedObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min()" is used - returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute */ - public static func minimum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm { - - return self.minimum(keyPath._kvcKeyPathString!, as: alias) + public static func minimum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm { + + return self.minimum( + keyPath._kvcKeyPathString!, + as: alias + ) } /** @@ -363,9 +423,15 @@ extension SelectTerm where O: NSManagedObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum()" is used - returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute */ - public static func sum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm { - - return self.sum(keyPath._kvcKeyPathString!, as: alias) + public static func sum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm { + + return self.sum( + keyPath._kvcKeyPathString!, + as: alias + ) } } @@ -379,7 +445,9 @@ extension SelectTerm where O: CoreStoreObject { - parameter keyPath: the attribute name - returns: a `SelectTerm` to a `Select` clause for querying an entity attribute */ - public static func attribute(_ keyPath: KeyPath) -> SelectTerm where K.ObjectType == O { + public static func attribute( + _ keyPath: KeyPath + ) -> SelectTerm where K.ObjectType == O { return self.attribute(O.meta[keyPath: keyPath].cs_keyPathString) } @@ -390,9 +458,15 @@ extension SelectTerm where O: CoreStoreObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average()" is used - returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute */ - public static func average(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm where K.ObjectType == O{ - - return self.average(O.meta[keyPath: keyPath].cs_keyPathString, as: alias) + public static func average( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm where K.ObjectType == O{ + + return self.average( + O.meta[keyPath: keyPath].cs_keyPathString, + as: alias + ) } /** @@ -401,10 +475,15 @@ extension SelectTerm where O: CoreStoreObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count()" is used - returns: a `SelectTerm` to a `Select` clause for a count query */ - public static func count(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm where K.ObjectType == O { - - return self.count(O.meta[keyPath: keyPath].cs_keyPathString, as: alias) + public static func count( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm where K.ObjectType == O { + + return self.count( + O.meta[keyPath: keyPath].cs_keyPathString, + as: alias + ) } /** @@ -413,10 +492,15 @@ extension SelectTerm where O: CoreStoreObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max()" is used - returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute */ - public static func maximum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm where K.ObjectType == O { - - return self.maximum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias) + public static func maximum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm where K.ObjectType == O { + + return self.maximum( + O.meta[keyPath: keyPath].cs_keyPathString, + as: alias + ) } /** @@ -425,9 +509,15 @@ extension SelectTerm where O: CoreStoreObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min()" is used - returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute */ - public static func minimum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm where K.ObjectType == O { - - return self.minimum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias) + public static func minimum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm where K.ObjectType == O { + + return self.minimum( + O.meta[keyPath: keyPath].cs_keyPathString, + as: alias + ) } /** @@ -436,9 +526,15 @@ extension SelectTerm where O: CoreStoreObject { - parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum()" is used - returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute */ - public static func sum(_ keyPath: KeyPath, as alias: KeyPathString? = nil) -> SelectTerm where K.ObjectType == O { - - return self.sum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias) + public static func sum( + _ keyPath: KeyPath, + as alias: KeyPathString? = nil + ) -> SelectTerm where K.ObjectType == O { + + return self.sum( + O.meta[keyPath: keyPath].cs_keyPathString, + as: alias + ) } } @@ -479,8 +575,11 @@ public struct Select: SelectClause, Hasha - parameter selectTerm: a `SelectTerm` - parameter selectTerms: a series of `SelectTerm`s */ - public init(_ selectTerm: SelectTerm, _ selectTerms: SelectTerm...) { - + public init( + _ selectTerm: SelectTerm, + _ selectTerms: SelectTerm... + ) { + self.selectTerms = [selectTerm] + selectTerms } @@ -489,15 +588,20 @@ public struct Select: SelectClause, Hasha - parameter selectTerms: a series of `SelectTerm`s */ - public init(_ selectTerms: [SelectTerm]) { - + public init( + _ selectTerms: [SelectTerm] + ) { + self.selectTerms = selectTerms } // MARK: Equatable - public static func == (lhs: Select, rhs: Select) -> Bool { + public static func == ( + lhs: Select, + rhs: Select + ) -> Bool { return lhs.selectTerms == rhs.selectTerms } @@ -521,8 +625,10 @@ public struct Select: SelectClause, Hasha // MARK: Internal - internal func applyToFetchRequest(_ fetchRequest: NSFetchRequest) { - + internal func applyToFetchRequest( + _ fetchRequest: NSFetchRequest + ) { + fetchRequest.includesPendingChanges = false fetchRequest.resultType = .dictionaryResultType @@ -661,8 +767,10 @@ extension NSDictionary: SelectAttributesResultType { // MARK: SelectAttributesResultType - public static func cs_fromQueryResultsNativeType(_ result: [Any]) -> [[String : Any]] { - + public static func cs_fromQueryResultsNativeType( + _ result: [Any] + ) -> [[String : Any]] { + return result as! [[String: Any]] } } diff --git a/Sources/StorageInterface.swift b/Sources/StorageInterface.swift index a94a49f..3ab4529 100644 --- a/Sources/StorageInterface.swift +++ b/Sources/StorageInterface.swift @@ -139,17 +139,24 @@ public protocol LocalStorage: StorageInterface { /** The options dictionary for the specified `LocalStorageOptions` */ - func dictionary(forOptions options: LocalStorageOptions) -> [AnyHashable: Any]? - + func dictionary( + forOptions options: LocalStorageOptions + ) -> [AnyHashable: Any]? + /** Called by the `DataStack` to perform checkpoint operations on the storage. (SQLite stores for example, can convert the database's WAL journaling mode to DELETE to force a checkpoint) */ - func cs_finalizeStorageAndWait(soureModelHint: NSManagedObjectModel) throws - + func cs_finalizeStorageAndWait( + soureModelHint: NSManagedObjectModel + ) throws(any Swift.Error) + /** Called by the `DataStack` to perform actual deletion of the store file from disk. **Do not call directly!** The `sourceModel` argument is a hint for the existing store's model version. Implementers can use the `sourceModel` to perform necessary store operations. (SQLite stores for example, can convert WAL journaling mode to DELETE before deleting) */ - func cs_eraseStorageAndWait(metadata: [String: Any], soureModelHint: NSManagedObjectModel?) throws + func cs_eraseStorageAndWait( + metadata: [String: Any], + soureModelHint: NSManagedObjectModel? + ) throws(any Swift.Error) } extension LocalStorage { diff --git a/Sources/SynchronousDataTransaction.swift b/Sources/SynchronousDataTransaction.swift index d31459d..ced1489 100644 --- a/Sources/SynchronousDataTransaction.swift +++ b/Sources/SynchronousDataTransaction.swift @@ -41,8 +41,8 @@ public final class SynchronousDataTransaction: BaseDataTransaction { ``` - Important: Always use plain `try` on a `cancel()` call. Never use `try?` or `try!`. Using `try?` will swallow the cancellation and the transaction will proceed to commit as normal. Using `try!` will crash the app as `cancel()` will *always* throw an error. */ - public func cancel() throws -> Never { - + public func cancel() throws(CoreStoreError) -> Never { + throw CoreStoreError.userCancelled } @@ -55,8 +55,10 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter into: the `Into` clause indicating the destination `NSManagedObject` or `CoreStoreObject` entity type and the destination configuration - returns: a new `NSManagedObject` or `CoreStoreObject` instance of the specified entity type. */ - public override func create(_ into: Into) -> O { - + public override func create( + _ into: Into + ) -> O { + Internals.assert( !self.isCommitted, "Attempted to create an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))." @@ -71,8 +73,10 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter object: the `NSManagedObject` or `CoreStoreObject` to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public override func edit(_ object: O?) -> O? { - + public override func edit( + _ object: O? + ) -> O? { + Internals.assert( !self.isCommitted, "Attempted to update an entity of type \(Internals.typeName(object)) from an already committed \(Internals.typeName(self))." @@ -88,8 +92,11 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter objectID: the `NSManagedObjectID` for the object to be edited - returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`. */ - public override func edit(_ into: Into, _ objectID: NSManagedObjectID) -> O? { - + public override func edit( + _ into: Into, + _ objectID: NSManagedObjectID + ) -> O? { + Internals.assert( !self.isCommitted, "Attempted to update an entity of type \(Internals.typeName(into.entityClass)) from an already committed \(Internals.typeName(self))." @@ -103,7 +110,9 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter objectIDs: the `NSManagedObjectID`s of the objects to delete */ - public override func delete(objectIDs: S) where S.Iterator.Element: NSManagedObjectID { + public override func delete( + objectIDs: S + ) where S.Iterator.Element: NSManagedObjectID { Internals.assert( !self.isCommitted, @@ -119,7 +128,10 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter object: the `ObjectRepresentation` representing an `NSManagedObject` or `CoreStoreObject` to be deleted - parameter objects: other `ObjectRepresentation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public override func delete(_ object: O?, _ objects: O?...) { + public override func delete( + _ object: O?, + _ objects: O?... + ) { Internals.assert( !self.isCommitted, @@ -134,7 +146,9 @@ public final class SynchronousDataTransaction: BaseDataTransaction { - parameter objects: the `ObjectRepresenation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted */ - public override func delete(_ objects: S) where S.Iterator.Element: ObjectRepresentation { + public override func delete( + _ objects: S + ) where S.Iterator.Element: ObjectRepresentation { Internals.assert( !self.isCommitted, @@ -162,8 +176,13 @@ public final class SynchronousDataTransaction: BaseDataTransaction { ) } - internal func autoCommit(waitForMerge: Bool) -> (hasChanges: Bool, error: CoreStoreError?) { - + internal func autoCommit( + waitForMerge: Bool + ) -> ( + hasChanges: Bool, + error: CoreStoreError? + ) { + self.isCommitted = true let result = self.context.saveSynchronously( waitForMerge: waitForMerge, diff --git a/Sources/UnsafeDataModelSchema.swift b/Sources/UnsafeDataModelSchema.swift index 494549d..a313b32 100644 --- a/Sources/UnsafeDataModelSchema.swift +++ b/Sources/UnsafeDataModelSchema.swift @@ -44,8 +44,11 @@ public final class UnsafeDataModelSchema: DynamicSchema { - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter model: the `NSManagedObjectModel` */ - public required init(modelName: ModelVersion, model: NSManagedObjectModel) { - + public required init( + modelName: ModelVersion, + model: NSManagedObjectModel + ) { + self.modelVersion = modelName self.model = model } diff --git a/Sources/UnsafeDataTransaction+Observing.swift b/Sources/UnsafeDataTransaction+Observing.swift index bd22faf..0c24c91 100644 --- a/Sources/UnsafeDataTransaction+Observing.swift +++ b/Sources/UnsafeDataTransaction+Observing.swift @@ -37,7 +37,9 @@ extension UnsafeDataTransaction { - parameter object: the `DynamicObject` to observe changes from - returns: an `ObjectMonitor` that monitors changes to `object` */ - public func monitorObject(_ object: O) -> ObjectMonitor { + public func monitorObject( + _ object: O + ) -> ObjectMonitor { return .init(objectID: object.cs_id(), context: self.unsafeContext()) } @@ -49,8 +51,11 @@ extension UnsafeDataTransaction { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorList(_ from: From, _ fetchClauses: FetchClause...) -> ListMonitor { - + public func monitorList( + _ from: From, + _ fetchClauses: FetchClause... + ) -> ListMonitor { + return self.monitorList(from, fetchClauses) } @@ -61,8 +66,11 @@ extension UnsafeDataTransaction { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorList(_ from: From, _ fetchClauses: [FetchClause]) -> ListMonitor { - + public func monitorList( + _ from: From, + _ fetchClauses: [FetchClause] + ) -> ListMonitor { + Internals.assert( fetchClauses.filter { $0 is OrderBy }.count > 0, "A ListMonitor requires an OrderBy clause." @@ -96,8 +104,10 @@ extension UnsafeDataTransaction { - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` */ - public func monitorList(_ clauseChain: B) -> ListMonitor { - + public func monitorList( + _ clauseChain: B + ) -> ListMonitor { + return self.monitorList(clauseChain.from, clauseChain.fetchClauses) } @@ -108,8 +118,12 @@ extension UnsafeDataTransaction { - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ fetchClauses: FetchClause...) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ fetchClauses: FetchClause... + ) { + self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses) } @@ -120,8 +134,12 @@ extension UnsafeDataTransaction { - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ fetchClauses: [FetchClause]) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ fetchClauses: [FetchClause] + ) { + Internals.assert( fetchClauses.filter { $0 is OrderBy }.count > 0, "A ListMonitor requires an OrderBy clause." @@ -155,8 +173,11 @@ extension UnsafeDataTransaction { - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses */ - public func monitorList(createAsynchronously: @escaping (ListMonitor) -> Void, _ clauseChain: B) { - + public func monitorList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ clauseChain: B + ) { + self.monitorList( createAsynchronously: createAsynchronously, clauseChain.from, @@ -172,8 +193,12 @@ extension UnsafeDataTransaction { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorSectionedList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor { - + public func monitorSectionedList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) -> ListMonitor { + return self.monitorSectionedList(from, sectionBy, fetchClauses) } @@ -185,8 +210,12 @@ extension UnsafeDataTransaction { - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ - public func monitorSectionedList(_ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor { - + public func monitorSectionedList( + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) -> ListMonitor { + Internals.assert( fetchClauses.filter { $0 is OrderBy }.count > 0, "A ListMonitor requires an OrderBy clause." @@ -216,8 +245,10 @@ extension UnsafeDataTransaction { - parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses - returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `SectionMonitorBuilderType` */ - public func monitorSectionedList(_ clauseChain: B) -> ListMonitor { - + public func monitorSectionedList( + _ clauseChain: B + ) -> ListMonitor { + return self.monitorSectionedList( clauseChain.from, clauseChain.sectionBy, @@ -233,8 +264,13 @@ extension UnsafeDataTransaction { - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) { - + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: FetchClause... + ) { + self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses) } @@ -246,7 +282,12 @@ extension UnsafeDataTransaction { - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ from: From, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) { + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ from: From, + _ sectionBy: SectionBy, + _ fetchClauses: [FetchClause] + ) { Internals.assert( fetchClauses.filter { $0 is OrderBy }.count > 0, @@ -281,7 +322,10 @@ extension UnsafeDataTransaction { - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses */ - public func monitorSectionedList(createAsynchronously: @escaping (ListMonitor) -> Void, _ clauseChain: B) { + public func monitorSectionedList( + createAsynchronously: @escaping (ListMonitor) -> Void, + _ clauseChain: B + ) { self.monitorSectionedList( createAsynchronously: createAsynchronously, diff --git a/Sources/UnsafeDataTransaction.swift b/Sources/UnsafeDataTransaction.swift index 2ec3f25..0dd4309 100644 --- a/Sources/UnsafeDataTransaction.swift +++ b/Sources/UnsafeDataTransaction.swift @@ -41,8 +41,10 @@ public final class UnsafeDataTransaction: BaseDataTransaction { - parameter completion: the block executed after the save completes. Success or failure is reported by the optional `error` argument of the block. */ - public func commit(_ completion: @escaping (_ error: CoreStoreError?) -> Void) { - + public func commit( + _ completion: @escaping (_ error: CoreStoreError?) -> Void + ) { + self.context.saveAsynchronously( sourceIdentifier: self.sourceIdentifier, completion: { (_, error) in @@ -58,8 +60,8 @@ public final class UnsafeDataTransaction: BaseDataTransaction { - throws: a `CoreStoreError` value indicating the failure. */ - public func commitAndWait() throws { - + public func commitAndWait() throws(CoreStoreError) { + if case (_, let error?) = self.context.saveSynchronously( waitForMerge: true, sourceIdentifier: self.sourceIdentifier @@ -111,8 +113,10 @@ public final class UnsafeDataTransaction: BaseDataTransaction { - parameter closure: the closure where changes can be made prior to the flush - throws: an error thrown from `closure`, or an error thrown by Core Data (usually validation errors or conflict errors) */ - public func flush(closure: () throws -> Void) rethrows { - + public func flush( + closure: () throws(any Swift.Error) -> Void + ) rethrows { + try closure() self.context.processPendingChanges() } diff --git a/Sources/Where.Expression.swift b/Sources/Where.Expression.swift index 198f800..53b0065 100644 --- a/Sources/Where.Expression.swift +++ b/Sources/Where.Expression.swift @@ -118,9 +118,15 @@ extension Where { let owner = dataStack.fetchOne(From().where((\.master ~ \.name) == "John")) ``` */ -public func ~(_ lhs: KeyPath, _ rhs: KeyPath) -> Where.Expression.SingleTarget, V> { +public func ~( + _ lhs: KeyPath, + _ rhs: KeyPath +) -> Where.Expression.SingleTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -129,9 +135,15 @@ public func ~().where((\.master ~ \.name) == "John")) ``` */ -public func ~ (_ lhs: KeyPath, _ rhs: KeyPath) -> Where.Expression.SingleTarget, V> { +public func ~ ( + _ lhs: KeyPath, + _ rhs: KeyPath +) -> Where.Expression.SingleTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -140,9 +152,15 @@ public func ~ ().where((\.master ~ \.pets).count() > 1)) ``` */ -public func ~ (_ lhs: KeyPath, _ rhs: KeyPath) -> Where.Expression.CollectionTarget, V> { +public func ~ ( + _ lhs: KeyPath, + _ rhs: KeyPath +) -> Where.Expression.CollectionTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -151,9 +169,15 @@ public func ~ ().where((\.master ~ \.pets).count() > 1)) ``` */ -public func ~ (_ lhs: KeyPath, _ rhs: KeyPath) -> Where.Expression.CollectionTarget, V> { +public func ~ ( + _ lhs: KeyPath, + _ rhs: KeyPath +) -> Where.Expression.CollectionTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -162,9 +186,15 @@ public func ~ ().where((\.spouse ~ \.father ~ \.name) == "John")) ``` */ -public func ~ (_ lhs: Where.Expression, _ rhs: KeyPath) -> Where.Expression { +public func ~ ( + _ lhs: Where.Expression, + _ rhs: KeyPath +) -> Where.Expression { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -173,9 +203,15 @@ public func ~ ().where((\.spouse ~ \.father ~ \.name) == "John")) ``` */ -public func ~ (_ lhs: Where.Expression, _ rhs: KeyPath) -> Where.Expression { +public func ~ ( + _ lhs: Where.Expression, + _ rhs: KeyPath +) -> Where.Expression { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -184,9 +220,15 @@ public func ~ ().where((\.spouse ~ \.father ~ \.children).count() > 0)) ``` */ -public func ~ (_ lhs: Where.Expression, _ rhs: KeyPath) -> Where.Expression.CollectionTarget, V> { +public func ~ ( + _ lhs: Where.Expression, + _ rhs: KeyPath +) -> Where.Expression.CollectionTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -195,9 +237,15 @@ public func ~ ().where((\.spouse ~ \.father ~ \.children).count() > 0)) ``` */ -public func ~ (_ lhs: Where.Expression, _ rhs: KeyPath) -> Where.Expression.CollectionTarget, V> { +public func ~ ( + _ lhs: Where.Expression, + _ rhs: KeyPath +) -> Where.Expression.CollectionTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } /** @@ -206,9 +254,15 @@ public func ~ ().where((\.spouse ~ \.pets ~ \.name).any() == "Spot")) ``` */ -public func ~ (_ lhs: Where.Expression, _ rhs: KeyPath) -> Where.Expression.CollectionTarget, V> { +public func ~ ( + _ lhs: Where.Expression, + _ rhs: KeyPath +) -> Where.Expression.CollectionTarget, V> { - return .init(lhs.cs_keyPathString, rhs.cs_keyPathString) + return .init( + lhs.cs_keyPathString, + rhs.cs_keyPathString + ) } @@ -220,7 +274,10 @@ public func ~ ().where((\.$master ~ \.$name) == "John")) ``` */ -public func ~ (_ lhs: KeyPath.Relationship>, _ rhs: KeyPath) -> Where.Expression.SingleTarget, K.DestinationValueType> where K.ObjectType == D.DestinationObjectType { +public func ~ ( + _ lhs: KeyPath.Relationship>, + _ rhs: KeyPath +) -> Where.Expression.SingleTarget, K.DestinationValueType> where K.ObjectType == D.DestinationObjectType { return .init( O.meta[keyPath: lhs].cs_keyPathString, diff --git a/Sources/Where.swift b/Sources/Where.swift index 93a6629..496e773 100644 --- a/Sources/Where.swift +++ b/Sources/Where.swift @@ -37,33 +37,59 @@ public struct Where: WhereClauseType, FetchClause, QueryClause /** Combines two `Where` predicates together using `AND` operator */ - public static func && (left: Where, right: Where) -> Where { - - return Where(NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])) + public static func && ( + left: Where, + right: Where + ) -> Where { + + return Where( + NSCompoundPredicate( + type: .and, + subpredicates: [left.predicate, right.predicate] + ) + ) } /** Combines two `Where` predicates together using `OR` operator */ - public static func || (left: Where, right: Where) -> Where { - - return Where(NSCompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate])) + public static func || ( + left: Where, + right: Where + ) -> Where { + + return Where( + NSCompoundPredicate( + type: .or, + subpredicates: [left.predicate, right.predicate] + ) + ) } /** Inverts the predicate of a `Where` clause using `NOT` operator */ - public static prefix func ! (clause: Where) -> Where { - - return Where(NSCompoundPredicate(type: .not, subpredicates: [clause.predicate])) + public static prefix func ! ( + clause: Where + ) -> Where { + + return Where( + NSCompoundPredicate( + type: .not, + subpredicates: [clause.predicate] + ) + ) } /** Combines two `Where` predicates together using `AND` operator. - returns: `left` if `right` is `nil`, otherwise equivalent to `(left && right)` */ - public static func &&? (left: Where, right: Where?) -> Where { - + public static func &&? ( + left: Where, + right: Where? + ) -> Where { + if let right = right { return left && right @@ -75,8 +101,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause Combines two `Where` predicates together using `AND` operator. - returns: `right` if `left` is `nil`, otherwise equivalent to `(left && right)` */ - public static func &&? (left: Where?, right: Where) -> Where { - + public static func &&? ( + left: Where?, + right: Where + ) -> Where { + if let left = left { return left && right @@ -88,8 +117,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause Combines two `Where` predicates together using `OR` operator. - returns: `left` if `right` is `nil`, otherwise equivalent to `(left || right)` */ - public static func ||? (left: Where, right: Where?) -> Where { - + public static func ||? ( + left: Where, + right: Where? + ) -> Where { + if let right = right { return left || right @@ -101,8 +133,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause Combines two `Where` predicates together using `OR` operator. - returns: `right` if `left` is `nil`, otherwise equivalent to `(left || right)` */ - public static func ||? (left: Where?, right: Where) -> Where { - + public static func ||? ( + left: Where?, + right: Where + ) -> Where { + if let left = left { return left || right @@ -123,7 +158,9 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter clause: the existing `Where` clause. */ - public init(_ clause: Where) { + public init( + _ clause: Where + ) { self.init(clause.predicate) } @@ -133,8 +170,10 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter value: the boolean value for the predicate */ - public init(_ value: Bool) { - + public init( + _ value: Bool + ) { + self.init(NSPredicate(value: value)) } @@ -144,8 +183,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter format: the format string for the predicate - parameter args: the arguments for `format` */ - public init(_ format: String, _ args: Any...) { - + public init( + _ format: String, + _ args: Any... + ) { + self.init(NSPredicate(format: format, argumentArray: args)) } @@ -155,8 +197,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter format: the format string for the predicate - parameter argumentArray: the arguments for `format` */ - public init(_ format: String, argumentArray: [Any]?) { - + public init( + _ format: String, + argumentArray: [Any]? + ) { + self.init(NSPredicate(format: format, argumentArray: argumentArray)) } @@ -166,8 +211,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter null: the arguments for the `==` operator */ - public init(_ keyPath: KeyPathString, isEqualTo null: Void?) { - + public init( + _ keyPath: KeyPathString, + isEqualTo null: Void? + ) { + self.init(NSPredicate(format: "\(keyPath) == nil")) } @@ -177,7 +225,10 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ - public init(_ keyPath: KeyPathString, isEqualTo value: V) { + public init( + _ keyPath: KeyPathString, + isEqualTo value: V + ) { var nilPredicate: NSPredicate { @@ -227,16 +278,28 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter value: the arguments for the `==` operator */ @_disfavoredOverload - public init(_ keyPath: KeyPathString, isEqualTo value: U?) { + public init( + _ keyPath: KeyPathString, + isEqualTo value: U? + ) { switch value { case nil, is NSNull: - self.init(NSPredicate(format: "\(keyPath) == nil")) + self.init( + NSPredicate( + format: "\(keyPath) == nil" + ) + ) case let value?: - self.init(NSPredicate(format: "\(keyPath) == %@", argumentArray: [value.cs_toQueryableNativeType()])) + self.init( + NSPredicate( + format: "\(keyPath) == %@", + argumentArray: [value.cs_toQueryableNativeType()] + ) + ) } } @@ -246,15 +309,27 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter object: the arguments for the `==` operator */ - public init(_ keyPath: KeyPathString, isEqualTo object: Other?) { + public init( + _ keyPath: KeyPathString, + isEqualTo object: Other? + ) { switch object { case nil: - self.init(NSPredicate(format: "\(keyPath) == nil")) - + self.init( + NSPredicate( + format: "\(keyPath) == nil" + ) + ) + case let object?: - self.init(NSPredicate(format: "\(keyPath) == %@", argumentArray: [object.cs_id()])) + self.init( + NSPredicate( + format: "\(keyPath) == %@", + argumentArray: [object.cs_id()] + ) + ) } } @@ -264,9 +339,17 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter objectID: the arguments for the `==` operator */ - public init(_ keyPath: KeyPathString, isEqualTo objectID: NSManagedObjectID) { - - self.init(NSPredicate(format: "\(keyPath) == %@", argumentArray: [objectID])) + public init( + _ keyPath: KeyPathString, + isEqualTo objectID: NSManagedObjectID + ) { + + self.init( + NSPredicate( + format: "\(keyPath) == %@", + argumentArray: [objectID] + ) + ) } /** @@ -275,9 +358,17 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPathString, isMemberOf list: S) where S.Iterator.Element: FieldStorableType { + public init( + _ keyPath: KeyPathString, + isMemberOf list: S + ) where S.Iterator.Element: FieldStorableType { - self.init(NSPredicate(format: "\(keyPath) IN %@", list.map({ $0.cs_toFieldStoredNativeType() }) as NSArray)) + self.init( + NSPredicate( + format: "\(keyPath) IN %@", + list.map({ $0.cs_toFieldStoredNativeType() }) as NSArray + ) + ) } /** @@ -287,9 +378,17 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter list: the sequence to check membership of */ @_disfavoredOverload - public init(_ keyPath: KeyPathString, isMemberOf list: S) where S.Iterator.Element: QueryableAttributeType { - - self.init(NSPredicate(format: "\(keyPath) IN %@", list.map({ $0.cs_toQueryableNativeType() }) as NSArray)) + public init( + _ keyPath: KeyPathString, + isMemberOf list: S + ) where S.Iterator.Element: QueryableAttributeType { + + self.init( + NSPredicate( + format: "\(keyPath) IN %@", + list.map({ $0.cs_toQueryableNativeType() }) as NSArray + ) + ) } /** @@ -298,9 +397,17 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPathString, isMemberOf list: S) where S.Iterator.Element: DynamicObject { - - self.init(NSPredicate(format: "\(keyPath) IN %@", list.map({ $0.cs_id() }) as NSArray)) + public init( + _ keyPath: KeyPathString, + isMemberOf list: S + ) where S.Iterator.Element: DynamicObject { + + self.init( + NSPredicate( + format: "\(keyPath) IN %@", + list.map({ $0.cs_id() }) as NSArray + ) + ) } /** @@ -309,9 +416,17 @@ public struct Where: WhereClauseType, FetchClause, QueryClause - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPathString, isMemberOf list: S) where S.Iterator.Element: NSManagedObjectID { - - self.init(NSPredicate(format: "\(keyPath) IN %@", list.map({ $0 }) as NSArray)) + public init( + _ keyPath: KeyPathString, + isMemberOf list: S + ) where S.Iterator.Element: NSManagedObjectID { + + self.init( + NSPredicate( + format: "\(keyPath) IN %@", + list.map({ $0 }) as NSArray + ) + ) } @@ -332,8 +447,10 @@ public struct Where: WhereClauseType, FetchClause, QueryClause // MARK: FetchClause, QueryClause, DeleteClause - public func applyToFetchRequest(_ fetchRequest: NSFetchRequest) { - + public func applyToFetchRequest( + _ fetchRequest: NSFetchRequest + ) { + if let predicate = fetchRequest.predicate, predicate != self.predicate { Internals.log( @@ -348,8 +465,11 @@ public struct Where: WhereClauseType, FetchClause, QueryClause // MARK: Equatable - public static func == (lhs: Where, rhs: Where) -> Bool { - + public static func == ( + lhs: Self, + rhs: Self + ) -> Bool { + return lhs.predicate == rhs.predicate } @@ -373,9 +493,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter null: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath, isEqualTo null: Void?) { - - self.init(keyPath._kvcKeyPathString!, isEqualTo: null) + public init( + _ keyPath: KeyPath, + isEqualTo null: Void? + ) { + + self.init( + keyPath._kvcKeyPathString!, + isEqualTo: null + ) } /** @@ -384,9 +510,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter null: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath, isEqualTo null: Void?) { - - self.init(keyPath._kvcKeyPathString!, isEqualTo: null) + public init( + _ keyPath: KeyPath, + isEqualTo null: Void? + ) { + + self.init( + keyPath._kvcKeyPathString!, + isEqualTo: null + ) } /** @@ -395,9 +527,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath, isEqualTo value: V?) { - - self.init(keyPath._kvcKeyPathString!, isEqualTo: value) + public init( + _ keyPath: KeyPath, + isEqualTo value: V? + ) { + + self.init( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -406,9 +544,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath, isEqualTo value: D?) { - - self.init(keyPath._kvcKeyPathString!, isEqualTo: value) + public init( + _ keyPath: KeyPath, + isEqualTo value: D? + ) { + + self.init( + keyPath._kvcKeyPathString!, + isEqualTo: value + ) } /** @@ -417,9 +561,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter objectID: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath, isEqualTo objectID: NSManagedObjectID) { - - self.init(keyPath._kvcKeyPathString!, isEqualTo: objectID) + public init( + _ keyPath: KeyPath, + isEqualTo objectID: NSManagedObjectID + ) { + + self.init( + keyPath._kvcKeyPathString!, + isEqualTo: objectID + ) } /** @@ -428,9 +578,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath, isMemberOf list: S) where S.Iterator.Element == V { - - self.init(keyPath._kvcKeyPathString!, isMemberOf: list) + public init( + _ keyPath: KeyPath, + isMemberOf list: S + ) where S.Iterator.Element == V { + + self.init( + keyPath._kvcKeyPathString!, + isMemberOf: list + ) } /** @@ -439,9 +595,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath, isMemberOf list: S) where S.Iterator.Element == D { - - self.init(keyPath._kvcKeyPathString!, isMemberOf: list) + public init( + _ keyPath: KeyPath, + isMemberOf list: S + ) where S.Iterator.Element == D { + + self.init( + keyPath._kvcKeyPathString!, + isMemberOf: list + ) } /** @@ -450,9 +612,15 @@ extension Where where O: NSManagedObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath, isMemberOf list: S) where S.Iterator.Element: NSManagedObjectID { - - self.init(keyPath._kvcKeyPathString!, isMemberOf: list) + public init( + _ keyPath: KeyPath, + isMemberOf list: S + ) where S.Iterator.Element: NSManagedObjectID { + + self.init( + keyPath._kvcKeyPathString!, + isMemberOf: list + ) } } @@ -467,9 +635,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath.Stored>, isEqualTo value: V) { + public init( + _ keyPath: KeyPath.Stored>, + isEqualTo value: V + ) { - self.init(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) + self.init( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: value + ) } /** @@ -478,9 +652,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter value: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath.Relationship>, isEqualTo value: V.DestinationObjectType?) { + public init( + _ keyPath: KeyPath.Relationship>, + isEqualTo value: V.DestinationObjectType? + ) { - self.init(O.meta[keyPath: keyPath].keyPath, isEqualTo: value) + self.init( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: value + ) } /** @@ -489,9 +669,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter null: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath.Stored>, isEqualTo null: Void?) { - - self.init(O.meta[keyPath: keyPath].keyPath, isEqualTo: null) + public init( + _ keyPath: KeyPath.Stored>, + isEqualTo null: Void? + ) { + + self.init( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: null + ) } /** @@ -500,9 +686,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter null: the arguments for the `==` operator */ - public init(_ keyPath: KeyPath.Relationship>, isEqualTo null: Void?) { - - self.init(O.meta[keyPath: keyPath].keyPath, isEqualTo: null) + public init( + _ keyPath: KeyPath.Relationship>, + isEqualTo null: Void? + ) { + + self.init( + O.meta[keyPath: keyPath].keyPath, + isEqualTo: null + ) } /** @@ -511,9 +703,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath.Stored>, isMemberOf list: S) where S.Iterator.Element == V { - - self.init(O.meta[keyPath: keyPath].keyPath, isMemberOf: list) + public init( + _ keyPath: KeyPath.Stored>, + isMemberOf list: S + ) where S.Iterator.Element == V { + + self.init( + O.meta[keyPath: keyPath].keyPath, + isMemberOf: list + ) } /** @@ -522,9 +720,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath.Relationship>, isMemberOf list: S) where S.Iterator.Element == V.DestinationObjectType { - - self.init(O.meta[keyPath: keyPath].keyPath, isMemberOf: list) + public init( + _ keyPath: KeyPath.Relationship>, + isMemberOf list: S + ) where S.Iterator.Element == V.DestinationObjectType { + + self.init( + O.meta[keyPath: keyPath].keyPath, + isMemberOf: list + ) } /** @@ -533,9 +737,15 @@ extension Where where O: CoreStoreObject { - parameter keyPath: the keyPath to compare with - parameter list: the sequence to check membership of */ - public init(_ keyPath: KeyPath.Relationship>, isMemberOf list: S) where S.Iterator.Element: NSManagedObjectID { - - self.init(O.meta[keyPath: keyPath].keyPath, isMemberOf: list) + public init( + _ keyPath: KeyPath.Relationship>, + isMemberOf list: S + ) where S.Iterator.Element: NSManagedObjectID { + + self.init( + O.meta[keyPath: keyPath].keyPath, + isMemberOf: list + ) } /** @@ -543,8 +753,10 @@ extension Where where O: CoreStoreObject { - parameter condition: closure that returns the `Where` clause */ - public init(_ condition: (O) -> Where) { - + public init( + _ condition: (O) -> Where + ) { + self = condition(O.meta) } } @@ -559,7 +771,12 @@ extension Sequence where Iterator.Element: WhereClauseType { */ public func combinedByAnd() -> Where { - return Where(NSCompoundPredicate(type: .and, subpredicates: self.map({ $0.predicate }))) + return Where( + NSCompoundPredicate( + type: .and, + subpredicates: self.map({ $0.predicate }) + ) + ) } /** @@ -567,7 +784,12 @@ extension Sequence where Iterator.Element: WhereClauseType { */ public func combinedByOr() -> Where { - return Where(NSCompoundPredicate(type: .or, subpredicates: self.map({ $0.predicate }))) + return Where( + NSCompoundPredicate( + type: .or, + subpredicates: self.map({ $0.predicate }) + ) + ) } } diff --git a/Sources/WhereClauseType.swift b/Sources/WhereClauseType.swift index 468afc7..ab28cc1 100644 --- a/Sources/WhereClauseType.swift +++ b/Sources/WhereClauseType.swift @@ -45,35 +45,67 @@ extension WhereClauseType { Combines two `Where` predicates together using `AND` operator. - Warning: This operator overload is a workaround for Swift generics' inability to constrain by inheritance (https://bugs.swift.org/browse/SR-5213). In effect, this is less type-safe than other overloads because it allows AND'ing clauses of unrelated `DynamicObject` types. */ - public static func && (left: Self, right: TWhere) -> Where { + public static func && ( + left: Self, + right: TWhere + ) -> Where { - return .init(NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])) + return .init( + NSCompoundPredicate( + type: .and, + subpredicates: [left.predicate, right.predicate] + ) + ) } /** Combines two `Where` predicates together using `AND` operator. - Warning: This operator overload is a workaround for Swift generics' inability to constrain by inheritance (https://bugs.swift.org/browse/SR-5213). In effect, this is less type-safe than other overloads because it allows AND'ing clauses of unrelated `DynamicObject` types. */ - public static func && (left: TWhere, right: Self) -> Where { + public static func && ( + left: TWhere, + right: Self + ) -> Where { - return .init(NSCompoundPredicate(type: .and, subpredicates: [left.predicate, right.predicate])) + return .init( + NSCompoundPredicate( + type: .and, + subpredicates: [left.predicate, right.predicate] + ) + ) } /** Combines two `Where` predicates together using `OR` operator. - Warning: This operator overload is a workaround for Swift generics' inability to constrain by inheritance (https://bugs.swift.org/browse/SR-5213). In effect, this is less type-safe than other overloads because it allows OR'ing clauses of unrelated `DynamicObject` types. */ - public static func || (left: Self, right: TWhere) -> Where { + public static func || ( + left: Self, + right: TWhere + ) -> Where { - return .init(NSCompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate])) + return .init( + NSCompoundPredicate( + type: .or, + subpredicates: [left.predicate, right.predicate] + ) + ) } /** Combines two `Where` predicates together using `OR` operator. - Warning: This operator overload is a workaround for Swift generics' inability to constrain by inheritance (https://bugs.swift.org/browse/SR-5213). In effect, this is less type-safe than other overloads because it allows OR'ing clauses of unrelated `DynamicObject` types. */ - public static func || (left: TWhere, right: Self) -> Where { + public static func || ( + left: TWhere, + right: Self + ) -> Where { - return .init(NSCompoundPredicate(type: .or, subpredicates: [left.predicate, right.predicate])) + return .init( + NSCompoundPredicate( + type: .or, + subpredicates: [left.predicate, right.predicate] + ) + ) } } diff --git a/Sources/XcodeDataModelSchema.swift b/Sources/XcodeDataModelSchema.swift index dea8ca5..af69321 100644 --- a/Sources/XcodeDataModelSchema.swift +++ b/Sources/XcodeDataModelSchema.swift @@ -46,8 +46,15 @@ public final class XcodeDataModelSchema: DynamicSchema { - parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. - returns: a tuple containing all `XcodeDataModelSchema` for the models declared in the specified .xcdatamodeld file, and the current model version string declared or inferred from the file. */ - public static func from(modelName: XcodeDataModelFileName, bundle: Bundle = Bundle.main, migrationChain: MigrationChain = nil) -> (allSchema: [XcodeDataModelSchema], currentModelVersion: ModelVersion) { - + public static func from( + modelName: XcodeDataModelFileName, + bundle: Bundle = Bundle.main, + migrationChain: MigrationChain = nil + ) -> ( + allSchema: [XcodeDataModelSchema], + currentModelVersion: ModelVersion + ) { + guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else { // For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model. @@ -116,8 +123,11 @@ public final class XcodeDataModelSchema: DynamicSchema { - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter bundle: the `Bundle` that contains the .xcdatamodeld's "momd" file. If not specified, the `Bundle.main` will be searched. */ - public convenience init(modelName: ModelVersion, bundle: Bundle = Bundle.main) { - + public convenience init( + modelName: ModelVersion, + bundle: Bundle = Bundle.main + ) { + guard let modelFilePath = bundle.path(forResource: modelName, ofType: "momd") else { // For users migrating from very old Xcode versions: Old xcdatamodel files are not contained inside xcdatamodeld (with a "d"), and will thus fail this check. If that was the case, create a new xcdatamodeld file and copy all contents into the new model. @@ -142,8 +152,11 @@ public final class XcodeDataModelSchema: DynamicSchema { - parameter modelName: the model version, typically the file name of an *.xcdatamodeld file (without the file extension) - parameter modelVersionFileURL: the file URL that points to the .xcdatamodeld's "momd" file. */ - public required init(modelName: ModelVersion, modelVersionFileURL: URL) { - + public required init( + modelName: ModelVersion, + modelVersionFileURL: URL + ) { + Internals.assert( NSManagedObjectModel(contentsOf: modelVersionFileURL) != nil, "Could not find the \"\(modelName).mom\" version file for the model at URL \"\(modelVersionFileURL)\"." diff --git a/Sources/XcodeSchemaMappingProvider.swift b/Sources/XcodeSchemaMappingProvider.swift index 56c92b5..3822a1e 100644 --- a/Sources/XcodeSchemaMappingProvider.swift +++ b/Sources/XcodeSchemaMappingProvider.swift @@ -56,8 +56,12 @@ public final class XcodeSchemaMappingProvider: Hashable, SchemaMappingProvider { - parameter destinationVersion: the destination model version for the mapping - parameter mappingModelBundle: the `Bundle` that contains the xcmappingmodel file */ - public required init(from sourceVersion: ModelVersion, to destinationVersion: ModelVersion, mappingModelBundle: Bundle) { - + public required init( + from sourceVersion: ModelVersion, + to destinationVersion: ModelVersion, + mappingModelBundle: Bundle + ) { + self.sourceVersion = sourceVersion self.destinationVersion = destinationVersion self.mappingModelBundle = mappingModelBundle @@ -85,8 +89,15 @@ public final class XcodeSchemaMappingProvider: Hashable, SchemaMappingProvider { // MARK: SchemaMappingProvider - public func cs_createMappingModel(from sourceSchema: DynamicSchema, to destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) { - + public func cs_createMappingModel( + from sourceSchema: DynamicSchema, + to destinationSchema: DynamicSchema, + storage: LocalStorage + ) throws(CoreStoreError) -> ( + mappingModel: NSMappingModel, + migrationType: MigrationType + ) { + let sourceModel = sourceSchema.rawModel() let destinationModel = destinationSchema.rawModel()