'use strict'; /** * 调整视频补录请求表(wms_video_record_request)的定时扫描索引。 * * 背景:结果通知定时任务(app/schedule/notify_video_record_result.js,每分钟一次) * 的取数条件是「在途 + 未通知」: * * WHERE status IN ('pending','requested','recording') * AND is_notified = 0 * AND deleted_at IS NULL * ORDER BY id ASC LIMIT 10 * * 单列 idx_status 只能命中 status 一层,随后还要回表按 is_notified 过滤; * 后续若按「超时」维度拆查询,还会用到 last_request_at 范围条件。 * * 因此: * - 新增 idx_status_notified_last_request (status, is_notified, last_request_at) * - 移除冗余的 idx_status(新索引以 status 为最左前缀,可覆盖原查询场景) * * 幂等:先 showIndex 判断存在性再增删,可重复执行。 */ const TABLE_NAME = 'wms_video_record_request'; const OLD_INDEX = 'idx_status'; const NEW_INDEX = 'idx_status_notified_last_request'; /** * 获取指定表的索引名集合。 * * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise>} 索引名集合。 */ const getIndexNameSet = async queryInterface => { const indexes = await queryInterface.showIndex(TABLE_NAME); return new Set( (Array.isArray(indexes) ? indexes : []) .map(index => String(index && index.name ? index.name : '').trim()) .filter(Boolean) ); }; module.exports = { /** * 执行迁移:新增覆盖扫描条件的组合索引,并移除冗余单列索引。 * * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async up(queryInterface) { const indexNameSet = await getIndexNameSet(queryInterface); if (!indexNameSet.has(NEW_INDEX)) { await queryInterface.addIndex(TABLE_NAME, { name: NEW_INDEX, fields: [ 'status', 'is_notified', 'last_request_at' ], }); } if (indexNameSet.has(OLD_INDEX)) { await queryInterface.removeIndex(TABLE_NAME, OLD_INDEX); } }, /** * 回滚迁移:恢复单列 idx_status,移除组合索引。 * * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { const indexNameSet = await getIndexNameSet(queryInterface); if (indexNameSet.has(NEW_INDEX)) { await queryInterface.removeIndex(TABLE_NAME, NEW_INDEX); } if (!indexNameSet.has(OLD_INDEX)) { await queryInterface.addIndex(TABLE_NAME, { name: OLD_INDEX, fields: [ 'status' ], }); } }, };