Skip to content

Commit a19c218

Browse files
committed
add an optional connecton timeout
1 parent 7f86f42 commit a19c218

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ For Unix-sockets the address is the absolute path to the MySQL-Server-socket, e.
100100
**Parameters are case-sensitive!**
101101

102102
Possible Parameters are:
103+
* `timeout`: **Driver** side connection timeout. The value must be a string of decimal numbers, each with optional fraction and a unit suffix ( *"ms"*, *"s"*, *"m"*, *"h"* ), such as *"30s"*, *"0.5m"* or *"1m30s"*. To set a server side timeout, use the parameter [`wait_timeout`](http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_wait_timeout).
103104
* `charset`: *"SET NAMES `value`"*. If multiple charsets are set (seperated by a comma), the following charset is used if setting the charset failes. This enables support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers.
104105
* _(pending)_ <s>`tls`</s>: will enable SSL/TLS-Encryption
105106
* _(pending)_ <s>`compress`</s>: will enable Compression

connection.go

+4
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ func (mc *mysqlConn) handleParams() (err error) {
5252
}
5353
}
5454

55+
// Timeout - already handled on connecting
56+
case "timeout":
57+
continue
58+
5559
// TLS-Encryption
5660
case "tls":
5761
err = errors.New("TLS-Encryption not implemented yet")

driver.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"database/sql"
1313
"database/sql/driver"
1414
"net"
15+
"time"
1516
)
1617

1718
type mysqlDriver struct{}
@@ -27,7 +28,15 @@ func (d *mysqlDriver) Open(dsn string) (driver.Conn, error) {
2728
mc.cfg = parseDSN(dsn)
2829

2930
// Connect to Server
30-
mc.netConn, err = net.Dial(mc.cfg.net, mc.cfg.addr)
31+
if _, ok := mc.cfg.params["timeout"]; ok { // with timeout
32+
var timeout time.Duration
33+
timeout, err = time.ParseDuration(mc.cfg.params["timeout"])
34+
if err == nil {
35+
mc.netConn, err = net.DialTimeout(mc.cfg.net, mc.cfg.addr, timeout)
36+
}
37+
} else { // no timeout
38+
mc.netConn, err = net.Dial(mc.cfg.net, mc.cfg.addr)
39+
}
3140
if err != nil {
3241
return nil, err
3342
}

driver_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func getEnv() bool {
4242
}
4343

4444
netAddr = fmt.Sprintf("%s(%s)", prot, addr)
45-
dsn = fmt.Sprintf("%s:%s@%s/%s?charset=utf8", user, pass, netAddr, dbname)
45+
dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&charset=utf8", user, pass, netAddr, dbname)
4646

4747
c, err := net.Dial(prot, addr)
4848
if err == nil {

0 commit comments

Comments
 (0)