-- 保留全部历史记录，只对同用户重复键追加记录 ID，避免迁移删除或丢失数据。
UPDATE inspection_records AS r
SET idempotency_key = r.idempotency_key || '#' || r.id
WHERE r.idempotency_key IS NOT NULL
  AND EXISTS (
      SELECT 1
      FROM inspection_records AS x
      WHERE x.user_id IS NOT DISTINCT FROM r.user_id
        AND x.idempotency_key = r.idempotency_key
        AND x.id <> r.id
  );

DROP INDEX IF EXISTS idx_inspection_records_idempotency_key;

CREATE UNIQUE INDEX IF NOT EXISTS idx_inspection_records_user_idempotency
    ON inspection_records (user_id, idempotency_key)
    WHERE idempotency_key IS NOT NULL;
