Skip to content

Commit

Permalink
Fix jmoiron#473: handle nil arguments in In()
Browse files Browse the repository at this point in the history
  • Loading branch information
ojrac committed Aug 16, 2019
1 parent 38398a3 commit b1416de
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
25 changes: 21 additions & 4 deletions bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@ func rebindBuff(bindType int, query string) string {
return rqb.String()
}

func asSliceToExpand(i interface{}) (v reflect.Value, ok bool) {
if i == nil {
ok = false
return
}

v = reflect.ValueOf(i)
t := reflectx.Deref(v.Type())

// []byte is a driver.Value type so it should not be expanded
ok = t.Kind() == reflect.Slice && t != reflect.TypeOf([]byte{})

if !ok {
// Don't return non-expandable values
v = reflect.Value{}
}

return
}

// In expands slice values in args, returning the modified query string
// and a new arg list that can be executed by a database. The `query` should
// use the `?` bindVar. The return value uses the `?` bindVar.
Expand All @@ -119,11 +139,8 @@ func In(query string, args ...interface{}) (string, []interface{}, error) {
if a, ok := arg.(driver.Valuer); ok {
arg, _ = a.Value()
}
v := reflect.ValueOf(arg)
t := reflectx.Deref(v.Type())

// []byte is a driver.Value type so it should not be expanded
if t.Kind() == reflect.Slice && t != reflect.TypeOf([]byte{}) {
if v, ok := asSliceToExpand(arg); ok {
meta[i].length = v.Len()
meta[i].v = v

Expand Down
3 changes: 3 additions & 0 deletions sqlx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1511,6 +1511,9 @@ func TestIn(t *testing.T) {
{"SELECT * FROM foo WHERE x = ? AND y in (?)",
[]interface{}{[]byte("foo"), []int{0, 5, 3}},
4},
{"SELECT * FROM foo WHERE x = ? AND y IN (?)",
[]interface{}{sql.NullString{Valid: false}, []string{"a", "b"}},
3},
}
for _, test := range tests {
q, a, err := In(test.q, test.args...)
Expand Down

0 comments on commit b1416de

Please sign in to comment.