Skip to content

Instantly share code, notes, and snippets.

@valzevul
Created February 26, 2024 15:28
Show Gist options
  • Save valzevul/1713710b90b1ed4fae6fa45fb60ce120 to your computer and use it in GitHub Desktop.
Save valzevul/1713710b90b1ed4fae6fa45fb60ce120 to your computer and use it in GitHub Desktop.
Manual local migration for AWS DataStore
import SQLite
// Check that there is no other migration in progress and local DB files are present
// Backup the DB just in case
// ...
// URL to the local DB copy
let dataStoreLocalCopyURL = ...
do {
let decoder = JSONDecoder()
let db = try Connection(dataStoreLocalCopyURL.absoluteString)
let table = Table("MutationEvent")
let json = Expression<String>("json")
let modelName = Expression<String>("modelName")
let mutationType = Expression<String>("mutationType")
let preparedDB = try db.prepare(table)
var eventsCount = 0
let eventsForMigration: [String : Model.Type] = [
String(describing: ModelName.self) : ModelName.self,
// List of all models to migrate
// ...
]
for mutationEvent in preparedDB {
let json = mutationEvent[json]
let mutationType = MutationType(rawValue: mutationEvent[mutationType]) ?? .unknown
let modelName = mutationEvent[modelName]
guard let jsonData = json.data(using: .utf8) else {
fatalError("Invalid model")
continue
}
guard let event = eventsForMigration[modelName] else {
fatalError("Event does not support Migration")
continue
}
eventsCount += 1
let parsedEvent = try decoder.decode(event, from: jsonData)
switch mutationType {
case .create, .update:
AmplifyClient.save(model: parsedEvent)
case .delete:
AmplifyClient.delete(model: parsedEvent)
default:
break
}
}
} catch {
fatalError("Migration failed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment