WMS_MAIN/database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js

76 lines
2.8 KiB
JavaScript

'use strict';
/**
* 打印迁移阶段对应的数据库连接上下文信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {'up'|'down'} phase 迁移阶段。
* @param {string} table 迁移目标表名。
* @return {Promise<void>} 无返回值。
*/
const logMigrationDbContext = async (queryInterface, phase, table) => {
try {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user'
);
const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {};
console.log(
`[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}`
);
} catch (error) {
console.warn(
`[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}`
);
}
};
/**
* Migration: add intercept_locked_quantity to wms_storage
* - intercept_locked_quantity: INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量'
*
* Idempotent: uses queryInterface.describeTable to only add if missing.
*
* Raw SQL (MySQL 8+ supports IF NOT EXISTS):
* ALTER TABLE `wms_storage`
* ADD COLUMN IF NOT EXISTS `intercept_locked_quantity` INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量';
*
* If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER.
*/
module.exports = {
/**
* 执行正向迁移,按需新增库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.intercept_locked_quantity) {
await queryInterface.addColumn(table, 'intercept_locked_quantity', {
type: Sequelize.INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '拦截锁定数量',
});
}
},
/**
* 执行回滚迁移,按需删除库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'intercept_locked_quantity');
}
},
};