'use strict'; const TABLE_NAME = 'wms_inbox_group'; /** 合并重复记录时允许从重复行补齐到保留行的字段 */ const FILLABLE_FIELDS = [ 'store_id', 'group_type', 'sub_type', 'source_type', 'source_extra', 'express_interfaces', 'system_express_code', ]; async function indexExists(queryInterface, tableName, indexName) { const indexes = await queryInterface.showIndex(tableName); return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName); } async function dropIndexIfExists(queryInterface, tableName, indexName) { if (await indexExists(queryInterface, tableName, indexName)) { await queryInterface.removeIndex(tableName, indexName); console.log(`[idx] ${tableName}.${indexName} 已删除`); } } async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) { if (await indexExists(queryInterface, tableName, indexName)) { console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`); return; } await queryInterface.addIndex(tableName, options.fields, { name: indexName, unique: !!options.unique, }); console.log(`[idx] ${tableName}.${indexName} 已创建`); } /** * 合并 (warehouse_id, group_id) 相同的重复群记录,为唯一索引铺路。 * 保留策略:is_blocked=0(启用)优先,其次 created_at 最早; * 群名称取 updated_at 最新一条的名称;其余字段为空时从重复行补齐;其余行软删除。 * * @param {Object} queryInterface Sequelize QueryInterface 实例。 * @return {Promise} */ async function mergeDuplicateGroups(queryInterface) { const q = queryInterface.sequelize; const dupGroups = await q.query( `SELECT warehouse_id, group_id FROM \`${TABLE_NAME}\` WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL GROUP BY warehouse_id, group_id HAVING COUNT(*) > 1`, { type: q.QueryTypes.SELECT } ); for (const g of dupGroups) { const rows = await q.query( `SELECT * FROM \`${TABLE_NAME}\` WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL ORDER BY is_blocked ASC, created_at ASC, id ASC`, { replacements: [ g.warehouse_id, g.group_id ], type: q.QueryTypes.SELECT } ); if (!rows || rows.length < 2) continue; const keep = rows[0]; const nameRow = [ ...rows ].sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0]; const dropIds = rows.filter(r => r.id !== keep.id).map(r => r.id); const updates = {}; if (keep.group_name !== nameRow.group_name) { updates.group_name = nameRow.group_name; } for (const field of FILLABLE_FIELDS) { if (keep[field] === null || keep[field] === undefined || keep[field] === '') { for (const row of rows) { if (row.id === keep.id) continue; if (row[field] !== null && row[field] !== undefined && row[field] !== '') { updates[field] = row[field]; break; } } } } if (Object.keys(updates).length > 0) { const setClauses = Object.keys(updates).map(k => `\`${k}\` = ?`).join(', '); await q.query( `UPDATE \`${TABLE_NAME}\` SET ${setClauses}, updated_at = NOW() WHERE id = ?`, { replacements: [ ...Object.values(updates), keep.id ] } ); console.log(`[dedupe] 保留 id=${keep.id} group_id=${g.group_id},更新: ${JSON.stringify(updates)}`); } const placeholders = dropIds.map(() => '?').join(','); await q.query( `UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`, { replacements: dropIds } ); console.log(`[dedupe] 软删除 id=${dropIds.join(',')} group_id=${g.group_id}`); } } module.exports = { // eslint-disable-next-line no-unused-vars up: async (queryInterface, Sequelize) => { // 1. 清理 (warehouse_id, group_id) 重复记录,否则唯一索引无法创建 await mergeDuplicateGroups(queryInterface); // 2. 删除错误的唯一索引 uk_group_warehouse(group_name, warehouse_id) // 群名称会变化,不应作为唯一约束维度 await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_group_warehouse'); // 3. 删除与唯一索引覆盖范围重复的普通索引 idx_warehouse_group_id await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id'); // 4. 新建唯一索引 (warehouse_id, group_id) // group_id 允许 NULL,MySQL 唯一索引允许多个 NULL,不影响无群ID的记录 await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id', { fields: [ 'warehouse_id', 'group_id' ], unique: true, }); }, down: async queryInterface => { await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_group_id'); await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_warehouse_group_id', { fields: [ 'warehouse_id', 'group_id' ], }); await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_group_warehouse', { fields: [ 'group_name', 'warehouse_id' ], unique: true, }); }, };