cluster: dedupe rows + enforce unique hostname index

Migration 004 wrapped table creation in IF NOT EXISTS, so deploys with
a pre-existing cluster_nodes table never picked up the inline UNIQUE
constraint and accumulated duplicate hostnames on every container
restart. This migration purges older duplicates and adds the unique
index idempotently so the ON CONFLICT (hostname) upsert finally works.
This commit is contained in:
Zac Gaetano 2026-05-21 00:14:01 -04:00
parent 066b9b17d3
commit a39c9831c5

View file

@ -0,0 +1,20 @@
-- 007 — De-duplicate cluster_nodes by hostname and enforce uniqueness.
--
-- Migration 004 created the table with `CREATE TABLE IF NOT EXISTS` and an
-- inline UNIQUE constraint; on deploys where the table predated 004 the
-- constraint was never applied, which let the same hostname accumulate
-- multiple rows (one per container restart in some setups).
--
-- This migration:
-- 1. Deletes older duplicates keeping only the most-recently-seen row
-- per hostname.
-- 2. Adds a UNIQUE INDEX on (hostname) which is idempotent and satisfies
-- the ON CONFLICT (hostname) upsert in routes/cluster.js.
DELETE FROM cluster_nodes a
USING cluster_nodes b
WHERE a.hostname = b.hostname
AND a.last_seen < b.last_seen;
CREATE UNIQUE INDEX IF NOT EXISTS cluster_nodes_hostname_uniq
ON cluster_nodes (hostname);