'use strict'; const TABLE_NAME = 'wms_order_express'; const MATERIAL_ID_COLUMN = 'package_material_id'; const MATERIAL_NAME_SNAPSHOT_COLUMN = 'package_material_name_snapshot'; const MATERIAL_ID_INDEX = 'idx_wms_order_express_package_material_id'; /** * 获取指定表的索引名集合。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @return {Promise>} 索引名集合。 */ const getIndexNameSet = async (queryInterface, tableName) => { const indexes = await queryInterface.showIndex(tableName); return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean)); }; module.exports = { /** * 执行迁移:为订单快递表新增包材字段并补齐索引(幂等)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ async up(queryInterface, Sequelize) { const columns = await queryInterface.describeTable(TABLE_NAME); if (!columns[MATERIAL_ID_COLUMN]) { await queryInterface.addColumn(TABLE_NAME, MATERIAL_ID_COLUMN, { type: Sequelize.BIGINT(20).UNSIGNED, allowNull: true, comment: '包材ID', }); } if (!columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { await queryInterface.addColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN, { type: Sequelize.STRING(128), allowNull: true, comment: '包材名称快照', }); } const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); if (!indexNameSet.has(MATERIAL_ID_INDEX)) { await queryInterface.addIndex(TABLE_NAME, [ MATERIAL_ID_COLUMN ], { name: MATERIAL_ID_INDEX, }); } }, /** * 回滚迁移:删除订单快递表包材字段及索引(幂等)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { const columns = await queryInterface.describeTable(TABLE_NAME); const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME); if (indexNameSet.has(MATERIAL_ID_INDEX)) { await queryInterface.removeIndex(TABLE_NAME, MATERIAL_ID_INDEX); } if (columns[MATERIAL_NAME_SNAPSHOT_COLUMN]) { await queryInterface.removeColumn(TABLE_NAME, MATERIAL_NAME_SNAPSHOT_COLUMN); } if (columns[MATERIAL_ID_COLUMN]) { await queryInterface.removeColumn(TABLE_NAME, MATERIAL_ID_COLUMN); } }, };