-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathconnection_test.go
More file actions
322 lines (278 loc) · 8.81 KB
/
connection_test.go
File metadata and controls
322 lines (278 loc) · 8.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package mysql
import (
"context"
"database/sql/driver"
"encoding/json"
"errors"
"net"
"testing"
"time"
)
func TestInterpolateParams(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(),
maxAllowedPacket: maxPacketSize,
cfg: &Config{
InterpolateParams: true,
},
}
q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42), "gopher"})
if err != nil {
t.Errorf("Expected err=nil, got %#v", err)
return
}
expected := `SELECT 42+'gopher'`
if q != expected {
t.Errorf("Expected: %q\nGot: %q", expected, q)
}
}
func TestInterpolateParamsJSONRawMessage(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(),
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(),
maxAllowedPacket: maxPacketSize,
cfg: &Config{
InterpolateParams: true,
},
}
q, err := mc.interpolateParams("SELECT ?+?", []driver.Value{int64(42)})
if err != driver.ErrSkip {
t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q)
}
}
// We don't support placeholder in string literal for now.
// https://github.com/go-sql-driver/mysql/pull/490
func TestInterpolateParamsPlaceholderInString(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(),
maxAllowedPacket: maxPacketSize,
cfg: &Config{
InterpolateParams: true,
},
}
q, err := mc.interpolateParams("SELECT 'abc?xyz',?", []driver.Value{int64(42)})
// When InterpolateParams support string literal, this should return `"SELECT 'abc?xyz', 42`
if err != driver.ErrSkip {
t.Errorf("Expected err=driver.ErrSkip, got err=%#v, q=%#v", err, q)
}
}
func TestInterpolateParamsUint64(t *testing.T) {
mc := &mysqlConn{
buf: newBuffer(),
maxAllowedPacket: maxPacketSize,
cfg: &Config{
InterpolateParams: true,
},
}
q, err := mc.interpolateParams("SELECT ?", []driver.Value{uint64(42)})
if err != nil {
t.Errorf("Expected err=nil, got err=%#v, q=%#v", err, q)
}
if q != "SELECT 42" {
t.Errorf("Expected uint64 interpolation to work, got q=%#v", q)
}
}
func TestCheckNamedValue(t *testing.T) {
value := driver.NamedValue{Value: ^uint64(0)}
mc := &mysqlConn{}
err := mc.CheckNamedValue(&value)
if err != nil {
t.Fatal("uint64 high-bit not convertible", err)
}
if value.Value != ^uint64(0) {
t.Fatalf("uint64 high-bit converted, got %#v %T", value.Value, value.Value)
}
}
// TestCleanCancel tests passed context is cancelled at start.
// No packet should be sent. Connection should keep current status.
func TestCleanCancel(t *testing.T) {
mc := &mysqlConn{
closech: make(chan struct{}),
}
mc.startWatcher()
defer mc.cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
for range 3 { // Repeat same behavior
err := mc.Ping(ctx)
if err != context.Canceled {
t.Errorf("expected context.Canceled, got %#v", err)
}
if mc.closed.Load() {
t.Error("expected mc is not closed, closed actually")
}
if mc.watching {
t.Error("expected watching is false, but true")
}
}
}
func TestPingMarkBadConnection(t *testing.T) {
nc := badConnection{err: errors.New("boom")}
mc := &mysqlConn{
netConn: nc,
buf: newBuffer(),
maxAllowedPacket: defaultMaxAllowedPacket,
closech: make(chan struct{}),
cfg: NewConfig(),
}
err := mc.Ping(context.Background())
if err != driver.ErrBadConn {
t.Errorf("expected driver.ErrBadConn, got %#v", err)
}
}
func TestPingErrInvalidConn(t *testing.T) {
nc := badConnection{err: errors.New("failed to write"), n: 10}
mc := &mysqlConn{
netConn: nc,
buf: newBuffer(),
maxAllowedPacket: defaultMaxAllowedPacket,
closech: make(chan struct{}),
cfg: NewConfig(),
}
err := mc.Ping(context.Background())
if err != nc.err {
t.Errorf("expected %#v, got %#v", nc.err, err)
}
}
type badConnection struct {
n int
err error
net.Conn
}
func (bc badConnection) Write(b []byte) (n int, err error) {
return bc.n, bc.err
}
func (bc badConnection) Close() error {
return nil
}
// chunkedConn is a net.Conn that serves pre-built data chunks, one per Read
// call. This simulates the behavior seen with TLS connections, where the
// server's TLS library typically produces a separate TLS record per write
// and Go's crypto/tls.Read returns one record at a time.
type chunkedConn struct {
chunks [][]byte
idx int // current chunk index
off int // offset within current chunk
}
func (c *chunkedConn) Read(b []byte) (int, error) {
if c.idx >= len(c.chunks) {
return 0, errors.New("no more data")
}
n := copy(b, c.chunks[c.idx][c.off:])
c.off += n
if c.off >= len(c.chunks[c.idx]) {
c.idx++
c.off = 0
}
return n, nil
}
func (c *chunkedConn) Write(b []byte) (int, error) { return len(b), nil } // swallow writes (e.g. COM_QUERY)
func (c *chunkedConn) Close() error { return nil }
func (c *chunkedConn) LocalAddr() net.Addr { return nil }
func (c *chunkedConn) RemoteAddr() net.Addr { return nil }
func (c *chunkedConn) SetDeadline(_ time.Time) error { return nil }
func (c *chunkedConn) SetReadDeadline(_ time.Time) error { return nil }
func (c *chunkedConn) SetWriteDeadline(_ time.Time) error { return nil }
var _ net.Conn = (*chunkedConn)(nil)
// makePacket wraps a payload in a MySQL protocol packet header.
func makePacket(seq byte, payload []byte) []byte {
pkt := make([]byte, 4+len(payload))
pkt[0] = byte(len(payload))
pkt[1] = byte(len(payload) >> 8)
pkt[2] = byte(len(payload) >> 16)
pkt[3] = seq
copy(pkt[4:], payload)
return pkt
}
// TestGetSystemVarBufferReuse verifies that getSystemVar returns a value that
// is not corrupted by the subsequent skipRows call.
//
// The row value returned by readRow points into the read buffer. skipRows may
// call fill(), which overwrites that memory. The test feeds each protocol
// packet as a separate Read call via chunkedConn (mimicking TLS record
// boundaries), guaranteeing that fill() is called for the trailing EOF.
func TestGetSystemVarBufferReuse(t *testing.T) {
// Protocol response for: SELECT @@max_allowed_packet → "67108864"
//
// Sequence numbers start at 1 (client sent COM_QUERY as seq 0).
//
// seq 1: column count = 1
// seq 2: column definition (minimal valid)
// seq 3: EOF (end of column defs)
// seq 4: row data — length-encoded string "67108864"
// seq 5: EOF (end of rows)
colCountPkt := makePacket(1, []byte{0x01})
colDef := []byte{
0x03, 'd', 'e', 'f', // catalog = "def"
0x00, // schema = ""
0x00, // table = ""
0x00, // org_table = ""
0x14, // name length = 20
'@', '@', 'm', 'a', 'x', '_', 'a', 'l', 'l', 'o',
'w', 'e', 'd', '_', 'p', 'a', 'c', 'k', 'e', 't',
0x00, // org_name = ""
0x0c, // length of fixed fields
0x3f, 0x00, // charset = 63 (binary)
0x14, 0x00, 0x00, 0x00, // column_length = 20
0x0f, // type = FIELD_TYPE_VARCHAR
0x00, 0x00, // flags
0x00, // decimals
0x00, 0x00, // filler
}
colDefPkt := makePacket(2, colDef)
eof1 := makePacket(3, []byte{0xfe, 0x00, 0x00, 0x02, 0x00})
// Row: length-encoded string "67108864" (8 bytes → length prefix 0x08)
rowPkt := makePacket(4, []byte{0x08, '6', '7', '1', '0', '8', '8', '6', '4'})
eof2 := makePacket(5, []byte{0xfe, 0x00, 0x00, 0x02, 0x00})
// Each packet arrives in its own Read call, simulating TLS record
// boundaries where each server Write becomes a separate TLS record
// and each client Read returns exactly one record.
conn := &chunkedConn{chunks: [][]byte{colCountPkt, colDefPkt, eof1, rowPkt, eof2}}
mc := &mysqlConn{
netConn: conn,
buf: newBuffer(),
cfg: NewConfig(),
closech: make(chan struct{}),
maxAllowedPacket: defaultMaxAllowedPacket,
sequence: 1, // after COM_QUERY (seq 0)
}
val, err := mc.getSystemVar("max_allowed_packet")
if err != nil {
t.Fatalf("getSystemVar failed: %v", err)
}
const expected = "67108864"
if val != expected {
t.Fatalf("getSystemVar(max_allowed_packet) = %q, want %q", val, expected)
}
}