diff --git a/server/migrations/20250918-add-tenant-id-to-drone-detections.js b/server/migrations/20250918-add-tenant-id-to-drone-detections.js new file mode 100644 index 0000000..5e80650 --- /dev/null +++ b/server/migrations/20250918-add-tenant-id-to-drone-detections.js @@ -0,0 +1,91 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // Add tenant_id column to drone_detections table + try { + await queryInterface.addColumn('drone_detections', 'tenant_id', { + type: Sequelize.UUID, + allowNull: true, + references: { + model: 'tenants', + key: 'id' + }, + comment: 'Tenant ID for multi-tenant isolation' + }); + + console.log('✅ Added tenant_id column to drone_detections table'); + } catch (error) { + if (error.original && error.original.code === '42701') { + // Column already exists + console.log('ℹ️ tenant_id column already exists in drone_detections table'); + } else { + throw error; + } + } + + // Add index for better query performance + try { + await queryInterface.addIndex('drone_detections', ['tenant_id'], { + name: 'idx_drone_detections_tenant_id' + }); + console.log('✅ Added index on tenant_id column'); + } catch (error) { + if (error.original && error.original.code === '42P07') { + // Index already exists + console.log('ℹ️ Index on tenant_id already exists'); + } else { + throw error; + } + } + + // Add foreign key constraint + try { + await queryInterface.addConstraint('drone_detections', { + fields: ['tenant_id'], + type: 'foreign key', + name: 'fk_drone_detections_tenant_id', + references: { + table: 'tenants', + field: 'id' + }, + onDelete: 'SET NULL', + onUpdate: 'CASCADE' + }); + console.log('✅ Added foreign key constraint for tenant_id'); + } catch (error) { + if (error.original && error.original.code === '42710') { + // Constraint already exists + console.log('ℹ️ Foreign key constraint already exists'); + } else { + throw error; + } + } + }, + + async down(queryInterface, Sequelize) { + // Remove foreign key constraint + try { + await queryInterface.removeConstraint('drone_detections', 'fk_drone_detections_tenant_id'); + console.log('✅ Removed foreign key constraint for tenant_id'); + } catch (error) { + console.log('ℹ️ Foreign key constraint already removed or does not exist'); + } + + // Remove index + try { + await queryInterface.removeIndex('drone_detections', 'idx_drone_detections_tenant_id'); + console.log('✅ Removed index on tenant_id column'); + } catch (error) { + console.log('ℹ️ Index already removed or does not exist'); + } + + // Remove tenant_id column + try { + await queryInterface.removeColumn('drone_detections', 'tenant_id'); + console.log('✅ Removed tenant_id column from drone_detections table'); + } catch (error) { + console.log('ℹ️ tenant_id column already removed or does not exist'); + } + } +}; \ No newline at end of file