Skip to content

Commit

Permalink
Merge c5cc0d9 into 00c6e74
Browse files Browse the repository at this point in the history
  • Loading branch information
arp242 committed Dec 28, 2020
2 parents 00c6e74 + c5cc0d9 commit 9a999e7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
8 changes: 7 additions & 1 deletion named.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,13 @@ func bindNamedMapper(bindType int, query string, arg interface{}, m *reflectx.Ma
k := t.Kind()
switch {
case k == reflect.Map && t.Key().Kind() == reflect.String:
return bindMap(bindType, query, arg.(map[string]interface{}))
var m map[string]interface{}
if !t.ConvertibleTo(reflect.TypeOf(m)) {
return "", nil, fmt.Errorf("sqlx.bindNamedMapper: unsupported map type: %T", arg)
}

m = reflect.ValueOf(arg).Convert(reflect.TypeOf(m)).Interface().(map[string]interface{})
return bindMap(bindType, query, m)
case k == reflect.Array || k == reflect.Slice:
return bindArray(bindType, query, arg, m)
default:
Expand Down
27 changes: 27 additions & 0 deletions sqlx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1738,6 +1738,33 @@ func BenchmarkBindStruct(b *testing.B) {
}
}

func TestBindNamedMapper(t *testing.T) {
type A map[string]interface{}
m := reflectx.NewMapperFunc("db", NameMapper)
query, args, err := bindNamedMapper(DOLLAR, `select :x`, A{
"x": "X!",
}, m)
if err != nil {
t.Fatal(err)
}

got := fmt.Sprintf("%s %s", query, args)
want := `select $1 [X!]`
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}

_, _, err = bindNamedMapper(DOLLAR, `select :x`, map[string]string{
"x": "X!",
}, m)
if err == nil {
t.Fatal("err is nil")
}
if !strings.Contains(err.Error(), "unsupported map type") {
t.Errorf("wrong error: %s", err)
}
}

func BenchmarkBindMap(b *testing.B) {
b.StopTimer()
q1 := `INSERT INTO foo (a, b, c, d) VALUES (:name, :age, :first, :last)`
Expand Down

0 comments on commit 9a999e7

Please sign in to comment.