Skip to content

Commit

Permalink
return 1=0 when values of condition IN are empty
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Apr 6, 2024
1 parent aa1124e commit a21b04b
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 4 deletions.
17 changes: 13 additions & 4 deletions op_condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
65 changes: 65 additions & 0 deletions op_condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package sqlx

import (
"reflect"
"testing"

"github.com/xgfone/go-op"
Expand Down Expand Up @@ -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)
}
}

0 comments on commit a21b04b

Please sign in to comment.