Implement initial store-migration functionality

This commit is contained in:
Angelo Stavrow 2021-10-08 17:16:01 -04:00
parent 2f1b895df5
commit f55ae3c621
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE

View File

@ -10,6 +10,17 @@ final class LocalStorageManager {
public static var standard = LocalStorageManager() public static var standard = LocalStorageManager()
public let container: NSPersistentContainer public let container: NSPersistentContainer
private var oldStoreURL: URL {
let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
return appSupport.appendingPathComponent("LocalStorageModel.sqlite")
}
private var sharedStoreURL: URL {
let id = "group.com.abunchtell.writefreely"
let groupContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: id)!
return groupContainer.appendingPathComponent("LocalStorageModel.sqlite")
}
init() { init() {
// Set up the persistent container. // Set up the persistent container.
container = NSPersistentContainer(name: "LocalStorageModel") container = NSPersistentContainer(name: "LocalStorageModel")
@ -56,6 +67,29 @@ final class LocalStorageManager {
print("Error: Failed to purge cached collections.") print("Error: Failed to purge cached collections.")
} }
} }
func migrateStore(for container: NSPersistentContainer) {
let coordinator = container.persistentStoreCoordinator
guard let oldStore = coordinator.persistentStore(for: oldStoreURL) else {
return
}
do {
try coordinator.migratePersistentStore(oldStore,
to: sharedStoreURL,
options: nil,
withType: NSSQLiteStoreType)
} catch {
fatalError("Something went wrong migrating the store: \(error)")
}
do {
try FileManager.default.removeItem(at: oldStoreURL)
} catch {
fatalError("Something went wrong while deleting the old store: \(error)")
}
}
} }
private extension LocalStorageManager { private extension LocalStorageManager {