92 lines
3.0 KiB
JavaScript
92 lines
3.0 KiB
JavaScript
/**
|
|
* Migration: Add tenant support to devices table
|
|
* This migration adds tenant_id field to devices for multi-tenant isolation
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
module.exports = {
|
|
async up(queryInterface, Sequelize) {
|
|
try {
|
|
// Check if devices table exists first
|
|
const tables = await queryInterface.showAllTables();
|
|
if (!tables.includes('devices')) {
|
|
console.log('⚠️ Devices table does not exist yet, skipping device tenant support migration...');
|
|
return;
|
|
}
|
|
|
|
// Check if tenant_id column already exists
|
|
const tableDescription = await queryInterface.describeTable('devices');
|
|
|
|
if (!tableDescription.tenant_id) {
|
|
// Add tenant_id column to devices table
|
|
await queryInterface.addColumn('devices', 'tenant_id', {
|
|
type: Sequelize.INTEGER,
|
|
allowNull: true, // Nullable for backward compatibility
|
|
references: {
|
|
model: 'tenants',
|
|
key: 'id'
|
|
},
|
|
onUpdate: 'CASCADE',
|
|
onDelete: 'SET NULL',
|
|
comment: 'Foreign key to tenants table for multi-tenant isolation'
|
|
});
|
|
|
|
// Add index for tenant_id for better query performance
|
|
try {
|
|
await queryInterface.addIndex('devices', ['tenant_id'], {
|
|
name: 'devices_tenant_id_idx'
|
|
});
|
|
console.log('✅ Added index on devices.tenant_id');
|
|
} catch (error) {
|
|
if (error.parent?.code === '42P07') { // Index already exists
|
|
console.log('⚠️ Index devices_tenant_id already exists, skipping...');
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Associate existing devices with default tenant (backward compatibility)
|
|
const defaultTenant = await queryInterface.sequelize.query(
|
|
'SELECT id FROM tenants WHERE slug = :slug',
|
|
{
|
|
replacements: { slug: 'default' },
|
|
type: Sequelize.QueryTypes.SELECT
|
|
}
|
|
);
|
|
|
|
if (defaultTenant.length > 0) {
|
|
await queryInterface.sequelize.query(
|
|
'UPDATE devices SET tenant_id = :tenantId WHERE tenant_id IS NULL',
|
|
{
|
|
replacements: { tenantId: defaultTenant[0].id },
|
|
type: Sequelize.QueryTypes.UPDATE
|
|
}
|
|
);
|
|
console.log('✅ Associated existing devices with default tenant');
|
|
}
|
|
|
|
console.log('✅ Added tenant_id field to devices table');
|
|
} else {
|
|
console.log('⚠️ Column tenant_id already exists in devices table, skipping...');
|
|
}
|
|
} catch (error) {
|
|
console.log('⚠️ Migration skipped - tables may not exist yet:', error.message);
|
|
// Don't throw error, just skip this migration if tables don't exist
|
|
}
|
|
},
|
|
|
|
async down(queryInterface, Sequelize) {
|
|
// Remove index
|
|
try {
|
|
await queryInterface.removeIndex('devices', 'devices_tenant_id_idx');
|
|
} catch (error) {
|
|
console.log('⚠️ Index devices_tenant_id_idx does not exist, skipping...');
|
|
}
|
|
|
|
// Remove column
|
|
await queryInterface.removeColumn('devices', 'tenant_id');
|
|
console.log('✅ Removed tenant_id field from devices table');
|
|
}
|
|
};
|