'use strict'; /** * wms_order_item_sn 增补货主字段与 SN 码索引。 * * 1. 新增 store_id(货主ID,可空):复核落库时从订单冗余,便于按货主隔离查询/统计; * 历史数据按 order_id + warehouse_id 关联各仓库订单分表回填。 * 2. 新增 idx_wms_order_item_sn_sn_code:支撑「按 SN 码反查订单」的查询条件 * (订单列表 where.sn_code → 先查 SN 表拿 order_id 再过滤订单,不改订单表结构); * 原唯一键 uk_wms_order_item_sn_warehouse_sn_code 以 warehouse_id 打头, * 单按 sn_code 查询无法使用,故补一条 sn_code 单列索引。 * 3. 新增 idx_wms_order_item_sn_store_id:按货主过滤/统计。 * * 幂等:列与索引已存在则跳过。 */ const TABLE_NAME = 'wms_order_item_sn'; const COLUMN_NAME = 'store_id'; const INDEX_SN_CODE = 'idx_wms_order_item_sn_sn_code'; const INDEX_STORE_ID = 'idx_wms_order_item_sn_store_id'; /** 订单分表命名:wms_order_delivery_{warehouseId}[_history|_dispatch|_outsourced] */ const ORDER_SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; /** * 判断列是否存在。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} columnName 列名。 * @return {Promise} 是否存在。 */ async function columnExists(queryInterface, tableName, columnName) { const described = await queryInterface.describeTable(tableName); return Boolean(described && described[columnName]); } /** * 判断索引是否存在。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} indexName 索引名。 * @return {Promise} 是否存在。 */ async function indexExists(queryInterface, tableName, indexName) { const indexes = await queryInterface.showIndex(tableName); return (Array.isArray(indexes) ? indexes : []).some(index => index.name === indexName); } /** * 列出库内全部订单分表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 分表名列表。 */ async function listOrderShardTables(queryInterface) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + 'ORDER BY TABLE_NAME' ); return (rows || []) .map(row => String(row.tableName || row.TABLE_NAME || '')) .filter(name => ORDER_SHARD_PATTERN.test(name)); } /** * 从订单分表回填 store_id(仅回填尚未赋值的行)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string[]} shardTables 订单分表名。 * @return {Promise} 每张分表的回填条数。 */ async function backfillStoreId(queryInterface, shardTables) { const results = []; for (const tableName of shardTables) { const [ result ] = await queryInterface.sequelize.query( `UPDATE ${TABLE_NAME} sn INNER JOIN ${tableName} o ON o.id = sn.order_id AND o.warehouse_id = sn.warehouse_id SET sn.store_id = o.store_id WHERE sn.store_id IS NULL AND o.store_id IS NOT NULL AND o.store_id > 0` ); results.push({ tableName, affectedRows: Number((result && result.affectedRows) || 0) }); } return results; } module.exports = { /** * 执行迁移。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 构造函数。 * @return {Promise} 无返回值。 */ async up(queryInterface, Sequelize) { const log = []; if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { log.push(`skip column ${COLUMN_NAME} (exists)`); } else { await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, { type: Sequelize.BIGINT(20).UNSIGNED, allowNull: true, defaultValue: null, after: 'warehouse_id', comment: '货主ID(复核落库时从订单冗余)', }); log.push(`added column ${COLUMN_NAME}`); } const shardTables = await listOrderShardTables(queryInterface); const backfillResults = await backfillStoreId(queryInterface, shardTables); log.push(`backfill: ${JSON.stringify(backfillResults)}`); if (await indexExists(queryInterface, TABLE_NAME, INDEX_SN_CODE)) { log.push(`skip index ${INDEX_SN_CODE} (exists)`); } else { await queryInterface.addIndex(TABLE_NAME, [ 'sn_code' ], { name: INDEX_SN_CODE }); log.push(`added index ${INDEX_SN_CODE}`); } if (await indexExists(queryInterface, TABLE_NAME, INDEX_STORE_ID)) { log.push(`skip index ${INDEX_STORE_ID} (exists)`); } else { await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: INDEX_STORE_ID }); log.push(`added index ${INDEX_STORE_ID}`); } console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] up:', log.join(' | ')); }, /** * 回滚:删除索引与 store_id 列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { const log = []; for (const indexName of [ INDEX_SN_CODE, INDEX_STORE_ID ]) { if (await indexExists(queryInterface, TABLE_NAME, indexName)) { await queryInterface.removeIndex(TABLE_NAME, indexName); log.push(`removed index ${indexName}`); } else { log.push(`skip index ${indexName} (missing)`); } } if (await columnExists(queryInterface, TABLE_NAME, COLUMN_NAME)) { await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME); log.push(`removed column ${COLUMN_NAME}`); } else { log.push(`skip column ${COLUMN_NAME} (missing)`); } console.log('[20261113233000-add-store-id-and-indexes-to-order-item-sn] down:', log.join(' | ')); }, };