/
client.go
67 lines (62 loc) · 1.37 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 ydbx
import (
"github.com/yandex-cloud/ydb-go-sdk"
"github.com/yandex-cloud/ydb-go-sdk/auth"
"context"
"crypto/tls"
"crypto/x509"
)
type Client struct {
DriverConfig *ydb.DriverConfig
Driver ydb.Driver
credentials ydb.Credentials
table *tableWrapper
}
func (c *Client) Close() {
_ = c.table.Pool().Close(context.Background())
_ = c.Driver.Close()
}
func (c *Client) Table() *tableWrapper {
return c.table
}
// NewClient creates a Client to a database
func NewClient(ctx context.Context, params ConnectParams, opts ...ClientOption) (c *Client, err error) {
c = &Client{}
for _, opt := range opts {
err := opt(c)
if err != nil {
return nil, err
}
}
if c.Driver == nil {
if c.DriverConfig == nil {
c.DriverConfig = &ydb.DriverConfig{}
}
c.DriverConfig.Database = params.Database()
if c.DriverConfig.Credentials == nil {
c.DriverConfig.Credentials, err = auth.FromEnviron(ctx)
if err != nil {
return nil, err
}
}
var tlsConfig *tls.Config
if params.UseTLS() {
roots, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
tlsConfig = &tls.Config{
RootCAs: roots,
}
}
c.Driver, err = (&ydb.Dialer{
DriverConfig: c.DriverConfig,
TLSConfig: tlsConfig,
}).Dial(ctx, params.Endpoint())
if err != nil {
return nil, err
}
}
c.table = newTableWrapper(c.Driver)
return c, nil
}