Skip to content
This repository was archived by the owner on May 31, 2025. It is now read-only.

Commit 1e65901

Browse files
committed
fix(condition): fix in and not in condition if value is empty
1 parent 5952c41 commit 1e65901

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

condition/condition.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,16 @@ func buildExpr(cond *sqlbuilder.Cond, field string, operator Operator, value any
9090
case LessEqualThan:
9191
return cond.LessEqualThan(field, value)
9292
case In:
93+
if len(castx.ToSlice(value)) == 0 {
94+
// if value is empty, force placeholder nil to avoid sql error
95+
return cond.In(field, nil)
96+
}
9397
return cond.In(field, castx.ToSlice(value)...)
9498
case NotIn:
99+
if len(castx.ToSlice(value)) == 0 {
100+
// if value is empty, force placeholder nil to avoid sql error
101+
return cond.NotIn(field, nil)
102+
}
95103
return cond.NotIn(field, castx.ToSlice(value)...)
96104
case Like:
97105
return cond.Like(field, value)

condition/condition_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,31 @@ func TestRawWhereClause(t *testing.T) {
169169
fmt.Println(sql)
170170
fmt.Println(args)
171171
}
172+
173+
func TestChain_In(t *testing.T) {
174+
t.Run("test", func(t *testing.T) {
175+
sqlbuilder.DefaultFlavor = sqlbuilder.MySQL
176+
sb := sqlbuilder.NewSelectBuilder().Select("id").From("users")
177+
builder := Select(*sb, Condition{
178+
Field: "id",
179+
Operator: In,
180+
Value: []int{1},
181+
})
182+
183+
sql, args := builder.Build()
184+
fmt.Println(sql, args)
185+
})
186+
187+
t.Run("test2", func(t *testing.T) {
188+
sqlbuilder.DefaultFlavor = sqlbuilder.MySQL
189+
sb := sqlbuilder.NewSelectBuilder().Select("id").From("users")
190+
builder := Select(*sb, Condition{
191+
Field: "id",
192+
Operator: In,
193+
Value: []int{},
194+
})
195+
196+
sql, args := builder.Build()
197+
fmt.Println(sql, args)
198+
})
199+
}

0 commit comments

Comments
 (0)