Skip to content

Commit

Permalink
Fix extra 'AND' when len(values) == 0 ON IN.NegationBuild() (#4618)
Browse files Browse the repository at this point in the history
  • Loading branch information
secake authored Aug 20, 2021
1 parent 7a53d8e commit 093694f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 2 additions & 2 deletions clause/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,19 +210,19 @@ func (in IN) Build(builder Builder) {
}

func (in IN) NegationBuild(builder Builder) {
builder.WriteQuoted(in.Column)
switch len(in.Values) {
case 0:
builder.WriteString(" IS NOT NULL")
case 1:
if _, ok := in.Values[0].([]interface{}); !ok {
builder.WriteQuoted(in.Column)
builder.WriteString(" <> ")
builder.AddVar(builder, in.Values[0])
break
}

fallthrough
default:
builder.WriteQuoted(in.Column)
builder.WriteString(" NOT IN (")
builder.AddVar(builder, in.Values...)
builder.WriteByte(')')
Expand Down
5 changes: 5 additions & 0 deletions tests/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,11 @@ func TestNot(t *testing.T) {
t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
}

result = dryDB.Not(map[string]interface{}{"name": []string{}}).Find(&User{})
if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* IS NOT NULL").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
}

result = dryDB.Not(map[string]interface{}{"name": []string{"jinzhu", "jinzhu 2"}}).Find(&User{})
if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* NOT IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
Expand Down

0 comments on commit 093694f

Please sign in to comment.