Skip to content

Commit c4f1976

Browse files
authored
connection: interpolate json.RawMessage as string (go-sql-driver#1058)
json encoded data is represented as bytes however it should be interpolated as a string Fixes go-sql-driver#819
1 parent 17ef3dd commit c4f1976

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
Aaron Hopkins <go-sql-driver at die.net>
1515
Achille Roussel <achille.roussel at gmail.com>
16+
Alex Snast <alexsn at fb.com>
1617
Alexey Palazhchenko <alexey.palazhchenko at gmail.com>
1718
Andrew Reid <andrew.reid at tixtrack.com>
1819
Arne Hormann <arnehormann at gmail.com>

connection.go

+9
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"context"
1313
"database/sql"
1414
"database/sql/driver"
15+
"encoding/json"
1516
"io"
1617
"net"
1718
"strconv"
@@ -271,6 +272,14 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin
271272
}
272273
buf = append(buf, '\'')
273274
}
275+
case json.RawMessage:
276+
buf = append(buf, '\'')
277+
if mc.status&statusNoBackslashEscapes == 0 {
278+
buf = escapeBytesBackslash(buf, v)
279+
} else {
280+
buf = escapeBytesQuotes(buf, v)
281+
}
282+
buf = append(buf, '\'')
274283
case []byte:
275284
if v == nil {
276285
buf = append(buf, "NULL"...)

connection_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ package mysql
1111
import (
1212
"context"
1313
"database/sql/driver"
14+
"encoding/json"
1415
"errors"
1516
"net"
1617
"testing"
@@ -36,6 +37,33 @@ func TestInterpolateParams(t *testing.T) {
3637
}
3738
}
3839

40+
func TestInterpolateParamsJSONRawMessage(t *testing.T) {
41+
mc := &mysqlConn{
42+
buf: newBuffer(nil),
43+
maxAllowedPacket: maxPacketSize,
44+
cfg: &Config{
45+
InterpolateParams: true,
46+
},
47+
}
48+
49+
buf, err := json.Marshal(struct {
50+
Value int `json:"value"`
51+
}{Value: 42})
52+
if err != nil {
53+
t.Errorf("Expected err=nil, got %#v", err)
54+
return
55+
}
56+
q, err := mc.interpolateParams("SELECT ?", []driver.Value{json.RawMessage(buf)})
57+
if err != nil {
58+
t.Errorf("Expected err=nil, got %#v", err)
59+
return
60+
}
61+
expected := `SELECT '{\"value\":42}'`
62+
if q != expected {
63+
t.Errorf("Expected: %q\nGot: %q", expected, q)
64+
}
65+
}
66+
3967
func TestInterpolateParamsTooManyPlaceholders(t *testing.T) {
4068
mc := &mysqlConn{
4169
buf: newBuffer(nil),

0 commit comments

Comments
 (0)