refactor(db): 简化设备索引迁移脚本逻辑

- 提取重复的索引检查创建逻辑为公共函数addIndexIfNotExists
- 减少冗余代码,提升脚本可维护性
This commit is contained in:
zhang1106
2026-05-12 09:37:12 +08:00
parent 0cf158ae40
commit a8e45d2d8a
+1 -32
View File
@@ -797,7 +797,6 @@ async function migrateIdleDeviceAndBusiness() {
}
async function migrateDevicePositionIndexes() {
const dialect = sequelize.getDialect();
const tableName = 'devices';
if (!(await tableExists(tableName))) {
@@ -811,37 +810,7 @@ async function migrateDevicePositionIndexes() {
];
for (const idx of indexesToCreate) {
console.log(` → 为 ${tableName} 表添加复合索引 ${idx.name}...`);
try {
const existingIndexes = await sequelize.query(`SHOW INDEX FROM ${tableName}`, {
type: sequelize.QueryTypes.SELECT,
});
const indexExists = existingIndexes.some(existing => existing.Key_name === idx.name);
if (indexExists) {
console.log(' → 索引已存在,跳过');
} else {
if (dialect === 'sqlite') {
await sequelize.query(
`CREATE INDEX IF NOT EXISTS ${idx.name} ON ${tableName}(${idx.fields.join(', ')})`
);
} else {
await sequelize.query(
`CREATE INDEX \`${idx.name}\` ON \`${tableName}\`(\`${idx.fields.join('`, `')}\`)`
);
}
console.log(' ✓ 索引创建成功');
}
} catch (error) {
if (
error.message.includes('already exists') ||
error.message.includes('Duplicate key name')
) {
console.log(' → 索引已存在,跳过');
} else {
throw error;
}
}
await addIndexIfNotExists(tableName, idx.name, idx.fields);
}
}