diff --git a/packages/db/migrations/20260329_020000_fix_household_item_classification_upsert.sql b/packages/db/migrations/20260329_020000_fix_household_item_classification_upsert.sql new file mode 100644 index 0000000..29e0133 --- /dev/null +++ b/packages/db/migrations/20260329_020000_fix_household_item_classification_upsert.sql @@ -0,0 +1,23 @@ +BEGIN; + +WITH ranked_classifications AS ( + SELECT + id, + ROW_NUMBER() OVER ( + PARTITION BY household_id, store_id, household_store_item_id + ORDER BY updated_at DESC NULLS LAST, id DESC + ) AS row_rank + FROM household_item_classifications + WHERE household_store_item_id IS NOT NULL +) +DELETE FROM household_item_classifications hic +USING ranked_classifications ranked +WHERE hic.id = ranked.id + AND ranked.row_rank > 1; + +DROP INDEX IF EXISTS idx_household_item_classifications_household_store_item; + +CREATE UNIQUE INDEX idx_household_item_classifications_household_store_item + ON household_item_classifications(household_id, store_id, household_store_item_id); + +COMMIT;