Can SwiftData guarantee full rollback after a failed migration step?
0 reputation · 27 Jul 2025, 05:58 UTC
0 reputation · 27 Jul 2025, 05:58 UTC
The goal is to preserve data integrity when a schema change fails during a migration. SwiftData wraps migration steps in a database transaction but the exact boundary—whether the rollback occurs before any schema alterations or after the schema is applied—is not explicitly documented. Developers can insert custom MigrationStage implementations to add savepoints and manual control, yet it is unclear how these stages interact with the underlying SQLite transaction.
Constraints include the default SQLite store’s journal mode, potential differences when using in‑memory or CloudKit‑backed stores, and the fact that lightweight migrations hide transaction control from the developer. The unresolved decision is whether a failed migration will always revert the store to its previous version or if partial schema changes might persist.
Questions for clarification:
MigrationStage reliably enforce a full rollback of both data and schema changes if an error occurs later in the migration plan?34775 reputation · 27 Jul 2025, 09:49 UTC
Yes – for the default SQLite store SwiftData guarantees a full rollback of both data and schema changes when any migration step throws an error.
SwiftData wraps each migration step (including the inferred lightweight‑migration steps) in a single SQLite transaction. If the step throws, the transaction is rolled back, which restores the store to the exact state it had before the migration began.
MigrationStage (e.g., by calling save() or using NSPersistentStoreCoordinator.execute(_:)), the automatic rollback is bypassed and partial changes may persist.NSPersistentStore subclass requires you to verify that it participates in the same transaction semantics.throw MigrationError.failed).sqlite3 command line: sqlite3 MyStore.sqlite ".schema" and verify that the schema alteration is absent and the data matches the pre‑migration state.PRAGMA journal_mode; to confirm the store is using the default (DELETE) or WAL mode; the rollback works regardless of the mode as long as no commit occurred.If you are using a CloudKit‑backed or in‑memory store, please confirm the store type so the recommendation can be adjusted.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.