forked from go-sql-driver/mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
90 lines (77 loc) · 1.94 KB
/
driver.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
// Copyright 2012 Julien Schmidt. All rights reserved.
// http://www.julienschmidt.com
//
// 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/.
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
package mysql
import (
"database/sql"
"database/sql/driver"
"net"
"time"
)
type mysqlDriver struct{}
// Open new Connection.
// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
// the DSN string is formated
func (d *mysqlDriver) Open(dsn string) (driver.Conn, error) {
var err error
// New mysqlConn
mc := &mysqlConn{
maxPacketAllowed: maxPacketSize,
maxWriteSize: maxPacketSize - 1,
}
mc.cfg, err = parseDSN(dsn)
if err != nil {
return nil, err
}
// Connect to Server
if _, ok := mc.cfg.params["timeout"]; ok { // with timeout
var timeout time.Duration
timeout, err = time.ParseDuration(mc.cfg.params["timeout"])
if err == nil {
mc.netConn, err = net.DialTimeout(mc.cfg.net, mc.cfg.addr, timeout)
}
} else { // no timeout
mc.netConn, err = net.Dial(mc.cfg.net, mc.cfg.addr)
}
if err != nil {
return nil, err
}
mc.buf = newBuffer(mc.netConn)
// Reading Handshake Initialization Packet
err = mc.readInitPacket()
if err != nil {
return nil, err
}
// Send Client Authentication Packet
err = mc.writeAuthPacket()
if err != nil {
return nil, err
}
// Read Result Packet
err = mc.readResultOK()
if err != nil {
return nil, err
}
// Get max allowed packet size
maxap, err := mc.getSystemVar("max_allowed_packet")
if err != nil {
return nil, err
}
mc.maxPacketAllowed = stringToInt(maxap) - 1
if mc.maxPacketAllowed < maxPacketSize {
mc.maxWriteSize = mc.maxPacketAllowed
}
// Handle DSN Params
err = mc.handleParams()
if err != nil {
return nil, err
}
return mc, err
}
func init() {
sql.Register("mysql", &mysqlDriver{})
}