Enforce unique taggings with a partial index (#202)
What this changes
taggings has no uniqueness constraint, so a tag can be applied twice to one object. Two paths reach that state:
Tag#replace_and_destroy!merges bytaggings.update_all tag_id: replacement.idwith no deduplication. If an object already carries the replacement, it ends up with two taggings for the replacement and appears twice wherever taggings are iterated.- Concurrent check-then-insert against a shared object.
The fix
- Dedupe first — a migration deletes duplicate rows, keeping the earliest id per
(tag_id, taggable_type, taggable_id)where the taggable is set. - Partial unique index —
index_taggings_uniqueon(tag_id, taggable_type, taggable_id)withwhere: taggable_id IS NOT NULL. A plain unique index would look like a constraint but not be one: both taggable columns are nullable, and Postgres treats NULLs as distinct in unique indexes, so duplicate rows with a NULL taggable would pass it silently. Partial form matches the dedupe predicate exactly, the explicit name stays under Postgres's 63-char identifier limit, andnulls_not_distinct: truecloses the NULL-taggable_typehole that plain distinct-key comparison would otherwise admit. Tag#replace_and_destroy!now skips taggings the object already carries for the replacement, so the merge cannot produce a duplicate on a code path that has no reason to fail. The skip subquery also excludes NULLtaggable_ids, becausewhere.not(taggable_id: <subquery>)compiles toNOT IN, and aNULLanywhere in that set would make every rowNULLand silently move no tags at all.
The migration runs transactional by default; a plain CREATE INDEX takes ShareUpdateExclusiveLock, so no concurrent insert can land a duplicate between the DELETE and the index.
Dedupe count (test DB)
0 duplicates in the committed test fixture set. At head b90ea7d, test/fixtures/taggings.yml holds exactly two rows — (tag one, Transaction, transaction one) and (tag two, Transaction, transaction one) — distinct (tag_id, taggable_type, taggable_id) pairs (one tag per row on the same object). So the test DB as seeded has no duplicate taggable group, and the dedupe is a clean no-op against it. This reflects the committed test fixtures only, not a live/production run — I have no reachable Postgres in this environment, so the migration could not be executed against a running DB to enumerate runtime rows. CI's green ci/test_unit did run the migration and the full unit suite on Postgres and passed, which proves the migration is clean and the index refuses a real (non-NULL) duplicate.
Not covered
- Local test suite not run — same constraints (no reachable Postgres, gems not installed,
docker runis blocked). CI is the verification gate for the full suite, per the repo's own development guide. - Existing fixtures (
test/fixtures/taggings.yml) are already de-duplicated and remain valid; the new partial index does not touch rows with a NULLtaggable_id, which the fixtures do not exercise.
Closes #202.