'use strict'; const TABLE_NAME = 'wms_workbench'; async function indexExists(queryInterface, tableName, indexName) { const indexes = await queryInterface.showIndex(tableName); return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); } async function dropIndexIfExists(queryInterface, tableName, indexName) { if (await indexExists(queryInterface, tableName, indexName)) { await queryInterface.removeIndex(tableName, indexName); console.log(`[idx] ${tableName}.${indexName} 已删除`); } } async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { if (await indexExists(queryInterface, tableName, indexName)) { console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); return; } await queryInterface.addIndex(tableName, options.fields, { name: indexName, unique: !!options.unique, }); console.log(`[idx] ${tableName}.${indexName} 已创建`); } /** * Migration: remove barcode from wms_workbench(工作台条码字段未使用,下线) * - 删除列 barcode VARCHAR(100) * - 删除索引 idx_barcode、uk_warehouse_barcode(仓库级唯一条码索引) * * Idempotent: 通过 describeTable / showIndex 判断后仅删除存在部分。 */ module.exports = { /** * 执行正向迁移:先删索引,再删 barcode 列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ up: async queryInterface => { await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode'); await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_barcode'); const columns = await queryInterface.describeTable(TABLE_NAME); if (columns.barcode) { await queryInterface.removeColumn(TABLE_NAME, 'barcode'); } }, /** * 执行回滚迁移:恢复 barcode 列与索引。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ down: async (queryInterface, Sequelize) => { const columns = await queryInterface.describeTable(TABLE_NAME); if (!columns.barcode) { await queryInterface.addColumn(TABLE_NAME, 'barcode', { type: Sequelize.STRING(100), allowNull: true, comment: '工作台条码(用户自定义,仓库内唯一)', }); } await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_barcode', { fields: [ 'barcode' ], }); await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode', { fields: [ 'warehouse_id', 'barcode', 'deleted_at' ], unique: true, }); }, };