-
Notifications
You must be signed in to change notification settings - Fork 9
/
db_client.go
73 lines (59 loc) · 1.71 KB
/
db_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
package db_client
import (
"context"
"database/sql"
"github.com/spf13/viper"
"github.com/turbot/pipe-fittings/constants"
"github.com/turbot/pipe-fittings/backend"
"github.com/turbot/pipe-fittings/utils"
)
// DbClient wraps over `sql.DB` and gives an interface to the database
type DbClient struct {
connectionString string
// db handle
db *sql.DB
// the Backend
Backend backend.Backend
}
func NewDbClient(ctx context.Context, connectionString string, opts ...backend.ConnectOption) (_ *DbClient, err error) {
utils.LogTime("db_client.NewDbClient start")
defer utils.LogTime("db_client.NewDbClient end")
b, err := backend.FromConnectionString(ctx, connectionString)
if err != nil {
return nil, err
}
client := &DbClient{
connectionString: connectionString,
Backend: b,
}
defer func() {
if err != nil {
// try closing the client
_ = client.Close(ctx)
}
}()
// process options - searhc path may have been passed in
config := backend.NewConnectConfig(opts)
config.MaxOpenConns = MaxDbConnections()
// if no search path override passed in as an option, use the viper config
if config.SearchPathConfig.Empty() {
config.SearchPathConfig = backend.SearchPathConfig{
SearchPath: viper.GetStringSlice(constants.ArgSearchPath),
SearchPathPrefix: viper.GetStringSlice(constants.ArgSearchPathPrefix),
}
}
if err := client.connect(ctx, backend.WithConfig(config)); err != nil {
return nil, err
}
return client, nil
}
func (c *DbClient) GetConnectionString() string {
return c.connectionString
}
// Close closes the connection to the database and shuts down the Backend
func (c *DbClient) Close(context.Context) error {
if c.db != nil {
return c.db.Close()
}
return nil
}