-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
107 lines (88 loc) · 1.91 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
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
105
106
107
package psql
import (
"database/sql"
"github.com/Pheethy/sqlx"
pg "github.com/lib/pq"
"github.com/opentracing/opentracing-go"
"github.com/qustavo/sqlhooks/v2"
)
type Client struct {
db *sqlx.DB
connectionURI string
driverName string
tracer opentracing.Tracer
}
func NewPsqlConnection(connectionStr string) (*Client, error) {
addr, err := pg.ParseURL(connectionStr)
if err != nil {
return nil, err
}
db, err := sqlx.Connect(postgres_driver, addr)
if err != nil {
return nil, err
}
return &Client{
db: db,
connectionURI: connectionStr,
driverName: postgres_driver,
}, nil
}
func NewPsqlWithTracingConnection(connectionStr string, tracing opentracing.Tracer) (client *Client, err error) {
addr, err := pg.ParseURL(connectionStr)
if err != nil {
return nil, err
}
if !isRegisterOTPG {
sql.Register(opentracing_driver, sqlhooks.Wrap(&pg.Driver{}, NewTracingHook(tracing)))
}
db, err := sqlx.Connect(opentracing_driver, addr)
if err != nil {
return nil, err
}
isRegisterOTPG = true
return &Client{
db: db,
connectionURI: connectionStr,
driverName: opentracing_driver,
tracer: tracing,
}, nil
}
func (c *Client) GetClient() *sqlx.DB {
return c.db
}
func (c *Client) GetConnectionURI() string {
return c.connectionURI
}
func (c *Client) SetDB(db *sqlx.DB) {
c.db = db
}
func (c *Client) IsConnect() bool {
if err := c.db.Ping(); err == nil {
return true
}
return false
}
func (c *Client) Reconnect() error {
if c.IsConnect() {
return nil
}
switch c.driverName {
case postgres_driver:
client, err := NewPsqlConnection(c.connectionURI)
if err != nil {
return err
}
c.db = client.GetClient()
case opentracing_driver:
addr, err := pg.ParseURL(c.connectionURI)
if err != nil {
return err
}
db, err := sqlx.Connect(opentracing_driver, addr)
if err != nil {
return err
}
c.db = db
}
return nil
}