-
Notifications
You must be signed in to change notification settings - Fork 3
/
mysql.go
94 lines (86 loc) · 2.33 KB
/
mysql.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
package data_store
import (
"database/sql"
"log"
"sync"
"time"
"github.com/go-sql-driver/mysql"
"github.com/shyyawn/go-to/x/source"
"github.com/spf13/viper"
)
type Mysql struct {
db *sql.DB
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Net string `mapstructure:"net"`
Addr string `mapstructure:"addr"`
DBName string `mapstructure:"db_name"`
AllowNativePasswords bool `mapstructure:"allow_native_passwords"`
Timeout int `json:"timeout"`
ReadTimeout int `json:"read_timeout"`
WriteTimeout int `json:"write_timeout"`
MaxOpenConns int `json:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns"`
ConnMaxLifetime int `json:"conn_max_lifetime"`
lock sync.RWMutex
}
func (ds *Mysql) LoadFromConfig(key string, config *viper.Viper) error {
err := source.LoadFromConfig(key, config, ds)
//Defaults
if ds.Timeout == 0 {
ds.Timeout = 5
}
if ds.ReadTimeout == 0 {
ds.ReadTimeout = 60
}
if ds.WriteTimeout == 0 {
ds.WriteTimeout = 60
}
if ds.MaxOpenConns == 0 {
ds.MaxOpenConns = 5
}
if ds.MaxIdleConns == 0 {
ds.MaxIdleConns = 5
}
if ds.ConnMaxLifetime == 0 {
ds.ConnMaxLifetime = 5
}
return err
}
func (ds *Mysql) Db() *sql.DB {
// if the db object is already created
if ds.db != nil {
// check ping
if pingErr := ds.db.Ping(); pingErr == nil {
return ds.db
}
}
defer ds.lock.Unlock()
ds.lock.Lock()
cfg := mysql.Config{
User: ds.User,
Passwd: ds.Password,
Net: ds.Net,
Addr: ds.Addr,
DBName: ds.DBName,
Timeout: time.Duration(ds.Timeout) * time.Second,
ReadTimeout: time.Duration(ds.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(ds.WriteTimeout) * time.Second,
AllowNativePasswords: ds.AllowNativePasswords,
}
var err error
ds.db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Fatalln(err)
}
if ds.MaxOpenConns != 0 {
ds.db.SetMaxOpenConns(ds.MaxOpenConns)
}
if ds.MaxIdleConns != 0 {
ds.db.SetMaxIdleConns(ds.MaxIdleConns)
}
if ds.ConnMaxLifetime != 0 {
ds.db.SetConnMaxLifetime(time.Minute * time.Duration(ds.ConnMaxLifetime))
}
return ds.db
}