CoreDataStack.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. container.loadPersistentStores { _, error in
  54. if let error = error as NSError? {
  55. fatalError("Unresolved Error \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  56. }
  57. }
  58. container.viewContext.automaticallyMergesChangesFromParent = false
  59. container.viewContext.name = "viewContext"
  60. /// - Tag: viewContextmergePolicy
  61. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  62. container.viewContext.undoManager = nil
  63. container.viewContext.shouldDeleteInaccessibleFaults = true
  64. return container
  65. }()
  66. /// Creates and configures a private queue context
  67. func newTaskContext() -> NSManagedObjectContext {
  68. // Create a private queue context
  69. /// - Tag: newBackgroundContext
  70. let taskContext = persistentContainer.newBackgroundContext()
  71. /// ensure that the background contexts stay in sync with the main context
  72. taskContext.automaticallyMergesChangesFromParent = true
  73. taskContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  74. taskContext.undoManager = nil
  75. return taskContext
  76. }
  77. func fetchPersistentHistory() async {
  78. do {
  79. try await fetchPersistentHistoryTransactionsAndChanges()
  80. } catch {
  81. debugPrint("\(error.localizedDescription)")
  82. }
  83. }
  84. private func fetchPersistentHistoryTransactionsAndChanges() async throws {
  85. let taskContext = newTaskContext()
  86. taskContext.name = "persistentHistoryContext"
  87. debugPrint("Start fetching persistent history changes from the store ... \(DebuggingIdentifiers.inProgress)")
  88. try await taskContext.perform {
  89. // Execute the persistent history change since the last transaction
  90. /// - Tag: fetchHistory
  91. let changeRequest = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
  92. let historyResult = try taskContext.execute(changeRequest) as? NSPersistentHistoryResult
  93. if let history = historyResult?.result as? [NSPersistentHistoryTransaction], !history.isEmpty {
  94. self.mergePersistentHistoryChanges(from: history)
  95. return
  96. }
  97. }
  98. }
  99. private func mergePersistentHistoryChanges(from history: [NSPersistentHistoryTransaction]) {
  100. debugPrint("Received \(history.count) persistent history transactions")
  101. // Update view context with objectIDs from history change request
  102. /// - Tag: mergeChanges
  103. let viewContext = persistentContainer.viewContext
  104. viewContext.perform {
  105. for transaction in history {
  106. viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
  107. self.lastToken = transaction.token
  108. }
  109. }
  110. }
  111. // Clean old Persistent History
  112. /// - Tag: clearHistory
  113. func cleanupPersistentHistoryTokens(before date: Date) async {
  114. let taskContext = newTaskContext()
  115. taskContext.name = "cleanPersistentHistoryTokensContext"
  116. await taskContext.perform {
  117. let deleteHistoryTokensRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date)
  118. do {
  119. try taskContext.execute(deleteHistoryTokensRequest)
  120. debugPrint("\(DebuggingIdentifiers.succeeded) Successfully deleted persistent history before \(date)")
  121. } catch {
  122. debugPrint(
  123. "\(DebuggingIdentifiers.failed) Failed to delete persistent history before \(date): \(error.localizedDescription)"
  124. )
  125. }
  126. }
  127. }
  128. }
  129. // MARK: - Delete
  130. extension CoreDataStack {
  131. /// Synchronously delete entry with specified object IDs
  132. /// - Tag: synchronousDelete
  133. func deleteObject(identifiedBy objectID: NSManagedObjectID) {
  134. let viewContext = persistentContainer.viewContext
  135. debugPrint("Start deleting data from the store ...\(DebuggingIdentifiers.inProgress)")
  136. viewContext.perform {
  137. do {
  138. let entryToDelete = viewContext.object(with: objectID)
  139. viewContext.delete(entryToDelete)
  140. guard viewContext.hasChanges else { return }
  141. try viewContext.save()
  142. debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  143. } catch {
  144. debugPrint("Failed to delete data: \(error.localizedDescription)")
  145. }
  146. }
  147. }
  148. /// Asynchronously deletes records for entities
  149. /// - Tag: batchDelete
  150. func batchDeleteOlderThan<T: NSManagedObject>(_ objectType: T.Type, dateKey: String, days: Int) async throws {
  151. let taskContext = newTaskContext()
  152. taskContext.name = "deleteContext"
  153. taskContext.transactionAuthor = "batchDelete"
  154. // Get the number of days we want to keep the data
  155. let targetDate = Calendar.current.date(byAdding: .day, value: -days, to: Date())!
  156. // Fetch all the objects that are older than the specified days
  157. let fetchRequest = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: objectType))
  158. fetchRequest.predicate = NSPredicate(format: "%K < %@", dateKey, targetDate as NSDate)
  159. fetchRequest.resultType = .managedObjectIDResultType
  160. do {
  161. // Execute the Fetch Request
  162. let objectIDs = try await taskContext.perform {
  163. try taskContext.fetch(fetchRequest)
  164. }
  165. // Guard check if there are NSManagedObjects older than 90 days
  166. guard !objectIDs.isEmpty else {
  167. debugPrint("No objects found older than \(days) days.")
  168. return
  169. }
  170. // Execute the Batch Delete
  171. try await taskContext.perform {
  172. let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  173. guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  174. let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  175. let success = batchDeleteResult.result as? Bool, success
  176. else {
  177. debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  178. throw CoreDataError.batchDeleteError
  179. }
  180. }
  181. debugPrint("Successfully deleted data older than \(days) days. \(DebuggingIdentifiers.succeeded)")
  182. } catch {
  183. debugPrint("Failed to fetch or delete data: \(error.localizedDescription) \(DebuggingIdentifiers.failed)")
  184. throw CoreDataError.batchDeleteError
  185. }
  186. }
  187. }
  188. // MARK: - Fetch Requests
  189. extension CoreDataStack {
  190. // Fetch in background thread
  191. /// - Tag: backgroundFetch
  192. func fetchEntities<T: NSManagedObject>(
  193. ofType type: T.Type,
  194. onContext context: NSManagedObjectContext,
  195. predicate: NSPredicate,
  196. key: String,
  197. ascending: Bool,
  198. fetchLimit: Int? = nil,
  199. batchSize: Int? = nil,
  200. propertiesToFetch: [String]? = nil,
  201. callingFunction: String = #function,
  202. callingClass: String = #fileID
  203. ) -> [T] {
  204. let request = NSFetchRequest<T>(entityName: String(describing: type))
  205. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  206. request.predicate = predicate
  207. if let limit = fetchLimit {
  208. request.fetchLimit = limit
  209. }
  210. if let batchSize = batchSize {
  211. request.fetchBatchSize = batchSize
  212. }
  213. if let propertiesTofetch = propertiesToFetch {
  214. request.propertiesToFetch = propertiesTofetch
  215. request.resultType = .managedObjectResultType
  216. } else {
  217. request.resultType = .managedObjectResultType
  218. }
  219. context.name = "fetchContext"
  220. context.transactionAuthor = "fetchEntities"
  221. var result: [T]?
  222. /// 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
  223. context.performAndWait {
  224. do {
  225. debugPrint(
  226. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  227. )
  228. result = try context.fetch(request)
  229. } catch let error as NSError {
  230. debugPrint(
  231. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  232. )
  233. }
  234. }
  235. return result ?? []
  236. }
  237. // 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
  238. // Fetch and update UI
  239. /// - Tag: uiFetch
  240. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  241. ofType type: T.Type,
  242. predicate: NSPredicate,
  243. key: String,
  244. ascending: Bool,
  245. fetchLimit: Int? = nil,
  246. batchSize: Int? = nil,
  247. propertiesToFetch: [String]? = nil,
  248. callingFunction: String = #function,
  249. callingClass: String = #fileID,
  250. completion: @escaping ([T]) -> Void
  251. ) {
  252. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  253. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  254. request.predicate = predicate
  255. request.resultType = .managedObjectIDResultType
  256. if let limit = fetchLimit {
  257. request.fetchLimit = limit
  258. }
  259. if let batchSize = batchSize {
  260. request.fetchBatchSize = batchSize
  261. }
  262. if let propertiesToFetch = propertiesToFetch {
  263. request.propertiesToFetch = propertiesToFetch
  264. }
  265. let taskContext = newTaskContext()
  266. taskContext.name = "fetchContext"
  267. taskContext.transactionAuthor = "fetchEntities"
  268. // perform fetch in the background
  269. //
  270. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  271. taskContext.perform {
  272. var result: [NSManagedObjectID]?
  273. do {
  274. debugPrint(
  275. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  276. )
  277. result = try taskContext.fetch(request)
  278. } catch let error as NSError {
  279. debugPrint(
  280. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  281. )
  282. }
  283. // change to the main queue to update UI
  284. DispatchQueue.main.async {
  285. if let result = result {
  286. debugPrint(
  287. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  288. )
  289. // Convert NSManagedObjectIDs to objects in the main context
  290. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  291. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  292. completion(mainContextObjects)
  293. } else {
  294. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  295. completion([])
  296. }
  297. }
  298. }
  299. }
  300. // Fetch the NSManagedObjectIDs
  301. // Useful if we need to pass the NSManagedObject to another thread as the objectID is thread safe
  302. /// - Tag: fetchIDs
  303. func fetchNSManagedObjectID<T: NSManagedObject>(
  304. ofType type: T.Type,
  305. predicate: NSPredicate,
  306. key: String,
  307. ascending: Bool,
  308. fetchLimit: Int? = nil,
  309. batchSize: Int? = nil,
  310. propertiesToFetch: [String]? = nil,
  311. callingFunction: String = #function,
  312. callingClass: String = #fileID,
  313. completion: @escaping ([NSManagedObjectID]) -> Void
  314. ) {
  315. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  316. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  317. request.predicate = predicate
  318. request.resultType = .managedObjectIDResultType
  319. if let limit = fetchLimit {
  320. request.fetchLimit = limit
  321. }
  322. if let batchSize = batchSize {
  323. request.fetchBatchSize = batchSize
  324. }
  325. if let propertiesToFetch = propertiesToFetch {
  326. request.propertiesToFetch = propertiesToFetch
  327. }
  328. let taskContext = newTaskContext()
  329. taskContext.name = "fetchContext"
  330. taskContext.transactionAuthor = "fetchEntities"
  331. // Perform fetch in the background
  332. taskContext.perform {
  333. var result: [NSManagedObjectID]?
  334. do {
  335. debugPrint(
  336. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  337. )
  338. result = try taskContext.fetch(request)
  339. } catch let error as NSError {
  340. debugPrint(
  341. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  342. )
  343. }
  344. completion(result ?? [])
  345. }
  346. }
  347. }
  348. // MARK: - Save
  349. extension NSManagedObjectContext {
  350. // takes a context as a parameter to be executed either on the main thread or on a background thread
  351. /// - Tag: save
  352. func saveContext(
  353. onContext: NSManagedObjectContext,
  354. callingFunction: String = #function,
  355. callingClass: String = #fileID
  356. ) throws {
  357. do {
  358. guard onContext.hasChanges else { return }
  359. try onContext.save()
  360. debugPrint(
  361. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  362. )
  363. } catch let error as NSError {
  364. debugPrint(
  365. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  366. )
  367. throw error
  368. }
  369. }
  370. }