fix(order): 波次取号原子性修复

This commit is contained in:
liufumingren 2026-08-30 07:28:17 +08:00
parent 2189911073
commit 3442ed5243

View File

@ -565,11 +565,13 @@ class WaveService extends OrderBaseService {
/**
* 获取当天前缀下的下一个波次序号(原子取号)。
*
* 基于序列表 wms_number_sequence 的单条 upsert 原子递增:
* INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE
* current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1)
* 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务):
* INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE
* current_seq = GREATEST(current_seq, :seed) + 1
* 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐;
* 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下不再撞号。
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
* 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。
* 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。
*
* @param {string} prefix 波次编号前缀。
* @param {string} datePart 日期片段(YYYYMMDD)。
@ -602,8 +604,8 @@ class WaveService extends OrderBaseService {
// 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务
await this.ctx.model.query(
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW())
ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`,
VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
{
replacements: {
warehouseId: 0,
@ -615,14 +617,24 @@ class WaveService extends OrderBaseService {
}
);
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
// FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响
const seqRows = await this.ctx.model.query(
'SELECT LAST_INSERT_ID() AS seq',
`SELECT current_seq
FROM wms_number_sequence
WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart
FOR UPDATE`,
{
replacements: {
warehouseId: 0,
bizType,
datePart: normalizedDatePart,
},
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
const sequence = Number(seqRows && seqRows[0] && seqRows[0].seq || 0);
const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0);
if (!Number.isInteger(sequence) || sequence <= 0) {
return 1;
}