This repository has been archived by the owner on Jan 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
client.go
401 lines (345 loc) · 8.68 KB
/
client.go
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* go-mysqlstack
* xelabs.org
*
* Copyright (c) XeLabs
* GPL License
*
*/
package driver
import (
"context"
"net"
"strings"
"time"
"github.com/xelabs/go-mysqlstack/packet"
"github.com/xelabs/go-mysqlstack/proto"
"github.com/xelabs/go-mysqlstack/sqldb"
"github.com/xelabs/go-mysqlstack/sqlparser/depends/common"
querypb "github.com/xelabs/go-mysqlstack/sqlparser/depends/query"
"github.com/xelabs/go-mysqlstack/sqlparser/depends/sqltypes"
)
var _ Conn = &conn{}
// Conn interface.
type Conn interface {
Ping() error
Quit()
Close() error
Closed() bool
Cleanup()
NextPacket() ([]byte, error)
// ConnectionID is the connection id at greeting.
ConnectionID() uint32
InitDB(db string) error
Command(command byte) error
Query(sql string) (Rows, error)
Exec(sql string) error
FetchAll(sql string, maxrows int) (*sqltypes.Result, error)
FetchAllWithFunc(sql string, maxrows int, fn Func) (*sqltypes.Result, error)
ComStatementPrepare(sql string) (*Statement, error)
}
type conn struct {
netConn net.Conn
auth *proto.Auth
greeting *proto.Greeting
packets *packet.Packets
}
func (c *conn) handleErrorPacket(data []byte) error {
if data[0] == proto.ERR_PACKET {
return c.packets.ParseERR(data)
}
return nil
}
func (c *conn) handShake(username, password, database, charset string) error {
var err error
var data []byte
//Parses the initial handshake from the server.
{
// greeting read
if data, err = c.packets.Next(); err != nil {
return err
}
// check greeting packet
if err = c.handleErrorPacket(data); err != nil {
return err
}
// unpack greeting packet
if err = c.greeting.UnPack(data); err != nil {
return err
}
// check greating Capability
if c.greeting.Capability&sqldb.CLIENT_PROTOCOL_41 == 0 {
err = sqldb.NewSQLError(sqldb.CR_VERSION_ERROR, "cannot connect to servers earlier than 4.1")
return err
}
}
{
cs, ok := sqldb.CharacterSetMap[strings.ToLower(charset)]
if !ok {
cs = sqldb.CharacterSetUtf8
}
// auth pack
data := c.auth.Pack(
proto.DefaultClientCapability,
cs,
username,
password,
c.greeting.Salt,
database,
)
// auth write
if err = c.packets.Write(data); err != nil {
return err
}
// clean the authreponse bytes to improve the gc pause.
c.auth.CleanAuthResponse()
}
{
// read
if data, err = c.packets.Next(); err != nil {
return err
}
if err = c.handleErrorPacket(data); err != nil {
return err
}
}
return nil
}
// NewConn used to create a new client connection.
// The timeout is 30 seconds.
func NewConn(username, password, address, database, charset string) (Conn, error) {
var err error
c := &conn{}
timeout := time.Duration(30) * time.Second
if c.netConn, err = net.DialTimeout("tcp", address, timeout); err != nil {
return nil, err
}
// Set KeepAlive to True and period to 180s.
if tcpConn, ok := c.netConn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(time.Second * 180)
c.netConn = tcpConn
}
defer func() {
if err != nil {
c.Cleanup()
}
}()
// Set timeouts, make the handshake timeout if the underflying connection blocked.
// This timeout only used in handshake, we will disable(set zero time) it at last.
c.netConn.SetReadDeadline(time.Now().Add(timeout))
defer c.netConn.SetReadDeadline(time.Time{})
c.auth = proto.NewAuth()
c.greeting = proto.NewGreeting(0, "")
c.packets = packet.NewPackets(c.netConn)
if err = c.handShake(username, password, database, charset); err != nil {
return nil, err
}
return c, nil
}
// NextPacket used to get the next packet
func (c *conn) NextPacket() ([]byte, error) {
return c.packets.Next()
}
func (c *conn) baseQuery(mode RowMode, command byte, datas []byte) (Rows, error) {
var ok *proto.OK
var myerr, err error
var columns []*querypb.Field
var colNumber int
// if err != nil means the connection is broken(packet error)
defer func() {
if err != nil {
c.Cleanup()
}
}()
// Query.
if err = c.packets.WriteCommand(command, datas); err != nil {
return nil, err
}
// Read column number.
ok, colNumber, myerr, err = c.packets.ReadComQueryResponse()
if err != nil {
return nil, err
}
if myerr != nil {
return nil, myerr
}
if colNumber > 0 {
if columns, err = c.packets.ReadColumns(colNumber); err != nil {
return nil, err
}
// Read EOF.
if (c.greeting.Capability & sqldb.CLIENT_DEPRECATE_EOF) == 0 {
if err = c.packets.ReadEOF(); err != nil {
return nil, err
}
}
}
var rows Rows
switch mode {
case TextRowMode:
textRows := NewTextRows(c)
textRows.rowsAffected = ok.AffectedRows
textRows.insertID = ok.LastInsertID
textRows.fields = columns
rows = textRows
case BinaryRowMode:
binRows := NewBinaryRows(c)
binRows.rowsAffected = ok.AffectedRows
binRows.insertID = ok.LastInsertID
binRows.fields = columns
rows = binRows
}
return rows, nil
}
func (c *conn) comQuery(command byte, datas []byte) (Rows, error) {
return c.baseQuery(TextRowMode, command, datas)
}
func (c *conn) stmtQuery(command byte, datas []byte) (Rows, error) {
return c.baseQuery(BinaryRowMode, command, datas)
}
// ConnectionID is the connection id at greeting
func (c *conn) ConnectionID() uint32 {
return c.greeting.ConnectionID
}
// Query execute the query and return the row iterator
func (c *conn) Query(sql string) (Rows, error) {
return c.comQuery(sqldb.COM_QUERY, common.StringToBytes(sql))
}
// Ping -- ping command.
func (c *conn) Ping() error {
rows, err := c.comQuery(sqldb.COM_PING, []byte{})
if err != nil {
return err
}
return rows.Close()
}
// InitDB -- Init DB command.
func (c *conn) InitDB(db string) error {
rows, err := c.comQuery(sqldb.COM_INIT_DB, common.StringToBytes(db))
if err != nil {
return err
}
return rows.Close()
}
// Exec executes the query and drain the results
func (c *conn) Exec(sql string) error {
rows, err := c.comQuery(sqldb.COM_QUERY, common.StringToBytes(sql))
if err != nil {
return err
}
if err := rows.Close(); err != nil {
c.Cleanup()
}
return nil
}
// FetchAll -- fetch all command.
func (c *conn) FetchAll(sql string, maxrows int) (*sqltypes.Result, error) {
return c.FetchAllWithFunc(sql, maxrows, func(rows Rows) error { return nil })
}
// Func calls on every rows.Next.
// If func returns error, the row.Next() is interrupted and the error is return.
type Func func(rows Rows) error
func (c *conn) FetchAllWithFunc(sql string, maxrows int, fn Func) (*sqltypes.Result, error) {
var err error
var iRows Rows
var qrRow []sqltypes.Value
var qrRows [][]sqltypes.Value
if iRows, err = c.comQuery(sqldb.COM_QUERY, common.StringToBytes(sql)); err != nil {
return nil, err
}
for iRows.Next() {
// callback check.
if err = fn(iRows); err != nil {
break
}
// Max rows check.
if len(qrRows) == maxrows {
break
}
if qrRow, err = iRows.RowValues(); err != nil {
c.Cleanup()
return nil, err
}
if qrRow != nil {
qrRows = append(qrRows, qrRow)
}
}
// Drain the results and check last error.
if err := iRows.Close(); err != nil {
c.Cleanup()
return nil, err
}
rowsAffected := iRows.RowsAffected()
if rowsAffected == 0 {
rowsAffected = uint64(len(qrRows))
}
qr := &sqltypes.Result{
Fields: iRows.Fields(),
RowsAffected: rowsAffected,
InsertID: iRows.LastInsertID(),
Rows: qrRows,
}
return qr, err
}
// ComStatementPrepare -- statement prepare command.
func (c *conn) ComStatementPrepare(sql string) (*Statement, error) {
if err := c.packets.WriteCommand(sqldb.COM_STMT_PREPARE, common.StringToBytes(sql)); err != nil {
return nil, err
}
stmt, err := c.packets.ReadStatementPrepareResponse(c.greeting.Capability)
if err != nil {
return nil, err
}
return &Statement{
conn: c,
ID: stmt.ID,
ColumnNames: stmt.ColumnNames,
}, nil
}
// Command -- execute a command.
func (c *conn) Command(command byte) error {
rows, err := c.comQuery(command, []byte{})
if err != nil {
return err
}
if err := rows.Close(); err != nil {
c.Cleanup()
}
return nil
}
// Quit -- quite command.
func (c *conn) Quit() {
c.packets.WriteCommand(sqldb.COM_QUIT, nil)
}
// Cleanup -- cleanup connection.
func (c *conn) Cleanup() {
if c.netConn != nil {
c.netConn.Close()
c.netConn = nil
}
}
// Close closes the connection
func (c *conn) Close() error {
if c != nil && c.netConn != nil {
quitCh := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
defer cancel()
// First to send quit, if quit timeout force to do cleanup.
go func(c *conn) {
c.Quit()
close(quitCh)
}(c)
select {
case <-ctx.Done():
c.Cleanup()
case <-quitCh:
c.Cleanup()
}
}
return nil
}
// Closed checks the connection broken or not
func (c *conn) Closed() bool {
return c.netConn == nil
}