/** * Migration: Add alert_event_id to alert_logs table * This migration adds alert_event_id field to group related alerts (SMS, email, webhook) * that are part of the same detection event */ 'use strict'; module.exports = { async up(queryInterface, Sequelize) { try { // Check if alert_logs table exists first const tables = await queryInterface.showAllTables(); if (!tables.includes('alert_logs')) { console.log('⚠️ Alert_logs table does not exist yet, skipping alert event ID migration...'); return; } // Check if alert_event_id column already exists const tableDescription = await queryInterface.describeTable('alert_logs'); if (!tableDescription.alert_event_id) { // Add alert_event_id column await queryInterface.addColumn('alert_logs', 'alert_event_id', { type: Sequelize.UUID, allowNull: true, comment: 'Groups related alerts (SMS, email, webhook) that are part of the same detection event' }); console.log('✅ Added alert_event_id column to alert_logs table'); // Add index for alert_event_id for better query performance try { await queryInterface.addIndex('alert_logs', ['alert_event_id'], { name: 'alert_logs_alert_event_id_idx' }); console.log('✅ Added index on alert_logs.alert_event_id'); } catch (error) { if (error.parent?.code === '42P07') { // Index already exists console.log('⚠️ Index alert_logs_alert_event_id already exists, skipping...'); } else { throw error; } } } else { console.log('⚠️ Column alert_event_id already exists in alert_logs table, skipping...'); } } catch (error) { console.error('❌ Error in migration 20250922000002-add-alert-event-id:', error); throw error; } }, async down(queryInterface, Sequelize) { try { // Check if alert_logs table exists const tables = await queryInterface.showAllTables(); if (!tables.includes('alert_logs')) { console.log('⚠️ Alert_logs table does not exist, skipping migration rollback...'); return; } // Check if alert_event_id column exists const tableDescription = await queryInterface.describeTable('alert_logs'); if (tableDescription.alert_event_id) { // Remove index first try { await queryInterface.removeIndex('alert_logs', 'alert_logs_alert_event_id_idx'); console.log('✅ Removed index alert_logs_alert_event_id_idx'); } catch (error) { console.log('⚠️ Index alert_logs_alert_event_id_idx might not exist, continuing...'); } // Remove column await queryInterface.removeColumn('alert_logs', 'alert_event_id'); console.log('✅ Removed alert_event_id column from alert_logs table'); } else { console.log('⚠️ Column alert_event_id does not exist in alert_logs table, skipping...'); } } catch (error) { console.error('❌ Error in migration rollback 20250922000002-add-alert-event-id:', error); throw error; } } };