CoreDataStack.swift 17 KB

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