From a21b04b106878e36142c294f14352a1f78f10c4d Mon Sep 17 00:00:00 2001 From: xgfone Date: Sat, 6 Apr 2024 19:34:41 +0800 Subject: [PATCH] return 1=0 when values of condition IN are empty --- op_condition.go | 17 +++++++++--- op_condition_test.go | 65 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/op_condition.go b/op_condition.go index 9951517..b3000f5 100644 --- a/op_condition.go +++ b/op_condition.go @@ -100,14 +100,23 @@ func newCondLike(format string) OpBuilder { func newCondIn(format string) OpBuilder { return OpBuilderFunc(func(ab *ArgsBuilder, op op.Op) string { vs := op.Val.([]interface{}) - if len(vs) == 0 { - return "" - } - if len(vs) == 1 { + switch len(vs) { + case 0: + return "1=0" + + case 1: if _vs, ok := vs[0].([]interface{}); ok { vs = _vs } + + switch len(vs) { + case 0: + return "1=0" + + case 1: + return fmt.Sprintf(format, ab.Quote(getOpKey(op)), ab.Add(vs[0])) + } } ss := make([]string, 0, len(vs)) diff --git a/op_condition_test.go b/op_condition_test.go index 331d7c1..92a45df 100644 --- a/op_condition_test.go +++ b/op_condition_test.go @@ -15,6 +15,7 @@ package sqlx import ( + "reflect" "testing" "github.com/xgfone/go-op" @@ -68,3 +69,67 @@ func TestAnd(t *testing.T) { } } } + +func TestCondInForNil(t *testing.T) { + ab := NewArgsBuilder(MySQL) + sql := BuildOper(ab, op.In("field")) + args := ab.Args() + + expectsql := "" + expectargs := []any{} + + if sql != expectsql { + t.Errorf("expect sql '%s', but got '%s'", expectsql, sql) + } + if !reflect.DeepEqual(args, expectargs) { + t.Errorf("expect args %v, but got %v", expectargs, args) + } +} + +func TestCondInForOne(t *testing.T) { + ab := NewArgsBuilder(MySQL) + sql := BuildOper(ab, op.In("field", "value")) + args := ab.Args() + + expectsql := "`field` IN (?)" + expectargs := []any{"value"} + + if sql != expectsql { + t.Errorf("expect sql '%s', but got '%s'", expectsql, sql) + } + if !reflect.DeepEqual(args, expectargs) { + t.Errorf("expect args %v, but got %v", expectargs, args) + } +} + +func TestCondInForOneSliceOne(t *testing.T) { + ab := NewArgsBuilder(MySQL) + sql := BuildOper(ab, op.In("field", []any{"value"})) + args := ab.Args() + + expectsql := "`field` IN (?)" + expectargs := []any{"value"} + + if sql != expectsql { + t.Errorf("expect sql '%s', but got '%s'", expectsql, sql) + } + if !reflect.DeepEqual(args, expectargs) { + t.Errorf("expect args %v, but got %v", expectargs, args) + } +} + +func TestCondInForOneSliceTwo(t *testing.T) { + ab := NewArgsBuilder(MySQL) + sql := BuildOper(ab, op.In("field", []any{"value1", "value2"})) + args := ab.Args() + + expectsql := "`field` IN (?, ?)" + expectargs := []any{"value1", "value2"} + + if sql != expectsql { + t.Errorf("expect sql '%s', but got '%s'", expectsql, sql) + } + if !reflect.DeepEqual(args, expectargs) { + t.Errorf("expect args %v, but got %v", expectargs, args) + } +}