CoreDataStack.swift 17 KB

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