forked from ngaut/sqltop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
103 lines (90 loc) · 1.72 KB
/
db.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
package main
import (
"database/sql"
"fmt"
"time"
)
type DataSource struct {
db *sql.DB
dsn string
user, pwd, host string
port int
}
const (
MaxRetryNum = 10
)
var (
globalDS *DataSource
)
func newDataSource(user, pwd, host string, port int) *DataSource {
return &DataSource{
user: user,
pwd: pwd,
host: host,
port: port,
}
}
func InitDB() error {
cfg := Config()
globalDS = newDataSource(cfg.DBUser, cfg.DBPwd, cfg.Host, cfg.Port)
if err := globalDS.Connect(); err != nil {
return err
}
return globalDS.Ping()
}
func DB() *DataSource {
return globalDS
}
func (ds *DataSource) Ping() error {
if ds.db == nil {
err := ds.Connect()
if err != nil {
cleanExit(err)
}
}
return ds.db.Ping()
}
func (ds *DataSource) Close() {
if ds.db != nil {
if err := ds.db.Close(); err != nil {
cleanExit(err)
}
ds.db = nil
}
}
func (ds *DataSource) Connect() error {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/INFORMATION_SCHEMA", ds.user, ds.pwd, ds.host, ds.port)
var err error
ds.db, err = sql.Open("mysql", dsn)
ds.db.SetMaxIdleConns(10)
ds.db.SetMaxOpenConns(10)
if err != nil {
return err
}
return nil
}
// make sure call Connect() before calling Query()
func (ds *DataSource) Query(query string, args ...interface{}) (*sql.Rows, error) {
var err error
var ret *sql.Rows
if ds.db == nil {
err := ds.Connect()
if err != nil {
cleanExit(err)
}
}
for i := 0; i < MaxRetryNum; i++ {
ret, err = ds.db.Query(query, args...)
if err != nil {
time.Sleep(500 * time.Millisecond)
ds.db.Close()
if err := ds.Connect(); err != nil {
return nil, err
}
} else {
return ret, nil
}
}
// excees max retry, but still got error
return nil, err
}