WMS_MAIN/database/migrations/20260929130000-unique-stock-check-record-detail-location.js

59 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 盘点作业记录表覆盖式语义加固:
* 1. location_code 归一:NULL → ''(空串表示"无库位"分组,使唯一索引可约束空库位场景)。
* 2. 合并历史重复记录:同一 (detail_id, location_code) 组保留 id 最大(最新)的一条,其余删除。
* 3. location_code 改为 NOT NULL DEFAULT ''。
* 4. 新增唯一索引 uk_detail_location(detail_id, location_code),从数据库层面保证
* report 覆盖式上报(同明细+同库位更新而非新增)在并发下不产生重复记录。
*/
const TABLE_NAME = 'wms_stock_check_record';
module.exports = {
up: async (queryInterface, Sequelize) => {
const { STRING } = Sequelize;
// 1) NULL → ''
await queryInterface.sequelize.query(
`UPDATE ${TABLE_NAME} SET location_code = '' WHERE location_code IS NULL`
);
// 2) 合并重复:每组保留 id 最大的记录
await queryInterface.sequelize.query(`
DELETE r1 FROM ${TABLE_NAME} r1
JOIN ${TABLE_NAME} r2
ON r1.detail_id = r2.detail_id
AND r1.location_code = r2.location_code
AND r1.id < r2.id
`);
// 3) 列定义调整
await queryInterface.changeColumn(TABLE_NAME, 'location_code', {
type: STRING(50),
allowNull: false,
defaultValue: '',
comment: '库位编码(盘点上报的库位,空串表示无库位分组)',
});
// 4) 唯一索引(覆盖式语义的数据库层保证)
await queryInterface.addIndex(TABLE_NAME, [ 'detail_id', 'location_code' ], {
unique: true,
name: 'uk_detail_location',
});
},
down: async (queryInterface, Sequelize) => {
const { STRING } = Sequelize;
await queryInterface.removeIndex(TABLE_NAME, 'uk_detail_location');
await queryInterface.changeColumn(TABLE_NAME, 'location_code', {
type: STRING(50),
allowNull: true,
defaultValue: null,
comment: '库位编码(盘点上报的库位)',
});
},
};