forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdsn.go
447 lines (422 loc) · 10.9 KB
/
dsn.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright (c) 2017-2018 Snowflake Computing Inc. All right reserved.
package gosnowflake
import (
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
const (
defaultLoginTimeout = 60 * time.Second
defaultRequestTimeout = 0 * time.Second
defaultAuthenticator = "snowflake"
defaultDomain = ".snowflakecomputing.com"
)
// Config is a set of configuration parameters
type Config struct {
Account string // Account name
User string // Username
Password string // Password (requires User)
Database string // Database name
Schema string // Schema
Warehouse string // Warehouse
Role string // Role
Region string // Region
Params map[string]*string // other connection parameters
Protocol string // http or https (optional)
Host string // hostname (optional)
Port int // port (optional)
Authenticator string // snowflake, okta URL, oauth or externalbrowser
Passcode string
PasscodeInPassword bool
LoginTimeout time.Duration // Login timeout
RequestTimeout time.Duration // request timeout
Application string // application name.
InsecureMode bool // driver doesn't check certificate revocation status
Token string // Token to use for OAuth / JWT / other forms of token based auth
}
// DSN constructs a DSN for Snowflake db.
func DSN(cfg *Config) (dsn string, err error) {
hasHost := true
if cfg.Host == "" {
hasHost = false
if cfg.Region == "" {
cfg.Host = cfg.Account + defaultDomain
} else {
cfg.Host = cfg.Account + "." + cfg.Region + defaultDomain
}
}
// in case account includes region
posDot := strings.Index(cfg.Account, ".")
if posDot > 0 {
cfg.Region = cfg.Account[posDot+1:]
cfg.Account = cfg.Account[:posDot]
}
err = fillMissingConfigParameters(cfg)
if err != nil {
return "", err
}
params := &url.Values{}
if hasHost && cfg.Account != "" {
// account may not be included in a Host string
params.Add("account", cfg.Account)
}
if cfg.Database != "" {
params.Add("database", cfg.Database)
}
if cfg.Schema != "" {
params.Add("schema", cfg.Schema)
}
if cfg.Warehouse != "" {
params.Add("warehouse", cfg.Warehouse)
}
if cfg.Role != "" {
params.Add("role", cfg.Role)
}
if cfg.Region != "" {
params.Add("region", cfg.Region)
}
if cfg.Authenticator != defaultAuthenticator {
params.Add("authenticator", strings.ToLower(cfg.Authenticator))
}
if cfg.Passcode != "" {
params.Add("passcode", cfg.Passcode)
}
if cfg.PasscodeInPassword {
params.Add("passcodeInPassword", strconv.FormatBool(cfg.PasscodeInPassword))
}
if cfg.LoginTimeout != defaultLoginTimeout {
params.Add("loginTimeout", strconv.FormatInt(int64(cfg.LoginTimeout/time.Second), 10))
}
if cfg.RequestTimeout != defaultRequestTimeout {
params.Add("requestTimeout", strconv.FormatInt(int64(cfg.RequestTimeout/time.Second), 10))
}
if cfg.Application != clientType {
params.Add("application", cfg.Application)
}
if cfg.Protocol != "" && cfg.Protocol != "https" {
params.Add("protocol", cfg.Protocol)
}
if cfg.Token != "" {
params.Add("token", cfg.Token)
}
if cfg.Params != nil {
for k, v := range cfg.Params {
params.Add(k, *v)
}
}
dsn = fmt.Sprintf("%v:%v@%v:%v", url.QueryEscape(cfg.User), url.QueryEscape(cfg.Password), cfg.Host, cfg.Port)
if params.Encode() != "" {
dsn += "?" + params.Encode()
}
return
}
// ParseDSN parses the DSN string to a Config.
func ParseDSN(dsn string) (cfg *Config, err error) {
// New config with some default values
cfg = &Config{
Params: make(map[string]*string),
}
// user[:password]@account/database/schema[?param1=value1¶mN=valueN]
// or
// user[:password]@account/database[?param1=value1¶mN=valueN]
// or
// user[:password]@host:port/database/schema?account=user_account[?param1=value1¶mN=valueN]
foundSlash := false
secondSlash := false
done := false
var i int
posQuestion := len(dsn)
for i = len(dsn) - 1; i >= 0; i-- {
switch {
case dsn[i] == '/':
foundSlash = true
// left part is empty if i <= 0
var j int
posSecondSlash := i
if i > 0 {
for j = i - 1; j >= 0; j-- {
switch {
case dsn[j] == '/':
// second slash
secondSlash = true
posSecondSlash = j
case dsn[j] == '@':
// username[:password]@...
cfg.User, cfg.Password = parseUserPassword(j, dsn)
}
if dsn[j] == '@' {
break
}
}
// account or host:port
err = parseAccountHostPort(cfg, j, posSecondSlash, dsn)
if err != nil {
return nil, err
}
}
// [?param1=value1&...¶mN=valueN]
// Find the first '?' in dsn[i+1:]
err = parseParams(cfg, i, dsn)
if err != nil {
return
}
if secondSlash {
cfg.Database = dsn[posSecondSlash+1 : i]
cfg.Schema = dsn[i+1 : posQuestion]
} else {
cfg.Database = dsn[posSecondSlash+1 : posQuestion]
}
done = true
case dsn[i] == '?':
posQuestion = i
}
if done {
break
}
}
if !foundSlash {
// no db or schema is specified
var j int
for j = len(dsn) - 1; j >= 0; j-- {
switch {
case dsn[j] == '@':
cfg.User, cfg.Password = parseUserPassword(j, dsn)
case dsn[j] == '?':
posQuestion = j
}
if dsn[j] == '@' {
break
}
}
err = parseAccountHostPort(cfg, j, posQuestion, dsn)
if err != nil {
return nil, err
}
err = parseParams(cfg, posQuestion-1, dsn)
if err != nil {
return
}
}
if cfg.Account == "" && strings.HasSuffix(cfg.Host, defaultDomain) {
posDot := strings.Index(cfg.Host, ".")
if posDot > 0 {
cfg.Account = cfg.Host[:posDot]
}
}
err = fillMissingConfigParameters(cfg)
if err != nil {
return nil, err
}
// unescape parameters
var s string
s, err = url.QueryUnescape(cfg.User)
if err != nil {
return nil, err
}
cfg.User = s
s, err = url.QueryUnescape(cfg.Password)
if err != nil {
return nil, err
}
cfg.Password = s
s, err = url.QueryUnescape(cfg.Database)
if err != nil {
return nil, err
}
cfg.Database = s
s, err = url.QueryUnescape(cfg.Schema)
if err != nil {
return nil, err
}
cfg.Schema = s
s, err = url.QueryUnescape(cfg.Role)
if err != nil {
return nil, err
}
cfg.Role = s
s, err = url.QueryUnescape(cfg.Warehouse)
if err != nil {
return nil, err
}
cfg.Warehouse = s
return cfg, nil
}
func fillMissingConfigParameters(cfg *Config) error {
if strings.Trim(cfg.Authenticator, " ") == "" {
cfg.Authenticator = defaultAuthenticator
}
if strings.Trim(cfg.Account, " ") == "" {
return ErrEmptyAccount
}
if strings.Trim(cfg.User, " ") == "" {
return ErrEmptyUsername
}
authenticator := strings.ToUpper(cfg.Authenticator)
if authenticator != authenticatorExternalBrowser && authenticator != authenticatorOAuth && strings.Trim(cfg.Password, " ") == "" {
// no password parameter is required for EXTERNALBROWSER and OAUTH.
return ErrEmptyPassword
}
if strings.Trim(cfg.Protocol, " ") == "" {
cfg.Protocol = "https"
}
if cfg.Port == 0 {
cfg.Port = 443
}
cfg.Region = strings.Trim(cfg.Region, " ")
if cfg.Region != "" {
// region is specified but not included in Host
i := strings.Index(cfg.Host, defaultDomain)
if i >= 1 {
hostPrefix := cfg.Host[0:i]
if !strings.HasSuffix(hostPrefix, cfg.Region) {
cfg.Host = hostPrefix + "." + cfg.Region + defaultDomain
}
}
}
if cfg.LoginTimeout == 0 {
cfg.LoginTimeout = defaultLoginTimeout
}
if cfg.RequestTimeout == 0 {
cfg.RequestTimeout = defaultRequestTimeout
}
if strings.Trim(cfg.Application, " ") == "" {
cfg.Application = clientType
}
if strings.HasSuffix(cfg.Host, defaultDomain) && len(cfg.Host) == len(defaultDomain) {
return &SnowflakeError{
Number: ErrCodeFailedToParseHost,
Message: errMsgFailedToParseHost,
MessageArgs: []interface{}{cfg.Host},
}
}
return nil
}
// transformAccountToHost transforms host to accout name
func transformAccountToHost(cfg *Config) (err error) {
if cfg.Port == 0 && !strings.HasSuffix(cfg.Host, defaultDomain) && cfg.Host != "" {
// account name is specified instead of host:port
cfg.Account = cfg.Host
cfg.Host = cfg.Account + defaultDomain
cfg.Port = 443
posDot := strings.Index(cfg.Account, ".")
if posDot > 0 {
cfg.Region = cfg.Account[posDot+1:]
cfg.Account = cfg.Account[:posDot]
}
}
return nil
}
// parseAccountHostPort parses the DSN string to attempt to get account or host and port.
func parseAccountHostPort(cfg *Config, posAt, posSlash int, dsn string) (err error) {
// account or host:port
var k int
for k = posAt + 1; k < posSlash; k++ {
if dsn[k] == ':' {
cfg.Port, err = strconv.Atoi(dsn[k+1 : posSlash])
if err != nil {
err = &SnowflakeError{
Number: ErrCodeFailedToParsePort,
Message: errMsgFailedToParsePort,
MessageArgs: []interface{}{dsn[k+1 : posSlash]},
}
return
}
break
}
}
cfg.Host = dsn[posAt+1 : k]
return transformAccountToHost(cfg)
}
// parseUserPassword parses the DSN string for username and password
func parseUserPassword(posAt int, dsn string) (user, password string) {
var k int
for k = 0; k < posAt; k++ {
if dsn[k] == ':' {
password = dsn[k+1 : posAt]
break
}
}
user = dsn[:k]
return
}
// parseParams parse parameters
func parseParams(cfg *Config, posQuestion int, dsn string) (err error) {
for j := posQuestion + 1; j < len(dsn); j++ {
if dsn[j] == '?' {
if err = parseDSNParams(cfg, dsn[j+1:]); err != nil {
return
}
break
}
}
return
}
// parseDSNParams parses the DSN "query string". Values must be url.QueryEscape'ed
func parseDSNParams(cfg *Config, params string) (err error) {
glog.V(2).Infof("Query String: %v\n", params)
for _, v := range strings.Split(params, "&") {
param := strings.SplitN(v, "=", 2)
if len(param) != 2 {
continue
}
var value string
value, err = url.QueryUnescape(param[1])
if err != nil {
return err
}
switch param[0] {
// Disable INFILE whitelist / enable all files
case "account":
cfg.Account = value
case "warehouse":
cfg.Warehouse = value
case "database":
cfg.Database = value
case "schema":
cfg.Schema = value
case "role":
cfg.Role = value
case "region":
cfg.Region = value
case "protocol":
cfg.Protocol = value
case "passcode":
cfg.Passcode = value
case "passcodeInPassword":
var vv bool
vv, err = strconv.ParseBool(value)
if err != nil {
return
}
cfg.PasscodeInPassword = vv
case "loginTimeout":
var vv int64
vv, err = strconv.ParseInt(value, 10, 64)
if err != nil {
return
}
cfg.LoginTimeout = time.Duration(vv * int64(time.Second))
case "application":
cfg.Application = value
case "authenticator":
cfg.Authenticator = strings.ToLower(value)
case "insecureMode":
var vv bool
vv, err = strconv.ParseBool(value)
if err != nil {
return
}
cfg.InsecureMode = vv
case "token":
cfg.Token = value
default:
if cfg.Params == nil {
cfg.Params = make(map[string]*string)
}
cfg.Params[param[0]] = &value
}
}
return
}