'use strict'; /** * 为订单配送分表增加 wave_no 索引。 * * 背景: * - order.deliveryOrder.list(app/service/systemMethods/order/base.js#listByModule)的 SQL 形态为 * `WHERE warehouse_id=? AND dispatch_lane=? AND wave_no=? ORDER BY updated_at DESC, id DESC LIMIT ?` * 且并行执行同条件 COUNT(*); * - 生产 wms_order_delivery_1000028_dispatch(1,488,523 行 / 约 2.4GB)没有任何 wave_no 索引, * 实测 COUNT(*) 26.4s、列表查询 21.1s:优化器只能走 (warehouse_id, dispatch_lane, updated_at, id) * 或 (warehouse_id) 索引扫掉约 55 万行后逐行回表过滤 wave_no; * - wave_no 在表内近似唯一(10.25 万个波次号 / 148.8 万行,平均约 14 行/波次), * 单列索引即可把上述扫描降为十几行的点查。 * * 本迁移枚举 current/dispatch/history/outsourced 四类分表补建索引,命名与 * app/model/order_delivery_table_schema.js#buildIndexOptions 的 idx_{prefix}_wave_no 一致 * (dispatch 分表沿用 current 前缀,与既有继承索引的命名习惯一致), * 避免应用运行时 drift 同步再补建一次同名索引。 * * 执行方式:ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE * (MySQL 5.6+ 在线加二级索引,不重建表、不锁写,建议低峰期执行)。 * 幂等:索引已存在、或表缺少 wave_no 列时跳过。 * * ⚠️ 本文件未对任何环境执行,仅由迁移流程(npm run migration:single <文件名>)在确认后落库。 */ const SHARD_PATTERNS = [ { modelType: 'dispatch', pattern: /^wms_order_delivery_(\d+)_dispatch$/ }, { modelType: 'history', pattern: /^wms_order_delivery_(\d+)_history$/ }, { modelType: 'outsourced', pattern: /^wms_order_delivery_(\d+)_outsourced$/ }, { modelType: 'current', pattern: /^wms_order_delivery_(\d+)$/ }, ]; const INDEX_COLUMN = 'wave_no'; /** * 解析分表名。 * @param {string} tableName 表名。 * @return {{ modelType: string, warehouseId: string }|null} 解析结果。 */ function parseShardTableName(tableName) { for (const item of SHARD_PATTERNS) { const match = item.pattern.exec(tableName); if (match) { return { modelType: item.modelType, warehouseId: match[1] }; } } return null; } /** * 构建 wave_no 索引名(与 buildIndexOptions 的 `idx_${prefix}_wave_no` 一致)。 * @param {string} warehouseId 仓库ID。 * @param {string} modelType 模型类型。 * @return {string} 索引名。 */ function buildWaveNoIndexName(warehouseId, modelType) { const prefix = modelType === 'dispatch' ? `${warehouseId}_current` : `${warehouseId}_${modelType}`; return `idx_${prefix}_${INDEX_COLUMN}`; } /** * 列举库内所有订单配送分表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise>} 分表名列表。 */ async function listManagedShards(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 => parseShardTableName(name)); } /** * 判断表是否存在指定列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} columnName 列名。 * @return {Promise} 是否存在。 */ async function columnExists(queryInterface, tableName, columnName) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', { replacements: [ tableName, columnName ] } ); return (rows || []).length > 0; } /** * 判断索引是否已存在。 * @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 (indexes || []).some(index => { const name = String(index && (index.name || index.Key_name || index.key_name) || ''); return name.toLowerCase() === String(indexName).toLowerCase(); }); } module.exports = { /** * 执行迁移:为订单配送分表增加 wave_no 索引。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async up(queryInterface) { const shards = await listManagedShards(queryInterface); const results = []; for (const tableName of shards) { const parsed = parseShardTableName(tableName); const indexName = buildWaveNoIndexName(parsed.warehouseId, parsed.modelType); if (!(await columnExists(queryInterface, tableName, INDEX_COLUMN))) { results.push({ tableName, action: 'skip', reason: 'column-missing' }); continue; } if (await indexExists(queryInterface, tableName, indexName)) { results.push({ tableName, action: 'skip', reason: 'exists' }); continue; } await queryInterface.sequelize.query( `ALTER TABLE \`${tableName}\` ADD INDEX \`${indexName}\` (\`${INDEX_COLUMN}\`), ALGORITHM=INPLACE, LOCK=NONE` ); results.push({ tableName, action: 'added', indexName }); } console.log('[20261105190000-add-wave-no-index] up results:', JSON.stringify(results)); }, /** * 回滚迁移:移除 wave_no 索引。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { const shards = await listManagedShards(queryInterface); for (const tableName of shards) { const parsed = parseShardTableName(tableName); const indexName = buildWaveNoIndexName(parsed.warehouseId, parsed.modelType); if (!(await indexExists(queryInterface, tableName, indexName))) { continue; } await queryInterface.sequelize.query( `ALTER TABLE \`${tableName}\` DROP INDEX \`${indexName}\`, ALGORITHM=INPLACE, LOCK=NONE` ); } }, };