diff --git a/op_condition.go b/op_condition.go index a66e529..8f60297 100644 --- a/op_condition.go +++ b/op_condition.go @@ -133,6 +133,9 @@ func newCondGroup(sep string) OpBuilder { panic(fmt.Errorf("sqlx: unsupported value type %T for op '%s:%v'", _op.Val, _op.Kind, _op.Op)) } + if len(ss) == 0 { + return "" + } return fmt.Sprintf("(%s)", strings.Join(ss, sep)) }) } diff --git a/op_condition_test.go b/op_condition_test.go index fd4c5e6..331d7c1 100644 --- a/op_condition_test.go +++ b/op_condition_test.go @@ -46,4 +46,25 @@ func TestAnd(t *testing.T) { } } } + + if sql := BuildOper(NewArgsBuilder(MySQL), op.And()); sql != "" { + t.Errorf("expect an empty sql, but got: %s", sql) + } + + expectsql = "SELECT `c1`, `c2` FROM `table` WHERE `id`=?" + expectargs = []interface{}{1} + sql, args = Selects("c1", "c2").From("table").Where(op.And(op.Eq("id", 1), op.And())).Build() + if expectsql != sql { + t.Errorf("expect sql: %s; but got: %s;", expectsql, sql) + } + + if len(args) != len(expectargs) { + t.Errorf("expect %d args, but got %d", len(expectargs), len(args)) + } else { + for i, arg := range args { + if expect := expectargs[i]; expect != arg { + t.Errorf("args %d: expect '%v', but got '%v'", i, expect, arg) + } + } + } } diff --git a/utils.go b/utils.go index 02f9d8c..9fa9693 100644 --- a/utils.go +++ b/utils.go @@ -710,6 +710,10 @@ func isZero(v reflect.Value) bool { } func toslice[S1 ~[]E1, E1, E2 any](srcs S1, to func(E1) E2) (dsts []E2) { + if len(srcs) == 0 { + return + } + dsts = make([]E2, len(srcs)) for i, src := range srcs { dsts[i] = to(src)