CoreDataStack.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. func initializeStack() throws {
  132. // Force initialization of persistent container
  133. let container = persistentContainer
  134. // Verify the store is loaded and available
  135. guard container.persistentStoreCoordinator.persistentStores.isNotEmpty else {
  136. throw CoreDataError.storeNotInitializedError
  137. }
  138. }
  139. }
  140. // MARK: - Delete
  141. extension CoreDataStack {
  142. /// Synchronously delete entry with specified object IDs
  143. /// - Tag: synchronousDelete
  144. func deleteObject(identifiedBy objectID: NSManagedObjectID) async {
  145. let viewContext = persistentContainer.viewContext
  146. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  147. await viewContext.perform {
  148. do {
  149. let entryToDelete = viewContext.object(with: objectID)
  150. viewContext.delete(entryToDelete)
  151. guard viewContext.hasChanges else { return }
  152. try viewContext.save()
  153. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  154. } catch {
  155. debugPrint("Failed to delete data: \(error.localizedDescription)")
  156. }
  157. }
  158. }
  159. /// Asynchronously deletes records for entities
  160. /// - Tag: batchDelete
  161. func batchDeleteOlderThan<T: NSManagedObject>(
  162. _ objectType: T.Type,
  163. dateKey: String,
  164. days: Int,
  165. isPresetKey: String? = nil
  166. ) async throws {
  167. let taskContext = newTaskContext()
  168. taskContext.name = "deleteContext"
  169. taskContext.transactionAuthor = "batchDelete"
  170. // Get the number of days we want to keep the data
  171. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  172. // Fetch all the objects that are older than the specified days
  173. let fetchRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: objectType))
  174. // Construct the predicate
  175. var predicates: [NSPredicate] = [NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)]
  176. if let isPresetKey = isPresetKey {
  177. predicates.append(NSPredicate(format: "%K == NO", isPresetKey))
  178. }
  179. fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
  180. fetchRequest.resultType = .managedObjectIDResultType
  181. do {
  182. // Execute the Fetch Request
  183. let objectIDs = try await taskContext.perform {
  184. try taskContext.fetch(fetchRequest)
  185. }
  186. // Guard check if there are NSManagedObjects older than the specified days
  187. guard !objectIDs.isEmpty else {
  188. // debugPrint("No objects found older than \(days) days.")
  189. return
  190. }
  191. // Execute the Batch Delete
  192. try await taskContext.perform {
  193. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  194. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  195. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  196. let success = batchDeleteResult.result as? Bool, success
  197. else {
  198. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  199. throw CoreDataError.batchDeleteError
  200. }
  201. }
  202. debugPrint("Successfully deleted data older than \(days) days. \(DebuggingIdentifiers.succeeded)")
  203. } catch {
  204. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  205. throw CoreDataError.batchDeleteError
  206. }
  207. }
  208. func batchDeleteOlderThan<Parent: NSManagedObject, Child: NSManagedObject>(
  209. parentType: Parent.Type,
  210. childType: Child.Type,
  211. dateKey: String,
  212. days: Int,
  213. relationshipKey: String // The key of the Child Entity that links to the parent Entity
  214. ) async throws {
  215. let taskContext = newTaskContext()
  216. taskContext.name = "deleteContext"
  217. taskContext.transactionAuthor = "batchDelete"
  218. // Get the target date
  219. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  220. // Fetch Parent objects older than the target date
  221. let fetchParentRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: parentType))
  222. fetchParentRequest.predicate = NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)
  223. fetchParentRequest.resultType = .managedObjectIDResultType
  224. do {
  225. let parentObjectIDs = try await taskContext.perform {
  226. try taskContext.fetch(fetchParentRequest)
  227. }
  228. guard !parentObjectIDs.isEmpty else {
  229. // debugPrint("No \(parentType) objects found older than \(days) days.")
  230. return
  231. }
  232. // Fetch Child objects related to the fetched Parent objects
  233. let fetchChildRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: childType))
  234. fetchChildRequest.predicate = NSPredicate(format: "ANY %K IN %@", relationshipKey, parentObjectIDs)
  235. fetchChildRequest.resultType = .managedObjectIDResultType
  236. let childObjectIDs = try await taskContext.perform {
  237. try taskContext.fetch(fetchChildRequest)
  238. }
  239. guard !childObjectIDs.isEmpty else {
  240. // debugPrint("No \(childType) objects found related to \(parentType) objects older than \(days) days.")
  241. return
  242. }
  243. // Execute the batch delete for Child objects
  244. try await taskContext.perform {
  245. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: childObjectIDs)
  246. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  247. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  248. let success = batchDeleteResult.result as? Bool, success
  249. else {
  250. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  251. throw CoreDataError.batchDeleteError
  252. }
  253. }
  254. debugPrint(
  255. "Successfully deleted \(childType) data related to \(parentType) objects older than \(days) days. \(DebuggingIdentifiers.succeeded)"
  256. )
  257. } catch {
  258. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  259. throw CoreDataError.batchDeleteError
  260. }
  261. }
  262. }
  263. // MARK: - Fetch Requests
  264. extension CoreDataStack {
  265. // Fetch in background thread
  266. /// - Tag: backgroundFetch
  267. func fetchEntities<T: NSManagedObject>(
  268. ofType type: T.Type,
  269. onContext context: NSManagedObjectContext,
  270. predicate: NSPredicate,
  271. key: String,
  272. ascending: Bool,
  273. fetchLimit: Int? = nil,
  274. batchSize: Int? = nil,
  275. propertiesToFetch: [String]? = nil,
  276. callingFunction: String = #function,
  277. callingClass: String = #fileID
  278. ) -> [Any] {
  279. let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: type))
  280. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  281. request.predicate = predicate
  282. if let limit = fetchLimit {
  283. request.fetchLimit = limit
  284. }
  285. if let batchSize = batchSize {
  286. request.fetchBatchSize = batchSize
  287. }
  288. if let propertiesToFetch = propertiesToFetch {
  289. request.propertiesToFetch = propertiesToFetch
  290. request.resultType = .dictionaryResultType
  291. } else {
  292. request.resultType = .managedObjectResultType
  293. }
  294. context.name = "fetchContext"
  295. context.transactionAuthor = "fetchEntities"
  296. /// 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
  297. return context.performAndWait {
  298. do {
  299. if propertiesToFetch != nil {
  300. return try context.fetch(request) as? [[String: Any]] ?? []
  301. } else {
  302. return try context.fetch(request) as? [T] ?? []
  303. }
  304. } catch let error as NSError {
  305. debugPrint(
  306. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  307. )
  308. return []
  309. }
  310. }
  311. }
  312. // Fetch Async
  313. func fetchEntitiesAsync<T: NSManagedObject>(
  314. ofType type: T.Type,
  315. onContext context: NSManagedObjectContext,
  316. predicate: NSPredicate,
  317. key: String,
  318. ascending: Bool,
  319. fetchLimit: Int? = nil,
  320. batchSize: Int? = nil,
  321. propertiesToFetch: [String]? = nil,
  322. callingFunction: String = #function,
  323. callingClass: String = #fileID
  324. ) async -> Any {
  325. let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: String(describing: type))
  326. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  327. request.predicate = predicate
  328. if let limit = fetchLimit {
  329. request.fetchLimit = limit
  330. }
  331. if let batchSize = batchSize {
  332. request.fetchBatchSize = batchSize
  333. }
  334. if let propertiesToFetch = propertiesToFetch {
  335. request.propertiesToFetch = propertiesToFetch
  336. request.resultType = .dictionaryResultType
  337. } else {
  338. request.resultType = .managedObjectResultType
  339. }
  340. context.name = "fetchContext"
  341. context.transactionAuthor = "fetchEntities"
  342. return await context.perform {
  343. do {
  344. if propertiesToFetch != nil {
  345. return try context.fetch(request) as? [[String: Any]] ?? []
  346. } else {
  347. return try context.fetch(request) as? [T] ?? []
  348. }
  349. } catch let error as NSError {
  350. debugPrint(
  351. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  352. )
  353. return []
  354. }
  355. }
  356. }
  357. // Get NSManagedObject
  358. func getNSManagedObject<T: NSManagedObject>(
  359. with ids: [NSManagedObjectID],
  360. context: NSManagedObjectContext
  361. ) async -> [T] {
  362. await context.perform {
  363. var objects = [T]()
  364. do {
  365. for id in ids {
  366. if let object = try context.existingObject(with: id) as? T {
  367. objects.append(object)
  368. }
  369. }
  370. } catch {
  371. debugPrint("Failed to fetch objects: \(error.localizedDescription)")
  372. }
  373. return objects
  374. }
  375. }
  376. }
  377. // MARK: - Save
  378. /// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
  379. extension CoreDataStack {
  380. func save() {
  381. let context = persistentContainer.viewContext
  382. guard context.hasChanges else { return }
  383. do {
  384. try context.save()
  385. } catch {
  386. debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
  387. }
  388. }
  389. }
  390. extension NSManagedObjectContext {
  391. // takes a context as a parameter to be executed either on the main thread or on a background thread
  392. /// - Tag: save
  393. func saveContext(
  394. onContext: NSManagedObjectContext,
  395. callingFunction: String = #function,
  396. callingClass: String = #fileID
  397. ) throws {
  398. do {
  399. guard onContext.hasChanges else { return }
  400. try onContext.save()
  401. // debugPrint(
  402. // "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  403. // )
  404. } catch let error as NSError {
  405. debugPrint(
  406. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  407. )
  408. throw error
  409. }
  410. }
  411. }