CoreDataStack.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 cleanupPersistentHistory(before date: Date) async {
  114. let taskContext = newTaskContext()
  115. taskContext.name = "cleanPersistentHistoryContext"
  116. await taskContext.perform {
  117. let deleteHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: date)
  118. do {
  119. try taskContext.execute(deleteHistoryRequest)
  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
  149. /// - Tag: batchDelete
  150. // func batchDelete<T: NSManagedObject>(_ objects: [T]) async throws {
  151. // let objectIDs = objects.map(\.objectID)
  152. // let taskContext = newTaskContext()
  153. // // Add name and author to identify source of persistent history changes.
  154. // taskContext.name = "deleteContext"
  155. // taskContext.transactionAuthor = "batchDelete"
  156. // debugPrint("Start deleting data from the store... \(DebuggingIdentifiers.inProgress)")
  157. //
  158. // try await taskContext.perform {
  159. // // Execute the batch delete.
  160. // let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs)
  161. // guard let fetchResult = try? taskContext.execute(batchDeleteRequest),
  162. // let batchDeleteResult = fetchResult as? NSBatchDeleteResult,
  163. // let success = batchDeleteResult.result as? Bool, success
  164. // else {
  165. // debugPrint("Failed to execute batch delete request \(DebuggingIdentifiers.failed)")
  166. // throw CoreDataError.batchDeleteError
  167. // }
  168. // }
  169. //
  170. // debugPrint("Successfully deleted data. \(DebuggingIdentifiers.succeeded)")
  171. // }
  172. }
  173. // MARK: - Fetch Requests
  174. extension CoreDataStack {
  175. // Fetch in background thread
  176. /// - Tag: backgroundFetch
  177. func fetchEntities<T: NSManagedObject>(
  178. ofType type: T.Type,
  179. onContext context: NSManagedObjectContext,
  180. predicate: NSPredicate,
  181. key: String,
  182. ascending: Bool,
  183. fetchLimit: Int? = nil,
  184. batchSize: Int? = nil,
  185. propertiesToFetch: [String]? = nil,
  186. callingFunction: String = #function,
  187. callingClass: String = #fileID
  188. ) -> [T] {
  189. let request = NSFetchRequest<T>(entityName: String(describing: type))
  190. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  191. request.predicate = predicate
  192. if let limit = fetchLimit {
  193. request.fetchLimit = limit
  194. }
  195. if let batchSize = batchSize {
  196. request.fetchBatchSize = batchSize
  197. }
  198. if let propertiesTofetch = propertiesToFetch {
  199. request.propertiesToFetch = propertiesTofetch
  200. request.resultType = .managedObjectResultType
  201. } else {
  202. request.resultType = .managedObjectResultType
  203. }
  204. context.name = "fetchContext"
  205. context.transactionAuthor = "fetchEntities"
  206. var result: [T]?
  207. /// 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
  208. context.performAndWait {
  209. do {
  210. debugPrint(
  211. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on Thread: \(Thread.current)"
  212. )
  213. result = try context.fetch(request)
  214. } catch let error as NSError {
  215. debugPrint(
  216. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on Thread: \(Thread.current)"
  217. )
  218. }
  219. }
  220. return result ?? []
  221. }
  222. // 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
  223. // Fetch and update UI
  224. /// - Tag: uiFetch
  225. func fetchEntitiesAndUpdateUI<T: NSManagedObject>(
  226. ofType type: T.Type,
  227. predicate: NSPredicate,
  228. key: String,
  229. ascending: Bool,
  230. fetchLimit: Int? = nil,
  231. batchSize: Int? = nil,
  232. propertiesToFetch: [String]? = nil,
  233. callingFunction: String = #function,
  234. callingClass: String = #fileID,
  235. completion: @escaping ([T]) -> Void
  236. ) {
  237. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  238. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  239. request.predicate = predicate
  240. request.resultType = .managedObjectIDResultType
  241. if let limit = fetchLimit {
  242. request.fetchLimit = limit
  243. }
  244. if let batchSize = batchSize {
  245. request.fetchBatchSize = batchSize
  246. }
  247. if let propertiesToFetch = propertiesToFetch {
  248. request.propertiesToFetch = propertiesToFetch
  249. }
  250. let taskContext = newTaskContext()
  251. taskContext.name = "fetchContext"
  252. taskContext.transactionAuthor = "fetchEntities"
  253. // perform fetch in the background
  254. //
  255. // the fetch returns a NSManagedObjectID which can be safely passed to the main queue because they are thread safe
  256. taskContext.perform {
  257. var result: [NSManagedObjectID]?
  258. do {
  259. debugPrint(
  260. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  261. )
  262. result = try taskContext.fetch(request)
  263. } catch let error as NSError {
  264. debugPrint(
  265. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  266. )
  267. }
  268. // change to the main queue to update UI
  269. DispatchQueue.main.async {
  270. if let result = result {
  271. debugPrint(
  272. "Returning fetch result to main thread in \(callingFunction) from \(callingClass) on thread \(Thread.current)"
  273. )
  274. // Convert NSManagedObjectIDs to objects in the main context
  275. let mainContext = CoreDataStack.shared.persistentContainer.viewContext
  276. let mainContextObjects = result.compactMap { mainContext.object(with: $0) as? T }
  277. completion(mainContextObjects)
  278. } else {
  279. debugPrint("Fetch result is nil in \(callingFunction) from \(callingClass) on thread \(Thread.current)")
  280. completion([])
  281. }
  282. }
  283. }
  284. }
  285. // Fetch the NSManagedObjectIDs
  286. // Useful if we need to pass the NSManagedObject to another thread as the objectID is thread safe
  287. /// - Tag: fetchIDs
  288. func fetchNSManagedObjectID<T: NSManagedObject>(
  289. ofType type: T.Type,
  290. predicate: NSPredicate,
  291. key: String,
  292. ascending: Bool,
  293. fetchLimit: Int? = nil,
  294. batchSize: Int? = nil,
  295. propertiesToFetch: [String]? = nil,
  296. callingFunction: String = #function,
  297. callingClass: String = #fileID,
  298. completion: @escaping ([NSManagedObjectID]) -> Void
  299. ) {
  300. let request = NSFetchRequest<NSManagedObjectID>(entityName: String(describing: type))
  301. request.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
  302. request.predicate = predicate
  303. request.resultType = .managedObjectIDResultType
  304. if let limit = fetchLimit {
  305. request.fetchLimit = limit
  306. }
  307. if let batchSize = batchSize {
  308. request.fetchBatchSize = batchSize
  309. }
  310. if let propertiesToFetch = propertiesToFetch {
  311. request.propertiesToFetch = propertiesToFetch
  312. }
  313. let taskContext = newTaskContext()
  314. taskContext.name = "fetchContext"
  315. taskContext.transactionAuthor = "fetchEntities"
  316. // Perform fetch in the background
  317. taskContext.perform {
  318. var result: [NSManagedObjectID]?
  319. do {
  320. debugPrint(
  321. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.succeeded) on thread \(Thread.current)"
  322. )
  323. result = try taskContext.fetch(request)
  324. } catch let error as NSError {
  325. debugPrint(
  326. "Fetching \(T.self) in \(callingFunction) from \(callingClass): \(DebuggingIdentifiers.failed) \(error) on thread \(Thread.current)"
  327. )
  328. }
  329. completion(result ?? [])
  330. }
  331. }
  332. }
  333. // MARK: - Save
  334. extension NSManagedObjectContext {
  335. // takes a context as a parameter to be executed either on the main thread or on a background thread
  336. /// - Tag: save
  337. func saveContext(
  338. onContext: NSManagedObjectContext,
  339. callingFunction: String = #function,
  340. callingClass: String = #fileID
  341. ) throws {
  342. do {
  343. guard onContext.hasChanges else { return }
  344. try onContext.save()
  345. debugPrint(
  346. "Saving to Core Data successful in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.succeeded)"
  347. )
  348. } catch let error as NSError {
  349. debugPrint(
  350. "Saving to Core Data failed in \(callingFunction) in \(callingClass): \(DebuggingIdentifiers.failed) with error \(error), \(error.userInfo)"
  351. )
  352. throw error
  353. }
  354. }
  355. }