Files
Ludv1gL de4516d0d3 feat: Allow adding unique constraints to existing tables (#4465)
## Summary

Adding `#[unique]` or `#[primary_key]` to an existing column currently
triggers `AutoMigrateError::AddUniqueConstraint`, forcing a full
database clear to apply the schema change. This PR makes it a
non-breaking migration by validating existing data first:

- **If all values are unique**: constraint is added seamlessly
(non-breaking migration)
- **If duplicates exist**: migration fails with a detailed error listing
up to 10 duplicate groups

## Changes

- `auto_migrate.rs`: Replace hard `AddUniqueConstraint` error with
`CheckAddUniqueConstraintValid` precheck + `AddConstraint` migration
step
- `update.rs`: Implement precheck (full table scan, project constrained
columns, count duplicates) and `AddConstraint` step execution
- `relational_db.rs`: Expose `create_constraint()` (counterpart to
existing `drop_constraint()`)
- `traits.rs` / `datastore.rs`: Add `create_constraint_mut_tx` to
`MutTxDatastore` trait
- `mut_tx.rs`: Make `create_constraint` public
- `formatter.rs`: Format the new `AddConstraint` step

## Safety

- **Transaction safety**: Precheck and constraint creation run in the
same `MutTx` — no window for concurrent duplicate inserts
- **Index creation**: `auto_migrate_indexes()` already handles adding
the backing btree index (with `is_unique=true` from the new schema). The
constraint step only adds metadata.
- **Rollback**: If the precheck finds duplicates, the entire migration
aborts before any changes are applied
- **Error quality**: Duplicate error shows table name, column names, and
up to 10 example duplicate values with counts

## Example error output

```
Precheck failed: cannot add unique constraint 'Users_email_key' on table 'Users' column(s) [email]:
3 duplicate group(s) found.
  - String("alice@example.com") appears 2 times
  - String("bob@example.com") appears 3 times
  - String("charlie@example.com") appears 2 times
```

## Test plan

- [x] All 12 `auto_migrate` tests pass
- [x] `cargo check` passes for `spacetimedb-schema` and
`spacetimedb-core`
- [x] Verified the previously-expected `AddUniqueConstraint` error test
is updated
- [x] Manual test: add `#[unique]` to existing column with clean data →
succeeds
- [x] Manual test: add `#[unique]` to existing column with duplicates →
fails with detailed error

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Mazdak Farrokhzad <twingoow@gmail.com>
Co-authored-by: Zeke Foppa <196249+bfops@users.noreply.github.com>
Co-authored-by: clockwork-labs-bot <clockwork-labs-bot@users.noreply.github.com>
2026-06-23 09:17:46 -07:00
..
2026-01-14 09:44:20 +00:00
2025-08-12 18:20:58 +00:00

⚠️ Internal Crate ⚠️

This crate is intended for internal use only. It is not stable and may change without notice.