forked from databricks/databricks-sql-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.go
207 lines (179 loc) · 5.75 KB
/
connector.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package dbsql
import (
"context"
"database/sql/driver"
"fmt"
"net/http"
"strings"
"time"
"github.com/databricks/databricks-sql-go/auth/pat"
"github.com/databricks/databricks-sql-go/driverctx"
"github.com/databricks/databricks-sql-go/internal/cli_service"
"github.com/databricks/databricks-sql-go/internal/client"
"github.com/databricks/databricks-sql-go/internal/config"
dbsqlerr "github.com/databricks/databricks-sql-go/internal/err"
"github.com/databricks/databricks-sql-go/logger"
)
type connector struct {
cfg *config.Config
client *http.Client
}
// Connect returns a connection to the Databricks database from a connection pool.
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
var catalogName *cli_service.TIdentifier
var schemaName *cli_service.TIdentifier
if c.cfg.Catalog != "" {
catalogName = cli_service.TIdentifierPtr(cli_service.TIdentifier(c.cfg.Catalog))
}
if c.cfg.Schema != "" {
schemaName = cli_service.TIdentifierPtr(cli_service.TIdentifier(c.cfg.Schema))
}
tclient, err := client.InitThriftClient(c.cfg, c.client)
if err != nil {
return nil, dbsqlerr.WrapErr(err, "error initializing thrift client")
}
protocolVersion := int64(c.cfg.ThriftProtocolVersion)
session, err := tclient.OpenSession(ctx, &cli_service.TOpenSessionReq{
ClientProtocolI64: &protocolVersion,
Configuration: make(map[string]string),
InitialNamespace: &cli_service.TNamespace{
CatalogName: catalogName,
SchemaName: schemaName,
},
CanUseMultipleCatalogs: &c.cfg.CanUseMultipleCatalogs,
})
if err != nil {
return nil, dbsqlerr.WrapErrf(err, "error connecting: host=%s port=%d, httpPath=%s", c.cfg.Host, c.cfg.Port, c.cfg.HTTPPath)
}
conn := &conn{
id: client.SprintGuid(session.SessionHandle.GetSessionId().GUID),
cfg: c.cfg,
client: tclient,
session: session,
}
log := logger.WithContext(conn.id, driverctx.CorrelationIdFromContext(ctx), "")
log.Info().Msgf("connect: host=%s port=%d httpPath=%s", c.cfg.Host, c.cfg.Port, c.cfg.HTTPPath)
for k, v := range c.cfg.SessionParams {
setStmt := fmt.Sprintf("SET `%s` = `%s`;", k, v)
_, err := conn.ExecContext(ctx, setStmt, []driver.NamedValue{})
if err != nil {
return nil, err
}
log.Info().Msgf("set session parameter: param=%s value=%s", k, v)
}
return conn, nil
}
// Driver returns underlying databricksDriver for compatibility with sql.DB Driver method
func (c *connector) Driver() driver.Driver {
return &databricksDriver{}
}
var _ driver.Connector = (*connector)(nil)
type connOption func(*config.Config)
// NewConnector creates a connection that can be used with `sql.OpenDB()`.
// This is an easier way to set up the DB instead of having to construct a DSN string.
func NewConnector(options ...connOption) (driver.Connector, error) {
// config with default options
cfg := config.WithDefaults()
cfg.DriverVersion = DriverVersion
for _, opt := range options {
opt(cfg)
}
client := client.RetryableClient(cfg)
return &connector{cfg: cfg, client: client}, nil
}
func withUserConfig(ucfg config.UserConfig) connOption {
return func(c *config.Config) {
c.UserConfig = ucfg
}
}
// WithServerHostname sets up the server hostname. Mandatory.
func WithServerHostname(host string) connOption {
return func(c *config.Config) {
if host == "localhost" {
c.Protocol = "http"
}
c.Host = host
}
}
// WithPort sets up the server port. Mandatory.
func WithPort(port int) connOption {
return func(c *config.Config) {
c.Port = port
}
}
// WithRetries sets up retrying logic. Sane defaults are provided. Negative retryMax will disable retry behavior
// By default retryWaitMin = 1 * time.Second
// By default retryWaitMax = 30 * time.Second
// By default retryMax = 4
func WithRetries(retryMax int, retryWaitMin time.Duration, retryWaitMax time.Duration) connOption {
return func(c *config.Config) {
c.RetryWaitMax = retryWaitMax
c.RetryWaitMin = retryWaitMin
c.RetryMax = retryMax
}
}
// WithAccessToken sets up the Personal Access Token. Mandatory for now.
func WithAccessToken(token string) connOption {
return func(c *config.Config) {
if token != "" {
c.AccessToken = token
pat := &pat.PATAuth{
AccessToken: token,
}
c.Authenticator = pat
}
}
}
// WithHTTPPath sets up the endpoint to the warehouse. Mandatory.
func WithHTTPPath(path string) connOption {
return func(c *config.Config) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
c.HTTPPath = path
}
}
// WithMaxRows sets up the max rows fetched per request. Default is 10000
func WithMaxRows(n int) connOption {
return func(c *config.Config) {
if n != 0 {
c.MaxRows = n
}
}
}
// WithTimeout adds timeout for the server query execution. Default is no timeout.
func WithTimeout(n time.Duration) connOption {
return func(c *config.Config) {
c.QueryTimeout = n
}
}
// Sets the initial catalog name and schema name in the session.
// Use <select * from foo> instead of <select * from catalog.schema.foo>
func WithInitialNamespace(catalog, schema string) connOption {
return func(c *config.Config) {
c.Catalog = catalog
c.Schema = schema
}
}
// Used to identify partners. Set as a string with format <isv-name+product-name>.
func WithUserAgentEntry(entry string) connOption {
return func(c *config.Config) {
c.UserAgentEntry = entry
}
}
// Sessions params will be set upon opening the session by calling SET function.
// If using connection pool, session params can avoid successive calls of "SET ..."
func WithSessionParams(params map[string]string) connOption {
return func(c *config.Config) {
for k, v := range params {
if strings.ToLower(k) == "timezone" {
if loc, err := time.LoadLocation(v); err != nil {
logger.Error().Msgf("timezone %s is not valid", v)
} else {
c.Location = loc
}
}
}
c.SessionParams = params
}
}