/** * Migration: Link Device to InventoryDevice * * Fixes: InventoryDevice and Device have no explicit relationship * Changes: * - Add inventory_device_id FK to devices table * - Migrate existing data by matching hardware_id * * @type {import('node-pg-migrate').ColumnDefinitions | undefined} */ export const shorthands = undefined; /** * @param pgm {import('node-pg-migrate').MigrationBuilder} * @param run {() => void | undefined} * @returns {Promise | void} */ export const up = (pgm) => { console.log('Linking Device to InventoryDevice...'); // Add inventory_device_id column pgm.addColumn('devices', { inventory_device_id: { type: 'uuid', notNull: false, comment: 'FK to inventory_devices - the inventory record for this device', }, }); // Migrate data by matching hardware_id pgm.sql(` UPDATE devices d SET inventory_device_id = inv.id FROM inventory_devices inv WHERE d.hardware_id = inv.hardware_id; `); // Add FK constraint pgm.addConstraint('devices', 'devices_inventory_device_id_fkey', { foreignKeys: { columns: 'inventory_device_id', references: 'inventory_devices(id)', onDelete: 'SET NULL', }, }); // Add unique constraint - one device per inventory record pgm.createIndex('devices', 'inventory_device_id', { name: 'idx_devices_inventory_device_id_unique', unique: true, where: 'inventory_device_id IS NOT NULL', }); // Update inventory_devices.is_claimed based on linked devices pgm.sql(` UPDATE inventory_devices inv SET is_claimed = true WHERE EXISTS ( SELECT 1 FROM devices d WHERE d.inventory_device_id = inv.id ); `); console.log('Device to InventoryDevice link added.'); }; /** * @param pgm {import('node-pg-migrate').MigrationBuilder} * @param run {() => void | undefined} * @returns {Promise | void} */ export const down = (pgm) => { console.log('Rolling back Device to InventoryDevice link...'); // Drop unique index pgm.dropIndex('devices', 'inventory_device_id', { name: 'idx_devices_inventory_device_id_unique', ifExists: true, }); // Drop FK constraint pgm.dropConstraint('devices', 'devices_inventory_device_id_fkey', { ifExists: true, }); // Drop column pgm.dropColumn('devices', 'inventory_device_id', { ifExists: true }); console.log('Device to InventoryDevice link rollback complete.'); };