CoreDataStack.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import CoreData
  2. import Foundation
  3. import OSLog
  4. class CoreDataStack: ObservableObject {
  5. static let shared = CoreDataStack()
  6. static let identifier = "CoreDataStack"
  7. private var notificationToken: NSObjectProtocol?
  8. private let inMemory: Bool
  9. private init(inMemory: Bool = false) {
  10. self.inMemory = inMemory
  11. // Observe Core Data remote change notifications on the queue where the changes were made
  12. notificationToken = Foundation.NotificationCenter.default.addObserver(
  13. forName: .NSPersistentStoreRemoteChange,
  14. object: nil,
  15. queue: nil
  16. ) { _ in
  17. Task {
  18. await self.fetchPersistentHistory()
  19. }
  20. }
  21. }
  22. deinit {
  23. if let observer = notificationToken {
  24. Foundation.NotificationCenter.default.removeObserver(observer)
  25. }
  26. }
  27. /// A persistent history token used for fetching transactions from the store
  28. /// Save the last token to User defaults
  29. private var lastToken: NSPersistentHistoryToken? {
  30. get {
  31. UserDefaults.standard.lastHistoryToken
  32. }
  33. set {
  34. UserDefaults.standard.lastHistoryToken = newValue
  35. }
  36. }
  37. // Factory method for tests
  38. static func createForTests() -> CoreDataStack {
  39. CoreDataStack(inMemory: true)
  40. }
  41. /// A persistent container to set up the Core Data Stack
  42. lazy var persistentContainer: NSPersistentContainer = {
  43. let container = NSPersistentContainer(name: "TrioCoreDataPersistentContainer")
  44. guard let description = container.persistentStoreDescriptions.first else {
  45. fatalError("Failed \(DebuggingIdentifiers.failed) to retrieve a persistent store description")
  46. }
  47. if inMemory {
  48. description.url = URL(fileURLWithPath: "/dev/null")
  49. }
  50. // Enable persistent store remote change notifications
  51. /// - Tag: persistentStoreRemoteChange
  52. description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
  53. // Enable persistent history tracking
  54. /// - Tag: persistentHistoryTracking
  55. description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
  56. // Enable lightweight migration
  57. /// - Tag: lightweightMigration
  58. description.shouldMigrateStoreAutomatically = true
  59. description.shouldInferMappingModelAutomatically = true
  60. container.loadPersistentStores { _, error in
  61. if let error = error as NSError? {
  62. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  63. }
  64. }
  65. container.viewContext.automaticallyMergesChangesFromParent = false
  66. container.viewContext.name = "viewContext"
  67. /// - Tag: viewContextmergePolicy
  68. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  69. container.viewContext.undoManager = nil
  70. container.viewContext.shouldDeleteInaccessibleFaults = true
  71. return container
  72. }()
  73. /// Creates and configures a private queue context
  74. func newTaskContext() -> NSManagedObjectContext {
  75. // Create a private queue context
  76. /// - Tag: newBackgroundContext
  77. let taskContext = persistentContainer.newBackgroundContext()
  78. /// ensure that the background contexts stay in sync with the main context
  79. taskContext.automaticallyMergesChangesFromParent = false
  80. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  81. taskContext.undoManager = nil
  82. return taskContext
  83. }
  84. func fetchPersistentHistory() async {
  85. do {
  86. try await fetchPersistentHistoryTransactionsAndChanges()
  87. } catch {
  88. debugPrint("\(error.localizedDescription)")
  89. }
  90. }
  91. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  92. let taskContext = newTaskContext()
  93. taskContext.name = "persistentHistoryContext"
  94. // debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  95. try await taskContext.perform {
  96. // Execute the persistent history change since the last transaction
  97. /// - Tag: fetchHistory
  98. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  99. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  100. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  101. self.mergePersistentHistoryChanges(from: history)
  102. return
  103. }
  104. }
  105. }
  106. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  107. // debugPrint("Received \(history.count) persistent history transactions")
  108. // Update view context with objectIDs from history change request
  109. /// - Tag: mergeChanges
  110. let viewContext = persistentContainer.viewContext
  111. viewContext.perform {
  112. for transaction in history {
  113. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  114. self.lastToken = transaction.token
  115. }
  116. }
  117. }
  118. // Clean old Persistent History
  119. /// - Tag: clearHistory
  120. func cleanupPersistentHistoryTokens(before date: Date) async {
  121. let taskContext = newTaskContext()
  122. taskContext.name = "cleanPersistentHistoryTokensContext"
  123. await taskContext.perform {
  124. let deleteHistoryTokensRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date)
  125. do {
  126. try taskContext.execute(deleteHistoryTokensRequest)
  127. debugPrint("\(DebuggingIdentifiers.succeeded) Successfully deleted persistent history before \(date)")
  128. } catch {
  129. debugPrint(
  130. "\(DebuggingIdentifiers.failed) Failed to delete persistent history before \(date): \(error.localizedDescription)"
  131. )
  132. }
  133. }
  134. }
  135. }
  136. // MARK: - Delete
  137. extension CoreDataStack {
  138. /// Synchronously delete entry with specified object IDs
  139. /// - Tag: synchronousDelete
  140. func deleteObject(identifiedBy objectID: NSManagedObjectID) async {
  141. let viewContext = persistentContainer.viewContext
  142. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  143. await viewContext.perform {
  144. do {
  145. let entryToDelete = viewContext.object(with: objectID)
  146. viewContext.delete(entryToDelete)
  147. guard viewContext.hasChanges else { return }
  148. try viewContext.save()
  149. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  150. } catch {
  151. debugPrint("Failed to delete data: \(error.localizedDescription)")
  152. }
  153. }
  154. }
  155. /// Asynchronously deletes records for entities
  156. /// - Tag: batchDelete
  157. func batchDeleteOlderThan<T: NSManagedObject>(
  158. _ objectType: T.Type,
  159. dateKey: String,
  160. days: Int,
  161. isPresetKey: String? = nil
  162. ) async throws {
  163. let taskContext = newTaskContext()
  164. taskContext.name = "deleteContext"
  165. taskContext.transactionAuthor = "batchDelete"
  166. // Get the number of days we want to keep the data
  167. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  168. // Fetch all the objects that are older than the specified days
  169. let fetchRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: objectType))
  170. // Construct the predicate
  171. var predicates: [NSPredicate] = [NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)]
  172. if let isPresetKey = isPresetKey {
  173. predicates.append(NSPredicate(format: "%K == NO", isPresetKey))
  174. }
  175. fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
  176. fetchRequest.resultType = .managedObjectIDResultType
  177. do {
  178. // Execute the Fetch Request
  179. let objectIDs = try await taskContext.perform {
  180. try taskContext.fetch(fetchRequest)
  181. }
  182. // Guard check if there are NSManagedObjects older than the specified days
  183. guard !objectIDs.isEmpty else {
  184. // debugPrint("No objects found older than \(days) days.")
  185. return
  186. }
  187. // Execute the Batch Delete
  188. try await taskContext.perform {
  189. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  190. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  191. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  192. let success = batchDeleteResult.result as? Bool, success
  193. else {
  194. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  195. throw CoreDataError.batchDeleteError
  196. }
  197. }
  198. debugPrint("Successfully deleted data older than \(days) days. \(DebuggingIdentifiers.succeeded)")
  199. } catch {
  200. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  201. throw CoreDataError.batchDeleteError
  202. }
  203. }
  204. func batchDeleteOlderThan<Parent: NSManagedObject, Child: NSManagedObject>(
  205. parentType: Parent.Type,
  206. childType: Child.Type,
  207. dateKey: String,
  208. days: Int,
  209. relationshipKey: String // The key of the Child Entity that links to the parent Entity
  210. ) async throws {
  211. let taskContext = newTaskContext()
  212. taskContext.name = "deleteContext"
  213. taskContext.transactionAuthor = "batchDelete"
  214. // Get the target date
  215. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  216. // Fetch Parent objects older than the target date
  217. let fetchParentRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: parentType))
  218. fetchParentRequest.predicate = NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)
  219. fetchParentRequest.resultType = .managedObjectIDResultType
  220. do {
  221. let parentObjectIDs = try await taskContext.perform {
  222. try taskContext.fetch(fetchParentRequest)
  223. }
  224. guard !parentObjectIDs.isEmpty else {
  225. // debugPrint("No \(parentType) objects found older than \(days) days.")
  226. return
  227. }
  228. // Fetch Child objects related to the fetched Parent objects
  229. let fetchChildRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: childType))
  230. fetchChildRequest.predicate = NSPredicate(format: "ANY %K IN %@", relationshipKey, parentObjectIDs)
  231. fetchChildRequest.resultType = .managedObjectIDResultType
  232. let childObjectIDs = try await taskContext.perform {
  233. try taskContext.fetch(fetchChildRequest)
  234. }
  235. guard !childObjectIDs.isEmpty else {
  236. // debugPrint("No \(childType) objects found related to \(parentType) objects older than \(days) days.")
  237. return
  238. }
  239. // Execute the batch delete for Child objects
  240. try await taskContext.perform {
  241. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: childObjectIDs)
  242. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  243. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  244. let success = batchDeleteResult.result as? Bool, success
  245. else {
  246. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  247. throw CoreDataError.batchDeleteError
  248. }
  249. }
  250. debugPrint(
  251. "Successfully deleted \(childType) data related to \(parentType) objects older than \(days) days. \(DebuggingIdentifiers.succeeded)"
  252. )
  253. } catch {
  254. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  255. throw CoreDataError.batchDeleteError
  256. }
  257. }
  258. }
  259. // MARK: - Fetch Requests
  260. extension CoreDataStack {
  261. // Fetch in background thread
  262. /// - Tag: backgroundFetch
  263. func fetchEntities<T: NSManagedObject>(
  264. ofType type: T.Type,
  265. onContext context: NSManagedObjectContext,
  266. predicate: NSPredicate,
  267. key: String,
  268. ascending: Bool,
  269. fetchLimit: Int? = nil,
  270. batchSize: Int? = nil,
  271. propertiesToFetch: [String]? = nil,
  272. callingFunction: String = #function,
  273. callingClass: String = #fileID
  274. ) -> [Any] {
  275. let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: type))
  276. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  277. request.predicate = predicate
  278. if let limit = fetchLimit {
  279. request.fetchLimit = limit
  280. }
  281. if let batchSize = batchSize {
  282. request.fetchBatchSize = batchSize
  283. }
  284. if let propertiesToFetch = propertiesToFetch {
  285. request.propertiesToFetch = propertiesToFetch
  286. request.resultType = .dictionaryResultType
  287. } else {
  288. request.resultType = .managedObjectResultType
  289. }
  290. context.name = "fetchContext"
  291. context.transactionAuthor = "fetchEntities"
  292. /// we need to ensure that the fetch immediately returns a value as long as the whole app does not use the async await pattern, otherwise we could perform this asynchronously with backgroundContext.perform and not block the thread
  293. return context.performAndWait {
  294. do {
  295. if propertiesToFetch != nil {
  296. return try context.fetch(request) as? [[String: Any]] ?? []
  297. } else {
  298. return try context.fetch(request) as? [T] ?? []
  299. }
  300. } catch let error as NSError {
  301. debugPrint(
  302. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  303. )
  304. return []
  305. }
  306. }
  307. }
  308. // Fetch Async
  309. func fetchEntitiesAsync<T: NSManagedObject>(
  310. ofType type: T.Type,
  311. onContext context: NSManagedObjectContext,
  312. predicate: NSPredicate,
  313. key: String,
  314. ascending: Bool,
  315. fetchLimit: Int? = nil,
  316. batchSize: Int? = nil,
  317. propertiesToFetch: [String]? = nil,
  318. callingFunction: String = #function,
  319. callingClass: String = #fileID
  320. ) async -> Any {
  321. let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: String(describing: type))
  322. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  323. request.predicate = predicate
  324. if let limit = fetchLimit {
  325. request.fetchLimit = limit
  326. }
  327. if let batchSize = batchSize {
  328. request.fetchBatchSize = batchSize
  329. }
  330. if let propertiesToFetch = propertiesToFetch {
  331. request.propertiesToFetch = propertiesToFetch
  332. request.resultType = .dictionaryResultType
  333. } else {
  334. request.resultType = .managedObjectResultType
  335. }
  336. context.name = "fetchContext"
  337. context.transactionAuthor = "fetchEntities"
  338. return await context.perform {
  339. do {
  340. if propertiesToFetch != nil {
  341. return try context.fetch(request) as? [[String: Any]] ?? []
  342. } else {
  343. return try context.fetch(request) as? [T] ?? []
  344. }
  345. } catch let error as NSError {
  346. debugPrint(
  347. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  348. )
  349. return []
  350. }
  351. }
  352. }
  353. // Get NSManagedObject
  354. func getNSManagedObject<T: NSManagedObject>(
  355. with ids: [NSManagedObjectID],
  356. context: NSManagedObjectContext
  357. ) async -> [T] {
  358. await context.perform {
  359. var objects = [T]()
  360. do {
  361. for id in ids {
  362. if let object = try context.existingObject(with: id) as? T {
  363. objects.append(object)
  364. }
  365. }
  366. } catch {
  367. debugPrint("Failed to fetch objects: \(error.localizedDescription)")
  368. }
  369. return objects
  370. }
  371. }
  372. }
  373. // MARK: - Save
  374. /// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
  375. extension CoreDataStack {
  376. func save() {
  377. let context = persistentContainer.viewContext
  378. guard context.hasChanges else { return }
  379. do {
  380. try context.save()
  381. } catch {
  382. debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
  383. }
  384. }
  385. }
  386. extension NSManagedObjectContext {
  387. // takes a context as a parameter to be executed either on the main thread or on a background thread
  388. /// - Tag: save
  389. func saveContext(
  390. onContext: NSManagedObjectContext,
  391. callingFunction: String = #function,
  392. callingClass: String = #fileID
  393. ) throws {
  394. do {
  395. guard onContext.hasChanges else { return }
  396. try onContext.save()
  397. // debugPrint(
  398. // "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  399. // )
  400. } catch let error as NSError {
  401. debugPrint(
  402. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  403. )
  404. throw error
  405. }
  406. }
  407. }