-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
104 lines (83 loc) · 1.93 KB
/
client.go
File metadata and controls
104 lines (83 loc) · 1.93 KB
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
104
package dbcl
import (
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
const (
maxIdleConns = 20
maxOpenConns = 35
maxIdleTime = time.Minute * 5
maxLifetime = time.Minute * 30
defaultQs = "?multiStatements=true&parseTime=true&loc=UTC"
)
type Client struct {
readClient *sqlx.DB
writeClient *sqlx.DB
migrations map[string]string
}
func (c *Client) Reader() *sqlx.DB {
return c.readClient
}
func (c *Client) Writer() *sqlx.DB {
return c.writeClient
}
func (c *Client) Ping() error {
err := c.readClient.Ping()
if err != nil {
return fmt.Errorf("failed on read ping: %w", err)
}
err = c.writeClient.Ping()
if err != nil {
return fmt.Errorf("failed on write ping: %w", err)
}
return nil
}
func (c *Client) Begin() (*Tx, error) {
tx, err := c.writeClient.Beginx()
if err != nil {
return nil, err
}
return NewTx(tx), nil
}
func (c *Client) Close() {
c.readClient.Close()
c.writeClient.Close()
}
func initConnection(dsn string) (*sqlx.DB, error) {
client, err := sqlx.Connect("mysql", dsn)
if err != nil {
return nil, err
}
client.DB.SetMaxIdleConns(maxIdleConns)
client.DB.SetMaxOpenConns(maxOpenConns)
client.DB.SetConnMaxIdleTime(maxIdleTime)
client.DB.SetConnMaxLifetime(maxLifetime)
return client, nil
}
func New(
writeHost, readHost, port, name, user, pass string,
migrations map[string]string,
) (*Client, error) {
readDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s%s", user, pass, readHost, port, name, defaultQs)
readClient, err := initConnection(readDSN)
if err != nil {
return nil, err
}
writeDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s%s", user, pass, writeHost, port, name, defaultQs)
writeClient, err := initConnection(writeDSN)
if err != nil {
return nil, err
}
client := &Client{
readClient: readClient,
writeClient: writeClient,
migrations: migrations,
}
if err := client.Ping(); err != nil {
client.Close()
return nil, err
}
return client, nil
}