-
Notifications
You must be signed in to change notification settings - Fork 41
/
connector.go
285 lines (248 loc) · 8.23 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package dbsql
import (
"context"
"crypto/tls"
"database/sql/driver"
"fmt"
"net/http"
"strings"
"time"
"github.com/databricks/databricks-sql-go/auth"
"github.com/databricks/databricks-sql-go/auth/oauth/m2m"
"github.com/databricks/databricks-sql-go/auth/pat"
"github.com/databricks/databricks-sql-go/driverctx"
dbsqlerr "github.com/databricks/databricks-sql-go/errors"
"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"
dbsqlerrint "github.com/databricks/databricks-sql-go/internal/errors"
"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, dbsqlerrint.NewDriverError(ctx, dbsqlerr.ErrThriftClient, err)
}
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, dbsqlerrint.NewRequestError(ctx, fmt.Sprintf("error connecting: host=%s port=%d, httpPath=%s", c.cfg.Host, c.cfg.Port, c.cfg.HTTPPath), err)
}
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, dbsqlerrint.NewExecutionError(ctx, fmt.Sprintf("error setting session param: %s", setStmt), err, nil)
}
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) {
protocol, hostname := parseHostName(host)
if protocol != "" {
c.Protocol = protocol
}
c.Host = hostname
}
}
func parseHostName(host string) (protocol, hostname string) {
hostname = host
if strings.HasPrefix(host, "https") {
hostname = strings.TrimPrefix(host, "https")
protocol = "https"
} else if strings.HasPrefix(host, "http") {
hostname = strings.TrimPrefix(host, "http")
protocol = "http"
}
if protocol != "" {
hostname = strings.TrimPrefix(hostname, ":")
hostname = strings.TrimPrefix(hostname, "//")
}
if hostname == "localhost" && protocol == "" {
protocol = "http"
}
return
}
// 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
}
}
// WithSkipTLSHostVerify disables the verification of the hostname in the TLS certificate.
// WARNING:
// When this option is used, TLS is susceptible to machine-in-the-middle attacks.
// Please only use this option when the hostname is an internal private link hostname
func WithSkipTLSHostVerify() ConnOption {
return func(c *config.Config) {
if c.TLSConfig == nil {
c.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: true} // #nosec G402
} else {
c.TLSConfig.InsecureSkipVerify = true // #nosec G402
}
}
}
// WithAuthenticator sets up the Authentication. Mandatory if access token is not provided.
func WithAuthenticator(authr auth.Authenticator) ConnOption {
return func(c *config.Config) {
c.Authenticator = authr
}
}
// WithTransport sets up the transport configuration to be used by the httpclient.
func WithTransport(t http.RoundTripper) ConnOption {
return func(c *config.Config) {
c.Transport = t
}
}
// WithCloudFetch sets up the use of cloud fetch for query execution. Default is false.
func WithCloudFetch(useCloudFetch bool) ConnOption {
return func(c *config.Config) {
c.UseCloudFetch = useCloudFetch
}
}
// WithMaxDownloadThreads sets up maximum download threads for cloud fetch. Default is 10.
func WithMaxDownloadThreads(numThreads int) ConnOption {
return func(c *config.Config) {
c.MaxDownloadThreads = numThreads
}
}
// Setup of Oauth M2m authentication
func WithClientCredentials(clientID, clientSecret string) ConnOption {
return func(c *config.Config) {
if clientID != "" && clientSecret != "" {
authr := m2m.NewAuthenticator(clientID, clientSecret, c.Host)
c.Authenticator = authr
}
}
}