fix(clause): when the value of clause.Eq is an empty array, the SQL should be IN (NULL)

This commit is contained in:
weih 2023-08-04 10:25:41 +08:00
parent a7f01bd1b2
commit 4ac7538f12
2 changed files with 30 additions and 12 deletions

View File

@ -246,8 +246,11 @@ func (eq Eq) Build(builder Builder) {
switch eq.Value.(type) {
case []string, []int, []int32, []int64, []uint, []uint32, []uint64, []interface{}:
builder.WriteString(" IN (")
rv := reflect.ValueOf(eq.Value)
if rv.Len() == 0 {
builder.WriteString(" IN (NULL)")
} else {
builder.WriteString(" IN (")
for i := 0; i < rv.Len(); i++ {
if i > 0 {
builder.WriteByte(',')
@ -255,6 +258,7 @@ func (eq Eq) Build(builder Builder) {
builder.AddVar(builder, rv.Index(i).Interface())
}
builder.WriteByte(')')
}
default:
if eqNil(eq.Value) {
builder.WriteString(" IS NULL")
@ -277,8 +281,11 @@ func (neq Neq) Build(builder Builder) {
switch neq.Value.(type) {
case []string, []int, []int32, []int64, []uint, []uint32, []uint64, []interface{}:
builder.WriteString(" NOT IN (")
rv := reflect.ValueOf(neq.Value)
if rv.Len() == 0 {
builder.WriteString(" NOT IN (NULL)")
} else {
builder.WriteString(" NOT IN (")
for i := 0; i < rv.Len(); i++ {
if i > 0 {
builder.WriteByte(',')
@ -286,6 +293,7 @@ func (neq Neq) Build(builder Builder) {
builder.AddVar(builder, rv.Index(i).Interface())
}
builder.WriteByte(')')
}
default:
if eqNil(neq.Value) {
builder.WriteString(" IS NOT NULL")

View File

@ -199,6 +199,16 @@ func TestExpression(t *testing.T) {
},
ExpectedVars: []interface{}{"a", "b"},
Result: "`column-name` NOT IN (?,?)",
}, {
Expressions: []clause.Expression{
clause.Eq{Column: column, Value: []string{}},
},
Result: "`column-name` IN (NULL)",
}, {
Expressions: []clause.Expression{
clause.Neq{Column: column, Value: []string{}},
},
Result: "`column-name` NOT IN (NULL)",
}, {
Expressions: []clause.Expression{
clause.Eq{Column: clause.Expr{SQL: "SUM(?)", Vars: []interface{}{clause.Column{Name: "id"}}}, Value: 100},