'use strict'; /** * wms_order_express 三个 Y/N 标记列补单列索引: * * - `is_back`(是否退回)、`is_intercept`(是否拦截)、`is_galaxy_receive`(是否揽收) * 是运单列表的常用筛选条件,但此前均无索引; * - 运单表约 159 万行(生产),按单列筛选会走全表扫,且刚才的 NULL→'N' 回填里 * `MIN(id)/MAX(id) WHERE col IS NULL` 也需要 90s+; * - 三列区分度不高(Y/N 两值),但查询总是叠加 warehouse_id 等前置条件时收益有限, * 因此按「单列索引」建,交给优化器按组合选择; * 选择单列而非联合索引,是为了同时服务 * `is_galaxy_receive='N'`(未揽收待更新)、`is_back='Y'`、`is_intercept='Y'` 等 * 各方向独立的筛选与批量更新。 * * 执行方式:`ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE` * (MySQL 5.7 在线加二级索引,不重建表、不阻塞读写)。 * 幂等:索引已存在时跳过。 */ const TABLE_NAME = 'wms_order_express'; const INDEXES = [ { name: 'idx_is_back', column: 'is_back' }, { name: 'idx_is_intercept', column: 'is_intercept' }, { name: 'idx_is_galaxy_receive', column: 'is_galaxy_receive' }, ]; /** * 判断列是否存在。 * @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 = { /** * 执行迁移:为三个标记列分别建立单列索引。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async up(queryInterface) { for (const { name, column } of INDEXES) { if (!(await columnExists(queryInterface, TABLE_NAME, column))) { console.log(`[${name}] skip: ${TABLE_NAME}.${column} 列不存在`); continue; } if (await indexExists(queryInterface, TABLE_NAME, name)) { console.log(`[${name}] skip: 索引已存在`); continue; } await queryInterface.sequelize.query( `ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${name}\` (\`${column}\`), ALGORITHM=INPLACE, LOCK=NONE` ); console.log(`[${name}] added on ${TABLE_NAME}(${column})`); } }, /** * 回滚迁移:移除三个单列索引。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { for (const { name } of INDEXES) { if (!(await indexExists(queryInterface, TABLE_NAME, name))) continue; await queryInterface.sequelize.query( `ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${name}\`, ALGORITHM=INPLACE, LOCK=NONE` ); console.log(`[${name}] dropped`); } }, };