Skip to content

Commit 9f08cf2

Browse files
Jing-yilinclaude
andcommitted
fix: move snapshot deduplication outside IF block to handle existing duplicates
The deduplication logic was inside IF NOT EXISTS (snapshot_date), so it only ran on fresh databases. Existing databases with duplicate data would fail to create the unique index during AutoMigrate. Move the DELETE statement outside the IF block so it runs on EVERY deployment, ensuring duplicate data is cleaned up before AutoMigrate attempts to create the unique index idx_campaign_snapshot_date. Fixes deployment failure: ERROR: could not create unique index "idx_campaign_snapshot_date" (SQLSTATE 23505) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
1 parent 71dd293 commit 9f08cf2

1 file changed

Lines changed: 7 additions & 6 deletions

File tree

backend/internal/db/db.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -170,15 +170,16 @@ func Init(cfg *config.Config) error {
170170
ALTER TABLE campaign_snapshots ADD COLUMN backers_count int DEFAULT 0;
171171
END IF;
172172
173-
-- Deduplicate: keep only the latest snapshot per (campaign_pid, snapshot_date).
174-
DELETE FROM campaign_snapshots a USING campaign_snapshots b
175-
WHERE a.campaign_pid = b.campaign_pid
176-
AND a.snapshot_date = b.snapshot_date
177-
AND a.snapshot_at < b.snapshot_at;
178-
179173
-- Set NOT NULL now that all rows have a value.
180174
ALTER TABLE campaign_snapshots ALTER COLUMN snapshot_date SET NOT NULL;
181175
END IF;
176+
177+
-- Deduplicate: keep only the latest snapshot per (campaign_pid, snapshot_date).
178+
-- Run this EVERY time (not just when column is missing) to handle legacy duplicate data.
179+
DELETE FROM campaign_snapshots a USING campaign_snapshots b
180+
WHERE a.campaign_pid = b.campaign_pid
181+
AND a.snapshot_date = b.snapshot_date
182+
AND a.snapshot_at < b.snapshot_at;
182183
END
183184
$$;
184185
`).Error; err != nil {

0 commit comments

Comments
 (0)