-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdriver.go
66 lines (57 loc) · 1.9 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
package pqtimeouts
import (
"database/sql"
"database/sql/driver"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/lib/pq"
)
func init() {
sql.Register("pq-timeouts", timeoutDriver{dialOpen: pq.DialOpen})
}
type timeoutDriver struct {
dialOpen func(pq.Dialer, string) (driver.Conn, error) // Allow this to be stubbed for testing
}
func (t timeoutDriver) Open(connection string) (_ driver.Conn, err error) {
// Look for read_timeout and write_timeout in the connection string and extract the values.
// read_timeout and write_timeout need to be removed from the connection string before calling pq as well.
var newConnectionSettings []string
var readTimeout time.Duration
var writeTimeout time.Duration
// If the connection is specified as a URL, use the parsing function in lib/pq to turn it into options.
if strings.HasPrefix(connection, "postgres://") || strings.HasPrefix(connection, "postgresql://") {
connection, err = pq.ParseURL(connection)
if err != nil {
return nil, err
}
}
for _, setting := range strings.Fields(connection) {
s := strings.Split(setting, "=")
if s[0] == "read_timeout" {
val, err := strconv.Atoi(s[1])
if err != nil {
return nil, fmt.Errorf("Error interpreting value for read_timeout")
}
readTimeout = time.Duration(val) * time.Millisecond // timeout is in milliseconds
} else if s[0] == "write_timeout" {
val, err := strconv.Atoi(s[1])
if err != nil {
return nil, fmt.Errorf("Error interpreting value for write_timeout")
}
writeTimeout = time.Duration(val) * time.Millisecond // timeout is in milliseconds
} else {
newConnectionSettings = append(newConnectionSettings, setting)
}
}
newConnectionStr := strings.Join(newConnectionSettings, " ")
return t.dialOpen(
timeoutDialer{
netDial: net.Dial,
netDialTimeout: net.DialTimeout,
readTimeout: readTimeout,
writeTimeout: writeTimeout},
newConnectionStr)
}