CoreDataStack.swift 18 KB

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