CoreDataStack.swift 17 KB

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