CoreDataStack.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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) {
  138. let viewContext = persistentContainer.viewContext
  139. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  140. 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. }
  192. // MARK: - Fetch Requests
  193. extension CoreDataStack {
  194. // Fetch in background thread
  195. /// - Tag: backgroundFetch
  196. func fetchEntities<T: NSManagedObject>(
  197. ofType type: T.Type,
  198. onContext context: NSManagedObjectContext,
  199. predicate: NSPredicate,
  200. key: String,
  201. ascending: Bool,
  202. fetchLimit: Int? = nil,
  203. batchSize: Int? = nil,
  204. propertiesToFetch: [String]? = nil,
  205. callingFunction: String = #function,
  206. callingClass: String = #fileID
  207. ) -> [T] {
  208. let request = NSFetchRequest<T>(entityName: String(describing: type))
  209. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  210. request.predicate = predicate
  211. if let limit = fetchLimit {
  212. request.fetchLimit = limit
  213. }
  214. if let batchSize = batchSize {
  215. request.fetchBatchSize = batchSize
  216. }
  217. if let propertiesTofetch = propertiesToFetch {
  218. request.propertiesToFetch = propertiesTofetch
  219. request.resultType = .managedObjectResultType
  220. } else {
  221. request.resultType = .managedObjectResultType
  222. }
  223. context.name = "fetchContext"
  224. context.transactionAuthor = "fetchEntities"
  225. var result: [T]?
  226. /// 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
  227. context.performAndWait {
  228. do {
  229. debugPrint(
  230. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  231. )
  232. result = try context.fetch(request)
  233. } catch let error as NSError {
  234. debugPrint(
  235. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  236. )
  237. }
  238. }
  239. return result ?? []
  240. }
  241. // TODO: -refactor this, currently only the BolusStateModel uses this because we need to fetch in the background, then do calculations and after this update the UI
  242. // Fetch and update UI
  243. /// - Tag: uiFetch
  244. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  245. ofType type: T.Type,
  246. predicate: NSPredicate,
  247. key: String,
  248. ascending: Bool,
  249. fetchLimit: Int? = nil,
  250. batchSize: Int? = nil,
  251. propertiesToFetch: [String]? = nil,
  252. callingFunction: String = #function,
  253. callingClass: String = #fileID,
  254. completion: @escaping ([T]) -> Void
  255. ) {
  256. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  257. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  258. request.predicate = predicate
  259. request.resultType = .managedObjectIDResultType
  260. if let limit = fetchLimit {
  261. request.fetchLimit = limit
  262. }
  263. if let batchSize = batchSize {
  264. request.fetchBatchSize = batchSize
  265. }
  266. if let propertiesToFetch = propertiesToFetch {
  267. request.propertiesToFetch = propertiesToFetch
  268. }
  269. let taskContext = newTaskContext()
  270. taskContext.name = "fetchContext"
  271. taskContext.transactionAuthor = "fetchEntities"
  272. // perform fetch in the background
  273. //
  274. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  275. taskContext.perform {
  276. var result: [NSManagedObjectID]?
  277. do {
  278. debugPrint(
  279. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  280. )
  281. result = try taskContext.fetch(request)
  282. } catch let error as NSError {
  283. debugPrint(
  284. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  285. )
  286. }
  287. // change to the main queue to update UI
  288. DispatchQueue.main.async {
  289. if let result = result {
  290. debugPrint(
  291. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  292. )
  293. // Convert NSManagedObjectIDs to objects in the main context
  294. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  295. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  296. completion(mainContextObjects)
  297. } else {
  298. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  299. completion([])
  300. }
  301. }
  302. }
  303. }
  304. // Fetch the NSManagedObjectIDs
  305. // Useful if we need to pass the NSManagedObject to another thread as the objectID is thread safe
  306. /// - Tag: fetchIDs
  307. func fetchNSManagedObjectID<T: NSManagedObject>(
  308. ofType type: T.Type,
  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. completion: @escaping ([NSManagedObjectID]) -> Void
  318. ) {
  319. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  320. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  321. request.predicate = predicate
  322. request.resultType = .managedObjectIDResultType
  323. if let limit = fetchLimit {
  324. request.fetchLimit = limit
  325. }
  326. if let batchSize = batchSize {
  327. request.fetchBatchSize = batchSize
  328. }
  329. if let propertiesToFetch = propertiesToFetch {
  330. request.propertiesToFetch = propertiesToFetch
  331. }
  332. let taskContext = newTaskContext()
  333. taskContext.name = "fetchContext"
  334. taskContext.transactionAuthor = "fetchEntities"
  335. // Perform fetch in the background
  336. taskContext.perform {
  337. var result: [NSManagedObjectID]?
  338. do {
  339. debugPrint(
  340. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  341. )
  342. result = try taskContext.fetch(request)
  343. } catch let error as NSError {
  344. debugPrint(
  345. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  346. )
  347. }
  348. completion(result ?? [])
  349. }
  350. }
  351. }
  352. // MARK: - Save
  353. /// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
  354. extension CoreDataStack {
  355. func save() {
  356. let context = persistentContainer.viewContext
  357. guard context.hasChanges else { return }
  358. do {
  359. try context.save()
  360. } catch {
  361. debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
  362. }
  363. }
  364. }
  365. extension NSManagedObjectContext {
  366. // takes a context as a parameter to be executed either on the main thread or on a background thread
  367. /// - Tag: save
  368. func saveContext(
  369. onContext: NSManagedObjectContext,
  370. callingFunction: String = #function,
  371. callingClass: String = #fileID
  372. ) throws {
  373. do {
  374. guard onContext.hasChanges else { return }
  375. try onContext.save()
  376. debugPrint(
  377. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  378. )
  379. } catch let error as NSError {
  380. debugPrint(
  381. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  382. )
  383. throw error
  384. }
  385. }
  386. }