From 9f2dec3036a0750d0674b3d71834fcd33fc668fa Mon Sep 17 00:00:00 2001 From: zhangwenjian Date: Fri, 14 Aug 2026 15:33:48 +0800 Subject: [PATCH] =?UTF-8?q?fix=F0=9F=90=9B:=20=E4=BF=AE=E6=AD=A3=20General?= =?UTF-8?q?DelDto.GetIds=20=E9=87=8D=E5=A4=8D=E8=BF=BD=E5=8A=A0=20Id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 该方法先在开头追加了 Id,随后 else 分支中又追加一次:仅传 Id 时返回 [5 5],删除接口会对同一条记录执行两次 DELETE。 if g.Id != 0 { ids = append(ids, g.Id) } if len(g.Ids) > 0 { ... } else { if g.Id > 0 { ids = append(ids, g.Id) } // 重复 } 去掉冗余分支,同时将首个判断由 != 0 收紧为 > 0,与 Ids 中逐个元素的 过滤条件保持一致(负数 Id 无意义)。 补充单元测试,覆盖仅 Id、仅 Ids、二者并存、含非正数、全空回退等场景。 问题由 PR #848 指出。 --- common/dto/search.go | 18 +++++++----------- common/dto/search_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 11 deletions(-) create mode 100644 common/dto/search_test.go diff --git a/common/dto/search.go b/common/dto/search.go index 72cc60e4..58f50aca 100644 --- a/common/dto/search.go +++ b/common/dto/search.go @@ -13,21 +13,17 @@ type GeneralDelDto struct { func (g GeneralDelDto) GetIds() []int { ids := make([]int, 0) - if g.Id != 0 { + // Id 此前在 else 分支里被重复追加:仅传 Id 时会得到 [5 5], + // 同一条记录被执行两次删除 + if g.Id > 0 { ids = append(ids, g.Id) } - if len(g.Ids) > 0 { - for _, id := range g.Ids { - if id > 0 { - ids = append(ids, id) - } - } - } else { - if g.Id > 0 { - ids = append(ids, g.Id) + for _, id := range g.Ids { + if id > 0 { + ids = append(ids, id) } } - if len(ids) <= 0 { + if len(ids) == 0 { //方式全部删除 ids = append(ids, 0) } diff --git a/common/dto/search_test.go b/common/dto/search_test.go new file mode 100644 index 00000000..16897fe1 --- /dev/null +++ b/common/dto/search_test.go @@ -0,0 +1,32 @@ +package dto + +import ( + "reflect" + "testing" +) + +// GetIds 曾在 else 分支中重复追加 Id:仅传 Id 时返回 [5 5], +// 导致删除接口对同一条记录执行两次。 +func TestGeneralDelDtoGetIds(t *testing.T) { + cases := []struct { + name string + dto GeneralDelDto + want []int + }{ + {"仅 Id", GeneralDelDto{Id: 5}, []int{5}}, + {"仅 Ids", GeneralDelDto{Ids: []int{1, 2}}, []int{1, 2}}, + {"Id 与 Ids 并存", GeneralDelDto{Id: 5, Ids: []int{1, 2}}, []int{5, 1, 2}}, + {"Ids 含非正数被过滤", GeneralDelDto{Ids: []int{0, -1, 3}}, []int{3}}, + {"Id 为 0 视为未传", GeneralDelDto{Id: 0, Ids: []int{7}}, []int{7}}, + {"全部为空时回退到 0(全量删除约定)", GeneralDelDto{}, []int{0}}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := c.dto.GetIds() + if !reflect.DeepEqual(got, c.want) { + t.Errorf("GetIds() = %v, want %v", got, c.want) + } + }) + } +}