-
Notifications
You must be signed in to change notification settings - Fork 12
/
conn.go
325 lines (269 loc) · 6.9 KB
/
conn.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
// The MIT License (MIT)
// Copyright (c) 2016 Jerry Bai
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package mysql
import (
"fmt"
"net"
"strings"
"github.com/berkaroad/saashard/backend"
"github.com/berkaroad/saashard/net/mysql"
)
func init() {
backend.CreateConnection = func(dbHost *backend.DBHost) backend.Connection {
return new(Conn)
}
}
// Conn proxy <-> mysql server
type Conn struct {
conn net.Conn
pkg *mysql.PacketIO
dbHost *backend.DBHost
db string
connectionID uint32
capability uint32
status uint16
collation mysql.CollationID
charset string
salt []byte
}
// GetConnectionID get connection id
func (c *Conn) GetConnectionID() uint32 {
return c.connectionID
}
// SetConnectionID set connection id
func (c *Conn) SetConnectionID(id uint32) { c.connectionID = id }
// Connect to mysql
func (c *Conn) Connect(dbHost *backend.DBHost, db string) error {
c.dbHost = dbHost
c.db = db
//use utf8
c.collation = mysql.DEFAULT_COLLATION_ID
c.charset = mysql.DEFAULT_CHARSET
return c.Reconnect()
}
// Reconnect reconnect to mysql.
func (c *Conn) Reconnect() error {
var needReconnect = true
if c.conn != nil {
if err := c.Ping(); err == nil {
needReconnect = false
} else {
c.Close()
}
}
if needReconnect {
n := "tcp"
if strings.Contains(c.dbHost.Addr, "/") {
n = "unix"
}
netConn, err := net.Dial(n, c.dbHost.Addr)
if err != nil {
return err
}
if tcpConn, ok := netConn.(*net.TCPConn); ok {
//SetNoDelay controls whether the operating system should delay packet transmission
// in hopes of sending fewer packets (Nagle's algorithm).
// The default is true (no delay),
// meaning that data is sent as soon as possible after a Write.
//I set this option false.
tcpConn.SetNoDelay(false)
tcpConn.SetKeepAlive(true)
}
c.conn = netConn
c.pkg = mysql.NewPacketIO(netConn)
if c.capability, c.status, c.collation, err = c.pkg.ReadInitialHandshake(&(c.salt)); err != nil {
c.conn.Close()
c.conn = nil
return err
}
if err := c.pkg.WriteAuthHandshake(&(c.capability), c.dbHost.User, c.dbHost.Password, c.db, c.salt, c.collation); err != nil {
c.conn.Close()
c.conn = nil
return err
}
if _, err := c.pkg.ReadOK(c.capability, &(c.status)); err != nil {
c.conn.Close()
c.conn = nil
return err
}
}
c.pkg.Sequence = 0
//we must always use autocommit
if !c.IsAutoCommit() {
if _, err := c.pkg.Query(c.capability, &(c.status), "set autocommit = 1"); err != nil {
c.conn.Close()
return err
}
}
return nil
}
// Close conn
func (c *Conn) Close() error {
if !c.IsClosed() {
c.pkg.Quit(c.capability, &(c.status))
c.conn.Close()
c.conn = nil
c.salt = nil
c.pkg = nil
}
return nil
}
// ReturnConnection give back connection.
func (c *Conn) ReturnConnection() {
if c.dbHost != nil {
c.dbHost.Pool.ReturnConnection(c)
}
}
// Ping db
func (c *Conn) Ping() error {
if c.IsClosed() {
c.Reconnect()
}
return c.pkg.Ping(c.capability, &(c.status))
}
// UseDB use db.
func (c *Conn) UseDB(dbName string) error {
if c.IsClosed() {
c.Reconnect()
}
if c.db == dbName || len(dbName) == 0 {
return nil
}
if err := c.pkg.InitDB(c.capability, &(c.status), dbName); err != nil {
return err
}
c.db = dbName
return nil
}
// GetDB get db.
func (c *Conn) GetDB() string {
return c.db
}
// GetAddr get addr.
func (c *Conn) GetAddr() string {
return c.dbHost.Addr
}
// IsClosed check connection status
func (c *Conn) IsClosed() bool {
return c.conn == nil || c.pkg == nil
}
// Query command.
func (c *Conn) Query(query string) (*mysql.Result, error) {
if c.IsClosed() {
c.Reconnect()
}
return c.pkg.Query(c.capability, &(c.status), query)
}
// FieldList return field list.
func (c *Conn) FieldList(table string, wildcard string) ([]*mysql.Field, error) {
if c.IsClosed() {
c.Reconnect()
}
return c.pkg.FieldList(c.capability, table, wildcard)
}
// Execute command.
func (c *Conn) Execute(command string, args []interface{}) (*mysql.Result, error) {
if c.IsClosed() {
c.Reconnect()
}
if len(args) == 0 {
return c.pkg.Query(c.capability, &(c.status), command)
}
s, err := c.Prepare(command)
if err != nil {
return nil, err
}
var r *mysql.Result
r, err = s.Execute(args)
s.Close()
return r, err
}
// Prepare stmt.
func (c *Conn) Prepare(query string) (*mysql.Stmt, error) {
if c.IsClosed() {
c.Reconnect()
}
var err error
stmt := mysql.NewStmt(c.pkg, c.capability, &c.status)
stmt.Query = query
if err = c.pkg.StmtPrepare(c.capability, stmt); err != nil {
return nil, err
}
return stmt, nil
}
// Begin Tx
func (c *Conn) Begin() error {
_, err := c.Query("begin")
return err
}
// Commit Tx
func (c *Conn) Commit() error {
_, err := c.Query("commit")
return err
}
// Rollback Tx
func (c *Conn) Rollback() error {
_, err := c.Query("rollback")
return err
}
// SetCharset set charset
func (c *Conn) SetCharset(charset string) error {
if c.IsClosed() {
c.Reconnect()
}
charset = strings.Trim(charset, "\"'`")
if c.charset == charset {
return nil
}
cid, ok := mysql.CharsetIds[charset]
if !ok {
return fmt.Errorf("invalid charset %s", charset)
}
if _, err := c.pkg.Query(c.capability, &(c.status), fmt.Sprintf("set names %s", charset)); err != nil {
return err
}
c.collation = cid
c.charset = charset
return nil
}
// GetCharset get charset.
func (c *Conn) GetCharset() string {
return c.charset
}
// SetAutoCommit set autocommit.
func (c *Conn) SetAutoCommit(autocommit bool) error {
if c.IsClosed() {
c.Reconnect()
}
strAutoCommit := "0"
if autocommit {
strAutoCommit = "1"
}
if _, err := c.pkg.Query(c.capability, &(c.status), fmt.Sprintf("set autocommit %s", strAutoCommit)); err != nil {
return err
}
return nil
}
// IsAutoCommit status.
func (c *Conn) IsAutoCommit() bool {
return c.status&mysql.SERVER_STATUS_AUTOCOMMIT > 0
}
// IsInTransaction status.
func (c *Conn) IsInTransaction() bool {
return c.status&mysql.SERVER_STATUS_IN_TRANS > 0
}