'use strict'; const TABLE = 'wms_permission'; const COLUMN = 'parent_id'; const FK_NAME = 'fk_wms_permission_parent'; async function hasConstraint(queryInterface, tableName, constraintName) { const [ rows ] = await queryInterface.sequelize.query( ` SELECT 1 FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND TABLE_NAME = :tableName AND CONSTRAINT_NAME = :constraintName LIMIT 1 `, { replacements: { tableName, constraintName, }, } ); return rows.length > 0; } async function getOrphanCount(queryInterface) { const [ rows ] = await queryInterface.sequelize.query( ` SELECT COUNT(*) AS cnt FROM wms_permission p LEFT JOIN wms_permission pp ON pp.id = p.parent_id WHERE p.parent_id IS NOT NULL AND p.parent_id <> 0 AND pp.id IS NULL ` ); return Number(rows[0]?.cnt || 0); } async function getSelfLoopCount(queryInterface) { const [ rows ] = await queryInterface.sequelize.query( ` SELECT COUNT(*) AS cnt FROM wms_permission WHERE parent_id = id ` ); return Number(rows[0]?.cnt || 0); } module.exports = { async up(queryInterface) { const orphanCount = await getOrphanCount(queryInterface); if (orphanCount > 0) { throw new Error( `Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_permission.parent_id.` ); } const selfLoopCount = await getSelfLoopCount(queryInterface); if (selfLoopCount > 0) { throw new Error( `Cannot add ${FK_NAME}: found ${selfLoopCount} self-loop rows (id = parent_id) in wms_permission.` ); } // Normalize root sentinel to NULL before adding FK. await queryInterface.sequelize.query( 'UPDATE `wms_permission` SET `parent_id` = NULL WHERE `parent_id` = 0' ); await queryInterface.sequelize.query( "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)'" ); const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); if (!fkExists) { await queryInterface.sequelize.query( 'ALTER TABLE `wms_permission` ' + 'ADD CONSTRAINT `fk_wms_permission_parent` ' + 'FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ' + 'ON UPDATE RESTRICT ON DELETE SET NULL' ); } // Root node normalization from 0->NULL is handled in application model setters. }, async down(queryInterface) { const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME); if (fkExists) { await queryInterface.sequelize.query( 'ALTER TABLE `wms_permission` DROP FOREIGN KEY `fk_wms_permission_parent`' ); } await queryInterface.sequelize.query( 'UPDATE `wms_permission` SET `parent_id` = 0 WHERE `parent_id` IS NULL' ); await queryInterface.sequelize.query( "ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT 0 COMMENT '父级ID'" ); }, };