-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
67 lines (59 loc) · 1.09 KB
/
client.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
package mysqlclient
import (
"database/sql"
"errors"
_ "github.com/go-sql-driver/mysql"
"sync"
"time"
)
var (
CheckConfigNilError = errors.New("check config nil")
CheckDBPoolError = errors.New("check db pool nil")
)
type MysqlClient struct {
config *Config
mu sync.Mutex
}
func NewMysqlClient(opts ...Option) (*MysqlClient, error) {
//default
config := &Config{
ddlPath: "",
flyway: false,
timeout: 10 * time.Second,
}
for _, opt := range opts {
opt(config)
}
mc := &MysqlClient{
config: config,
}
mc.mu.Lock()
defer mc.mu.Unlock()
err := mc.validate()
if err != nil {
return nil, err
}
err = mc.initialFlayway()
if err != nil {
return nil, err
}
return mc, nil
}
func (mc *MysqlClient) validate() error {
if mc.config == nil {
return CheckConfigNilError
}
if mc.config.pool == nil {
return CheckDBPoolError
}
return mc.Ping()
}
func (mc *MysqlClient) Ping() error {
return mc.GetDB().Ping()
}
func (mc *MysqlClient) GetDB() *sql.DB {
return mc.config.pool
}
func (mc *MysqlClient) GetTransaction() (*sql.Tx, error) {
return mc.GetDB().Begin()
}