skip to content

In SwiftData, a release adds @Attribute(.unique) to Trip.bookingReference, but shipped stores hold duplicates; why does the store fail to open, and how does a custom stage fix it?

level: seniorimportance: should knowfreq 25%

answer

  1. the rule meets existing rows
  2. inference cannot pick a winner
  3. fix data in the old shape
  4. willMigrate, then save

basics

~20 s

A lightweight stage applies the new unique constraint to rows that already collide, so the migration fails and ModelContainer's initializer throws. A custom stage's willMigrate fetches the old Trip type, keeps one trip per reference, removes or merges the rest and saves.

solid answer

~40 s

SwiftData cannot decide which of two trips with the same `bookingReference` is real, so a `.lightweight` stage tries to apply the constraint as is, hits the duplicates and fails; the initializer throws `SwiftDataError.loadIssueModelContainer`, wrapping a constraint-violation error from the Core Data store underneath. The fix is `.custom(fromVersion:toVersion:willMigrate:didMigrate:)` with the work in `willMigrate`, which runs while the store still has the old shape: fetch `TripSchemaV2.Trip`, group by reference, keep the survivor you chose (the oldest, or the most complete after merging), delete the others and call `try context.save()`. Without that save the deletes are not kept and the migration fails just the same. `didMigrate` can be `nil`. The same applies to a compound `#Unique` rule, available from iOS 18.

code

swift · 37 lines
swift
import Foundation
import SwiftData

enum TripSchemaV2: VersionedSchema {
    static let versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip {
        var bookingReference = ""
        var createdAt = Date.now
        init() {}
    }
}

