From ed4fce49a4be7b5e46da93bcadf9316d2d7fd396 Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Thu, 5 Mar 2026 12:41:56 -0600 Subject: [PATCH] fix: ensure alerts table columns exist - Add idempotent migration to ensure severity, notification_sent, etc. columns exist - Fixes production issue where migration was marked as run but columns weren't created - Uses IF NOT EXISTS to safely add missing columns without errors - Includes all columns and indexes from ExtendAlertsForChecks migration --- ...0305184122_ensure_alerts_columns_exist.exs | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 priv/repo/migrations/20260305184122_ensure_alerts_columns_exist.exs diff --git a/priv/repo/migrations/20260305184122_ensure_alerts_columns_exist.exs b/priv/repo/migrations/20260305184122_ensure_alerts_columns_exist.exs new file mode 100644 index 00000000..342b4ed9 --- /dev/null +++ b/priv/repo/migrations/20260305184122_ensure_alerts_columns_exist.exs @@ -0,0 +1,70 @@ +defmodule Towerops.Repo.Migrations.EnsureAlertsColumnsExist do + use Ecto.Migration + + def up do + # Ensure columns from ExtendAlertsForChecks migration exist + # This fixes cases where the migration was marked as run but columns weren't created + execute """ + ALTER TABLE alerts + ADD COLUMN IF NOT EXISTS severity INTEGER DEFAULT 2 + """ + + execute """ + ALTER TABLE alerts + ADD COLUMN IF NOT EXISTS notification_sent BOOLEAN DEFAULT false + """ + + execute """ + ALTER TABLE alerts + ADD COLUMN IF NOT EXISTS notification_sent_at TIMESTAMP + """ + + execute """ + ALTER TABLE alerts + ADD COLUMN IF NOT EXISTS output TEXT + """ + + execute """ + ALTER TABLE alerts + ADD COLUMN IF NOT EXISTS check_id UUID + """ + + # Create indexes if they don't exist + execute """ + CREATE INDEX IF NOT EXISTS alerts_check_id_index ON alerts (check_id) + """ + + execute """ + CREATE INDEX IF NOT EXISTS alerts_severity_index ON alerts (severity) + """ + + execute """ + CREATE INDEX IF NOT EXISTS alerts_notification_sent_index ON alerts (notification_sent) + """ + + # Add foreign key constraint if it doesn't exist + execute """ + DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint WHERE conname = 'alerts_check_id_fkey' + ) THEN + ALTER TABLE alerts + ADD CONSTRAINT alerts_check_id_fkey + FOREIGN KEY (check_id) REFERENCES checks(id) ON DELETE CASCADE; + END IF; + END $$; + """ + + # Make device_id nullable if it isn't already + execute """ + ALTER TABLE alerts + ALTER COLUMN device_id DROP NOT NULL + """ + end + + def down do + # Don't remove columns on rollback - data safety + :ok + end +end