Eq, Neq support slice of data

This commit is contained in:
Jinzhu 2021-05-31 15:25:38 +08:00
parent 363f9b7863
commit 14e96080d8
2 changed files with 46 additions and 10 deletions

View File

@ -233,11 +233,24 @@ type Eq struct {
func (eq Eq) Build(builder Builder) { func (eq Eq) Build(builder Builder) {
builder.WriteQuoted(eq.Column) builder.WriteQuoted(eq.Column)
if eqNil(eq.Value) { switch eq.Value.(type) {
builder.WriteString(" IS NULL") case []string, []int, []int32, []int64, []uint, []uint32, []uint64, []interface{}:
} else { builder.WriteString(" IN (")
builder.WriteString(" = ") rv := reflect.ValueOf(eq.Value)
builder.AddVar(builder, eq.Value) for i := 0; i < rv.Len(); i++ {
if i > 0 {
builder.WriteByte(',')
}
builder.AddVar(builder, rv.Index(i))
}
builder.WriteByte(')')
default:
if eqNil(eq.Value) {
builder.WriteString(" IS NULL")
} else {
builder.WriteString(" = ")
builder.AddVar(builder, eq.Value)
}
} }
} }
@ -251,11 +264,24 @@ type Neq Eq
func (neq Neq) Build(builder Builder) { func (neq Neq) Build(builder Builder) {
builder.WriteQuoted(neq.Column) builder.WriteQuoted(neq.Column)
if eqNil(neq.Value) { switch neq.Value.(type) {
builder.WriteString(" IS NOT NULL") case []string, []int, []int32, []int64, []uint, []uint32, []uint64, []interface{}:
} else { builder.WriteString(" NOT IN (")
builder.WriteString(" <> ") rv := reflect.ValueOf(neq.Value)
builder.AddVar(builder, neq.Value) for i := 0; i < rv.Len(); i++ {
if i > 0 {
builder.WriteByte(',')
}
builder.AddVar(builder, rv.Index(i))
}
builder.WriteByte(')')
default:
if eqNil(neq.Value) {
builder.WriteString(" IS NOT NULL")
} else {
builder.WriteString(" <> ")
builder.AddVar(builder, neq.Value)
}
} }
} }

View File

@ -136,6 +136,16 @@ func TestExpression(t *testing.T) {
clause.Neq{Column: column, Value: (interface{})(nil)}, clause.Neq{Column: column, Value: (interface{})(nil)},
}, },
Result: "`column-name` IS NOT NULL", Result: "`column-name` IS NOT NULL",
}, {
Expressions: []clause.Expression{
clause.Eq{Column: column, Value: []string{"a", "b"}},
},
Result: "`column-name` IN (?,?)",
}, {
Expressions: []clause.Expression{
clause.Neq{Column: column, Value: []string{"a", "b"}},
},
Result: "`column-name` NOT IN (?,?)",
}} }}
for idx, result := range results { for idx, result := range results {