68 lines
2.6 KiB
JavaScript
68 lines
2.6 KiB
JavaScript
'use strict';
|
||
|
||
const TABLE_NAME = 'wms_shops';
|
||
const UNIQUE_INDEX_NAME = 'uk_warehouse_platform_shop_name';
|
||
const PLAIN_INDEX_NAME = 'idx_warehouse_platform_shop_name';
|
||
|
||
/**
|
||
* 检查指定表中是否存在指定名称的索引(通过 SHOW INDEX 做幂等判断)。
|
||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||
* @param {string} tableName 表名。
|
||
* @param {string} indexName 索引名。
|
||
* @returns {Promise<boolean>} 索引是否存在。
|
||
*/
|
||
const hasIndex = async (queryInterface, tableName, indexName) => {
|
||
const [rows] = await queryInterface.sequelize.query(
|
||
`SHOW INDEX FROM \`${tableName}\` WHERE Key_name = :indexName`,
|
||
{ replacements: { indexName } }
|
||
);
|
||
return rows && rows.length > 0;
|
||
};
|
||
|
||
module.exports = {
|
||
/**
|
||
* 正向迁移:删除唯一约束,改为普通索引。
|
||
* 原因:菜鸟 OAuth 授权回调时,预授权记录(status=0)与已授权记录(status=1)因同名店铺
|
||
* 触发 UNIQUE KEY `uk_warehouse_platform_shop_name` 约束冲突,导致 MySQL UPDATE 失败。
|
||
* 故将此唯一约束降为普通索引,仅保留查询性能。
|
||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||
* @returns {Promise<void>} 无返回值。
|
||
*/
|
||
async up(queryInterface) {
|
||
// 1. 删除唯一索引
|
||
if (await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME)) {
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${UNIQUE_INDEX_NAME}\`;`
|
||
);
|
||
}
|
||
|
||
// 2. 添加普通索引(仅用于查询性能)
|
||
if (!(await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME))) {
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${TABLE_NAME}\` ADD INDEX \`${PLAIN_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);`
|
||
);
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 回滚迁移:恢复唯一约束。
|
||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||
* @returns {Promise<void>} 无返回值。
|
||
*/
|
||
async down(queryInterface) {
|
||
// 1. 删除普通索引
|
||
if (await hasIndex(queryInterface, TABLE_NAME, PLAIN_INDEX_NAME)) {
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${TABLE_NAME}\` DROP INDEX \`${PLAIN_INDEX_NAME}\`;`
|
||
);
|
||
}
|
||
|
||
// 2. 恢复唯一索引(幂等:已存在则跳过)
|
||
if (!(await hasIndex(queryInterface, TABLE_NAME, UNIQUE_INDEX_NAME))) {
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${TABLE_NAME}\` ADD UNIQUE INDEX \`${UNIQUE_INDEX_NAME}\` (warehouse_id, platform_code, shop_name);`
|
||
);
|
||
}
|
||
},
|
||
};
|