From 093694fbf2922a3dff56059504ead6974399febf Mon Sep 17 00:00:00 2001 From: Sec Cake Date: Fri, 20 Aug 2021 18:06:48 +0800 Subject: [PATCH] Fix extra 'AND' when len(values) == 0 ON IN.NegationBuild() (#4618) --- clause/expression.go | 4 ++-- tests/query_test.go | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/clause/expression.go b/clause/expression.go index a177c5d8..f7b93f4c 100644 --- a/clause/expression.go +++ b/clause/expression.go @@ -210,11 +210,12 @@ 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 @@ -222,7 +223,6 @@ func (in IN) NegationBuild(builder Builder) { fallthrough default: - builder.WriteQuoted(in.Column) builder.WriteString(" NOT IN (") builder.AddVar(builder, in.Values...) builder.WriteByte(')') diff --git a/tests/query_test.go b/tests/query_test.go index 36046aee..8a476598 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -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())