Skip to content

Commit

Permalink
connection: interpolate json.RawMessage as string (#1058)
Browse files Browse the repository at this point in the history
json encoded data is represented as bytes however it should be interpolated as a string

Fixes #819
  • Loading branch information
alexsn committed Feb 9, 2020
1 parent 17ef3dd commit c4f1976
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -13,6 +13,7 @@

Aaron Hopkins <go-sql-driver at die.net>
Achille Roussel <achille.roussel at gmail.com>
Alex Snast <alexsn at fb.com>
Alexey Palazhchenko <alexey.palazhchenko at gmail.com>
Andrew Reid <andrew.reid at tixtrack.com>
Arne Hormann <arnehormann at gmail.com>
Expand Down
9 changes: 9 additions & 0 deletions connection.go
Expand Up @@ -12,6 +12,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"io"
"net"
"strconv"
Expand Down Expand Up @@ -271,6 +272,14 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin
}
buf = append(buf, '\'')
}
case json.RawMessage:
buf = append(buf, '\'')
if mc.status&statusNoBackslashEscapes == 0 {
buf = escapeBytesBackslash(buf, v)
} else {
buf = escapeBytesQuotes(buf, v)
}
buf = append(buf, '\'')
case []byte:
if v == nil {
buf = append(buf, "NULL"...)
Expand Down
28 changes: 28 additions & 0 deletions connection_test.go
Expand Up @@ -11,6 +11,7 @@ package mysql
import (
"context"
"database/sql/driver"
"encoding/json"
"errors"
"net"
"testing"
Expand All @@ -36,6 +37,33 @@ func TestInterpolateParams(t *testing.T) {
}
}

func TestInterpolateParamsJSONRawMessage(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(nil),
maxAllowedPacket: maxPacketSize,
cfg: &Config{
InterpolateParams: true,
},
}

buf, err := json.Marshal(struct {
Value int `json:"value"`
}{Value: 42})
if err != nil {
t.Errorf("Expected err=nil, got %#v", err)
return
}
q, err := mc.interpolateParams("SELECT ?", []driver.Value{json.RawMessage(buf)})
if err != nil {
t.Errorf("Expected err=nil, got %#v", err)
return
}
expected := `SELECT '{\"value\":42}'`
if q != expected {
t.Errorf("Expected: %q\nGot: %q", expected, q)
}
}

func TestInterpolateParamsTooManyPlaceholders(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(nil),
Expand Down

0 comments on commit c4f1976

Please sign in to comment.