Files

31 lines
832 B
SQL
Raw Permalink Normal View History

-- Deduplicate reports before adding the unique constraint:
-- keep the earliest report per (userId, date), move tasks from the
-- duplicates onto it, then delete the duplicates.
UPDATE "Task"
SET "reportId" = (
SELECT keep."id"
FROM "Report" keep
JOIN "Report" cur ON cur."id" = "Task"."reportId"
WHERE keep."userId" = cur."userId"
AND keep."date" = cur."date"
ORDER BY keep."createdAt" ASC, keep."id" ASC
LIMIT 1
);
DELETE FROM "Report"
WHERE "id" IN (
SELECT "id" FROM (
SELECT "id",
ROW_NUMBER() OVER (
PARTITION BY "userId", "date"
ORDER BY "createdAt" ASC, "id" ASC
) AS rn
FROM "Report"
)
WHERE rn > 1
);
-- CreateIndex
CREATE UNIQUE INDEX "Report_userId_date_key" ON "Report"("userId", "date");