enum TripSchemaV3: VersionedSchema {
    static let versionIdentifier = Schema.Version(3, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip {
        @Attribute(.unique) var bookingReference = ""
        var createdAt = Date.now
        init() {}
    }
}

let dedupeBookings = MigrationStage.custom(
    fromVersion: TripSchemaV2.self,
    toVersion: TripSchemaV3.self,
    willMigrate: { context in
        // Still the V2 shape: duplicates are allowed here, so remove them now.
        let byOldest = FetchDescriptor<TripSchemaV2.Trip>(sortBy: [SortDescriptor(\.createdAt)])
        var seen = Set<String>()
        for trip in try context.fetch(byOldest) {
            if !seen.insert(trip.bookingReference).inserted { context.delete(trip) }
        }
        try context.save()
    },
    didMigrate: nil
)

go deeper

for a junior

Recall that adding @Attribute(.unique) to data that already has duplicates makes the migration fail rather than cleaning the data for you.

for a middle

Explain why the clean-up belongs in a custom stage's willMigrate, which sees the old shape, and why the context must be saved there.

for a senior

Show that you choose the surviving row on purpose, merge what users typed, handle related models, and test the stage on a store copied from a shipped build.

for a principal

Discuss whether a uniqueness rule is worth a data-changing migration at all, and who signs off on which user records are merged or removed.

## Why the lightweight stage fails Adding `@Attribute(.unique)` to `bookingReference` changes the schema in a way SwiftData can apply mechanically **only if the data already obeys it**. A lightweight stage moves the existing rows into the new shape and enforces the constraint as it goes. When two shipped trips share a reference, there is no rule in the schema for which one wins, so: - the migration stops with a constraint violation reported by the Core Data store underneath SwiftData; - `ModelContainer`'s initializer throws `SwiftDataError.loadIssueModelContainer`, carrying that error; - the app has no container, so nothing that needs the store can run until the code changes. On a developer's clean simulator the same migration usually succeeds, because test data has no duplicates. The failure shows only on devices whose stored data already holds duplicates, which is why it tends to surface after release. ## The custom stage, step by step `MigrationStage.custom(fromVersion:toVersion:willMigrate:didMigrate:)` gives you a `ModelContext` before and after the schema change. De-duplication has to happen **before**, while duplicates are still allowed: 1. Declare the version that adds the rule, `TripSchemaV3`, with `@Attribute(.unique) var bookingReference`. 2. In `willMigrate`, fetch the **frozen old type**, `TripSchemaV2.Trip`, because the store still has the V2 shape. 3. Walk the trips in a deliberate order (here, oldest first by `createdAt`) and keep the first trip for each reference. 4. Delete the rest, or merge their data into the survivor first. 5. Call `try context.save()`. The stage does not save for you: without it, the deletes are thrown away and the constraint fails exactly as before. 6. Pass `nil` for `didMigrate` unless something must also be filled in after the rule is in place. In the plan, this stage replaces the lightweight one between V2 and V3; the code example shows it. ## Choosing the survivor Which row to keep is a product decision written as code, so make it on purpose: - **Oldest wins** keeps the first booking the user made, and is easy to explain. - **Most complete wins** keeps the row with notes, dates and attachments filled in. - **Merge** copies fields the survivor lacks from each duplicate before deleting it, so nothing the user typed is lost. - **Related models** need the same thought: a delete in `willMigrate` is an ordinary `ModelContext` delete, so move children to the survivor before deleting a duplicate if they must stay (relationship delete rules are covered with SwiftData relationships). | Approach | User data lost | Code to write | |---|---|---| | Lightweight stage only | Store does not open | None, and it fails | | Custom, delete duplicates | Fields only the duplicates held | A short loop and a save | | Custom, merge then delete | None, if the merge is complete | Field-by-field merge rules | ## Checking the stage before release The failure only appears with real duplicates, so prove the stage against them rather than against a fresh simulator: - Create a store at the old version with `ModelContainer(for: Schema(versionedSchema: TripSchemaV2.self), configurations: [ModelConfiguration(url: storeURL)])`, insert trips that share a reference, and save. - Open the same URL with the V3 models and the plan, then fetch and check that one trip per reference remains, and the one you meant to keep. - Run it once with the lightweight stage too, and watch the initializer throw. Seeing the failure confirms the test really exercises the duplicates. How many shipped versions to keep fixtures for is a wider strategy question; this check is about one stage doing what its code claims. ## Pitfalls - **De-duplicating in `didMigrate`.** It runs after the store reaches the new shape, and that shape cannot exist while duplicates do. - **Fetching through the app's typealias.** In `willMigrate` the store has the old attributes; the frozen V2 type describes them, and stays correct after the next release changes the current model. - **Forgetting the save.** A frequent reason a correct-looking stage still fails. - **Compound rules.** `#Unique<Trip>([\.bookingReference, \.startDate])`, available from iOS 18, fails the same way when rows collide on that combination; de-duplicate on the same key combination. - **Large stores.** The stage runs while the container opens the store, so a slow loop delays everything waiting for the container; fetch only what the check needs. The point an interviewer listens for: a unique rule is a statement about data users already have, and only a custom stage can make that data true before the rule arrives.

  • Why does the SwiftData willMigrate closure fetch TripSchemaV2.Trip rather than the app's current Trip?
    `willMigrate` runs before the store moves to the destination version, so the rows still have the V2 shape and the V2 type describes them. The app's typealias points at the newest version, which describes attributes the store does not have yet and will change again next release. Pinning migration code to the frozen types keeps it correct forever.
  • What if two duplicate trips each hold data the user cares about?
    Merge before deleting: choose the survivor, copy over the fields it lacks, such as notes or a later return date, move any related models it should own, then delete the duplicate and save. A blind delete is a product decision hidden in a migration, so agree the rule with whoever owns the feature.
  • Does the same failure happen with SwiftData's #Unique macro?
    Yes. `#Unique`, available from iOS 18, declares a uniqueness constraint over one or more properties. Adding it to a store whose rows collide on that combination fails the migration the same way, so de-duplicate on the same key combination in `willMigrate` before the version that introduces it.

  • SwiftData silently drops duplicate rows when a unique attribute is added.
  • Duplicates should be removed in didMigrate, once the constraint is in place.
  • Changes made in willMigrate are saved automatically when the closure returns.
  • If the migration works on the simulator, shipped stores will migrate too.