Dress Rehearsal for SwiftData: Testing Schema Changes on Copies of Real User Stores
Photo: Subhashish Panigrahi, CC BY-SA 3.0, via Wikimedia Commons
Every schema change is a database deployment wearing a SwiftUI hoodie. It arrives as a pull request, gets reviewed like code, and merges like code — but the moment a container opens on a store holding three years of somebody's notes, your app is doing DBA work at 7:42 on a Tuesday morning.
That is the part nobody rehearses. So before a SwiftData release goes out, we run a dress rehearsal against copies of real store files. Not in-memory containers, not a fresh simulator install. Real files, real row counts, real garbage.
The simulator is a liar with an empty store
A lightweight migration across zero rows is a formality. It will pass every time, and it will tell you nothing. Users show up with duplicate rows, relationships that point at objects deleted two iOS versions ago, and fields that were technically non-optional but happened to be nil in about forty records.
So the first rule of the rehearsal: the test data has to be data you did not invent.
Step 1: Capture the store, all three files
SwiftData sits on SQLite underneath, which means a store is not a single file. Copy the trio together — default.store, default.store-shm, and default.store-wal — or you will rehearse against a version of reality missing yesterday's writes. The WAL file is where the interesting bugs live.
We pull snapshots from internal TestFlight builds and from a small set of opt-in testers, then scrub anything personal and drop the files into a Fixtures/Stores directory that stays out of the repo. Keep at least two snapshots: one small, one from your heaviest user. If the biggest store you have is under a megabyte, you do not know what your launch path costs yet.
Step 2: Build a rehearsal harness, not another unit test
A migration test that constructs its own models proves that your code compiles. A harness that opens a copied store proves the migration works.
Start by pinning versions. Versioned schemas give you a stable name to migrate from and to.
enum StoreV1: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] { [Note.self] }
@Model final class Note {
var title: String
var createdAt: Date
init(title: String, createdAt: Date = .now) {
self.title = title
self.createdAt = createdAt
}
}
}
Version two adds tags and a relationship. Note that the old attribute names stay recoverable through originalName, which is the difference between a clean light migration and a column that silently comes back empty.
Step 3: Rehearse the stage you actually wrote
A migration plan is only as good as the closure bodies inside it. Custom stages are where deduplication and backfill happen, and they are the easiest thing in the file to get wrong without noticing.
enum StoreMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[StoreV1.self, StoreV2.self]
}
static var stages: [MigrationStage] {
[v1ToV2]
}
static let v1ToV2 = MigrationStage.custom(
fromVersion: StoreV1.self,
toVersion: StoreV2.self,
willMigrate: { context in
// Collapse duplicate tags before the unique constraint lands.
try context.save()
},
didMigrate: { context in
// Backfill relationships for rows that had no tag at all.
try context.save()
}
)
}
Then point a harness at a copy, never at the original fixture:
func rehearsalContainer(at url: URL) throws -> ModelContainer {
let configuration = ModelConfiguration(url: url)
return try ModelContainer(
for: Schema(versionedSchema: StoreV2.self),
migrationPlan: StoreMigrationPlan.self,
configurations: configuration
)
}
Run it twice. The second open should be a no-op — if it re-runs the stage, your version identifier is lying to you, and so is your release note.
Step 4: Time it, and find the rollback boundary
Wrap the container creation in a clock and log the duration alongside store size and row count. If a 90 MB store takes four seconds, you have found a launch-time regression before your users did, and you can move the migration behind a progress screen instead of a splash screen.
The harder question is where the one-way door closes. Once a v2 binary writes a v2 row, a downgrade will not open that store. So the rollback plan is not a rollback — it is a forward fix. Rehearse that reality: kill the process mid-migration, relaunch, and confirm the app recovers instead of crashing into a half-migrated file. Keep one pristine snapshot untouched for every run, and treat any store a rehearsal has opened as contaminated.
Step 5: Relationships are where the bodies are buried
Adding a @Attribute(.unique) to a field with duplicate values will fail on real data and pass on synthetic data. Making a previously optional property required will fail for every row that was nil. Deleting a parent without a cascade rule leaves children pointing at nothing.
All three are cheap to catch in the harness and expensive to catch in the App Store reviews. Load every model type after migration, count the rows, and assert that each relationship resolves. A loop over try context.fetch(FetchDescriptor<Note>()) that touches note.tags will surface an orphan in seconds.
The pre-flight checklist
- Snapshot the store trio from a real build, including the WAL.
- Keep one small fixture and one heavy fixture.
- Run the migration on copies only; never re-use a migrated file.
- Time container creation at both sizes and log it with the release.
- Re-open after migration and confirm the stage does not run twice.
- Kill mid-migration, relaunch, and verify recovery.
- Fetch and count every model, then walk every relationship.
- Confirm the downgrade story out loud, because it is a forward fix.
None of this takes a sprint. It takes an afternoon, a folder of store files, and the willingness to treat a schema change like what it is: a deployment to data you do not control, shipped to people who will absolutely notice when it goes sideways.