'use strict'; /** * 扫码记录列表(`/api/web/records`):补一个能被「覆盖」的索引 * * 该接口是 `findAndCountAll`,一次请求会跑两条 SQL: * 1. 列表:`WHERE subject_id = ? AND scanner_id IN (...) ORDER BY scan_time DESC, id DESC LIMIT 20` * 2. 总数:`WHERE` 同上,但**没有 LIMIT**(`count(id)` 要数完整个集合) * * 2026-11-16 线上实测(主体 1,约 16.5 万条): * - 列表:走 `idx_scan_time` 反向扫 + 过滤,约 28 ms,本来不慢; * - 总数:走 `idx_scan_subject_barcode`(`subject_id, barcode`)——索引里没有 `scanner_id`, * 只能**逐行回表**判断,`Rows_examined` ≈ 33 万;冷缓存 9.9 s、热缓存 0.45 s。 * 「第一次打开扫码记录很慢」就是它。 * * 加 `(subject_id, scanner_id, scan_time)` 后,总数变成纯索引扫描(不回表), * 顺带让「按设备过滤 + 按时间倒序」的列表也能直接吃索引顺序。 * * 注意:`sql/schema.sql` 基线已同步这个索引,空库执行时幂等。 */ const INDEX_NAME = 'idx_scan_subject_scanner_time'; /** 判断索引是否存在(重跑/已经手工加过的库不报错) */ async function hasIndex(queryInterface, table, name) { try { const indexes = await queryInterface.showIndex(table); return indexes.some(item => item.name === name); } catch (error) { return false; } } module.exports = { async up(queryInterface) { if (await hasIndex(queryInterface, 'scan_records', INDEX_NAME)) return; await queryInterface.addIndex('scan_records', [ 'subject_id', 'scanner_id', 'scan_time' ], { name: INDEX_NAME, }); }, async down(queryInterface) { if (!(await hasIndex(queryInterface, 'scan_records', INDEX_NAME))) return; await queryInterface.removeIndex('scan_records', INDEX_NAME); }, };