-
Notifications
You must be signed in to change notification settings - Fork 37
/
dsn.go
588 lines (497 loc) · 12.1 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
package dburl
import (
"errors"
"net/url"
"os"
stdpath "path"
"sort"
"strings"
)
// GenScheme returns a func that generates a scheme:// style DSN from the
// passed URL.
func GenScheme(scheme string) func(*URL) (string, error) {
return func(u *URL) (string, error) {
z := &url.URL{
Scheme: scheme,
Opaque: u.Opaque,
User: u.User,
Host: u.Host,
Path: u.Path,
RawPath: u.RawPath,
RawQuery: u.RawQuery,
Fragment: u.Fragment,
}
return z.String(), nil
}
}
// GenFromURL returns a func that generates a DSN using urlstr as the default
// URL parameters, overriding the values only if when in the passed URL.
func GenFromURL(urlstr string) func(*URL) (string, error) {
z, err := url.Parse(urlstr)
if err != nil {
panic(err)
}
return func(u *URL) (string, error) {
opaque := z.Opaque
if u.Opaque != "" {
opaque = u.Opaque
}
user := z.User
if u.User != nil {
user = u.User
}
host, port := hostname(z.Host), hostport(z.Host)
if h := hostname(u.Host); h != "" {
host = h
}
if p := hostport(u.Host); p != "" {
port = p
}
if port != "" {
host += ":" + port
}
path := z.Path
if u.Path != "" {
path = u.Path
}
rawPath := z.RawPath
if u.RawPath != "" {
rawPath = u.RawPath
}
q := z.Query()
for k, v := range u.Query() {
q.Set(k, strings.Join(v, " "))
}
fragment := z.Fragment
if u.Fragment != "" {
fragment = u.Fragment
}
y := &url.URL{
Scheme: z.Scheme,
Opaque: opaque,
User: user,
Host: host,
Path: path,
RawPath: rawPath,
RawQuery: q.Encode(),
Fragment: fragment,
}
return y.String(), nil
}
}
// GenOpaque generates a opaque file path DSN from the passed URL.
func GenOpaque(u *URL) (string, error) {
if u.Opaque == "" {
return "", ErrMissingPath
}
return u.Opaque + genQueryOptions(u.Query()), nil
}
// GenPostgres generates a postgres DSN from the passed URL.
func GenPostgres(u *URL) (string, error) {
host, port, dbname := hostname(u.Host), hostport(u.Host), strings.TrimPrefix(u.Path, "/")
if host == "." {
return "", ErrRelativePathNotSupported
}
// resolve path
if u.Proto == "unix" {
if host == "" {
dbname = "/" + dbname
}
host, port, dbname = resolveDir(stdpath.Join(host, dbname))
}
q := u.Query()
q.Set("host", host)
q.Set("port", port)
q.Set("dbname", dbname)
// add user/pass
if u.User != nil {
q.Set("user", u.User.Username())
pass, _ := u.User.Password()
q.Set("password", pass)
}
return genOptions(q, "", "=", " ", ",", true), nil
}
// GenSQLServer generates a mssql DSN from the passed URL.
func GenSQLServer(u *URL) (string, error) {
host, port, dbname := hostname(u.Host), hostport(u.Host), strings.TrimPrefix(u.Path, "/")
// add instance name to host if present
if i := strings.Index(dbname, "/"); i != -1 {
host = host + `\` + dbname[:i]
dbname = dbname[i+1:]
}
q := u.Query()
q.Set("Server", host)
q.Set("Port", port)
q.Set("Database", dbname)
// add user/pass
if u.User != nil {
q.Set("User ID", u.User.Username())
pass, _ := u.User.Password()
q.Set("Password", pass)
}
return genOptionsODBC(q, true), nil
}
// GenSybase generates a sqlany DSN from the passed URL.
func GenSybase(u *URL) (string, error) {
// of format "UID=DBA;PWD=sql;Host=demo12;DatabaseName=demo;ServerName=myserver"
host, port, dbname := hostname(u.Host), hostport(u.Host), strings.TrimPrefix(u.Path, "/")
// add instance name to host if present
if i := strings.Index(dbname, "/"); i != -1 {
host = host + `\` + dbname[:i]
dbname = dbname[i+1:]
}
q := u.Query()
q.Set("Host", host)
if port != "" {
q.Set("LINKS", "tcpip(PORT="+port+")")
}
q.Set("DatabaseName", dbname)
// add user/pass
if u.User != nil {
q.Set("UID", u.User.Username())
pass, _ := u.User.Password()
q.Set("PWD", pass)
}
return genOptionsODBC(q, true), nil
}
// GenMySQL generates a mysql DSN from the passed URL.
func GenMySQL(u *URL) (string, error) {
host, port, dbname := hostname(u.Host), hostport(u.Host), strings.TrimPrefix(u.Path, "/")
// create dsn
dsn := ""
// build user/pass
if u.User != nil {
if un := u.User.Username(); len(un) > 0 {
if up, ok := u.User.Password(); ok {
un += ":" + up
}
dsn += un + "@"
}
}
// resolve path
if u.Proto == "unix" {
if host == "" {
dbname = "/" + dbname
}
host, dbname = resolveSocket(stdpath.Join(host, dbname))
port = ""
}
// if host or proto is not empty
if u.Proto != "unix" {
if host == "" {
host = "127.0.0.1"
}
if port == "" {
port = "3306"
}
}
if port != "" {
port = ":" + port
}
dsn += u.Proto + "(" + host + port + ")"
// add database name
dsn += "/" + dbname
return dsn + genQueryOptions(u.Query()), nil
}
// GenMyMySQL generates a MyMySQL MySQL DSN from the passed URL.
func GenMyMySQL(u *URL) (string, error) {
host, port, dbname := hostname(u.Host), hostport(u.Host), strings.TrimPrefix(u.Path, "/")
// resolve path
if u.Proto == "unix" {
if host == "" {
dbname = "/" + dbname
}
host, dbname = resolveSocket(stdpath.Join(host, dbname))
port = ""
}
// if host or proto is not empty
if u.Proto != "unix" {
if host == "" {
host = "127.0.0.1"
}
if port == "" {
port = "3306"
}
}
if port != "" {
port = ":" + port
}
dsn := u.Proto + ":" + host + port
// add opts
dsn += genOptions(
convertOptions(u.Query(), "true", ""),
",", "=", ",", " ", false,
)
// add dbname
dsn += "*" + dbname
// add user/pass
if u.User != nil {
pass, _ := u.User.Password()
dsn += "/" + u.User.Username() + "/" + pass
} else if strings.HasSuffix(dsn, "*") {
dsn += "//"
}
return dsn, nil
}
// GenOracle generates a ora DSN from the passed URL.
func GenOracle(u *URL) (string, error) {
// create dsn
dsn := u.Host + u.Path
// build user/pass
var un string
if u.User != nil {
if un = u.User.Username(); len(un) > 0 {
if up, ok := u.User.Password(); ok {
un += "/" + up
}
}
}
return un + "@" + dsn, nil
}
// GenFirebird generates a firebirdsql DSN from the passed URL.
func GenFirebird(u *URL) (string, error) {
z := &url.URL{
User: u.User,
Host: u.Host,
Path: u.Path,
RawPath: u.RawPath,
RawQuery: u.RawQuery,
Fragment: u.Fragment,
}
return z.String(), nil
}
// GenADODB generates a adodb DSN from the passed URL.
func GenADODB(u *URL) (string, error) {
// grab data source
dsname, dbname := strings.TrimPrefix(u.Path, "/"), ""
if dsname == "" {
dsname = "."
}
// check if data source is not a path on disk
if mode(dsname) == 0 {
if i := strings.IndexAny(dsname, `\/`); i != -1 {
dbname = dsname[i+1:]
dsname = dsname[:i]
}
}
q := u.Query()
q.Set("Provider", hostname(u.Host))
q.Set("Port", hostport(u.Host))
q.Set("Data Source", dsname)
q.Set("Database", dbname)
// add user/pass
if u.User != nil {
q.Set("User ID", u.User.Username())
pass, _ := u.User.Password()
q.Set("Password", pass)
}
return genOptionsODBC(q, true), nil
}
// GenODBC generates a odbc DSN from the passed URL.
func GenODBC(u *URL) (string, error) {
q := u.Query()
q.Set("Driver", "{"+strings.Replace(u.Proto, "+", " ", -1)+"}")
q.Set("Server", hostname(u.Host))
port := hostport(u.Host)
if port == "" {
proto := strings.ToLower(u.Proto)
switch {
case strings.Contains(proto, "mysql"):
port = "3306"
case strings.Contains(proto, "postgres"):
port = "5432"
default:
port = "1433"
}
}
q.Set("Port", port)
q.Set("Database", strings.TrimPrefix(u.Path, "/"))
// add user/pass
if u.User != nil {
q.Set("UID", u.User.Username())
p, _ := u.User.Password()
q.Set("PWD", p)
}
return genOptionsODBC(q, true), nil
}
// GenOLEODBC generates a oleodbc DSN from the passed URL.
func GenOLEODBC(u *URL) (string, error) {
props, err := GenODBC(u)
if err != nil {
return "", nil
}
return `Provider=MSDASQL.1;Extended Properties="` + props + `"`, nil
}
// GenClickhouse generates a clickhouse DSN from the passed URL.
func GenClickhouse(u *URL) (string, error) {
z := &url.URL{
Scheme: "tcp",
Opaque: u.Opaque,
Host: u.Host,
Path: u.Path,
RawPath: u.RawPath,
RawQuery: u.RawQuery,
Fragment: u.Fragment,
}
if hostport(z.Host) == "" {
z.Host += ":9000"
}
// add parameters
q := z.Query()
if u.User != nil {
if user := u.User.Username(); len(user) > 0 {
q.Set("username", user)
}
if pass, ok := u.User.Password(); ok {
q.Set("password", pass)
}
}
z.RawQuery = q.Encode()
return z.String(), nil
}
// GenYQL generates a YQL DSN from the passed URL.
func GenYQL(u *URL) (string, error) {
dsn := ""
if u.User != nil {
if user := u.User.Username(); len(user) > 0 {
dsn += user
}
if pass, ok := u.User.Password(); ok {
dsn += "|" + pass
} else {
return "", errors.New("missing password")
}
}
if u.Host != "" {
if dsn == "" {
dsn = "|"
}
dsn += "|store://" + u.Host + u.Path
}
return dsn, nil
}
// GenVoltDB generates a VoltDB DSN from the passed URL.
func GenVoltDB(u *URL) (string, error) {
host, port := "localhost", "21212"
if h := hostname(u.Host); h != "" {
host = h
}
if p := hostport(u.Host); p != "" {
port = p
}
return host + ":" + port, nil
}
// genOptions takes URL values and generates options, joining together with
// joiner, and separated by sep, with any multi URL values joined by valSep,
// ignoring any values with keys in ignore.
//
// For example, to build a "ODBC" style connection string, use like the following:
// genOptions(u.Query(), "", "=", ";", ",")
func genOptions(q url.Values, joiner, assign, sep, valSep string, skipWhenEmpty bool, ignore ...string) string {
qlen := len(q)
if qlen == 0 {
return ""
}
// make ignore map
ig := make(map[string]bool, len(ignore))
for _, v := range ignore {
ig[strings.ToLower(v)] = true
}
// sort keys
s := make([]string, len(q))
var i int
for k := range q {
s[i] = k
i++
}
sort.Strings(s)
var opts []string
for _, k := range s {
if !ig[strings.ToLower(k)] {
val := strings.Join(q[k], valSep)
if !skipWhenEmpty || val != "" {
if val != "" {
val = assign + val
}
opts = append(opts, k+val)
}
}
}
if len(opts) != 0 {
return joiner + strings.Join(opts, sep)
}
return ""
}
// genOptionsODBC is a util wrapper around genOptions that uses the fixed settings
// for ODBC style connection strings.
func genOptionsODBC(q url.Values, skipWhenEmpty bool, ignore ...string) string {
return genOptions(q, "", "=", ";", ",", skipWhenEmpty, ignore...)
}
// genQueryOptions generates standard query options.
func genQueryOptions(q url.Values) string {
if s := q.Encode(); s != "" {
return "?" + s
}
return ""
}
// convertOptions converts an option value based on name, value pairs.
func convertOptions(q url.Values, pairs ...string) url.Values {
n := make(url.Values)
for k, v := range q {
x := make([]string, len(v))
for i, z := range v {
for j := 0; j < len(pairs); j += 2 {
if pairs[j] == z {
z = pairs[j+1]
}
}
x[i] = z
}
n[k] = x
}
return n
}
// mode returns the mode of the path.
func mode(path string) os.FileMode {
if fi, err := os.Stat(path); err == nil {
return fi.Mode()
}
return 0
}
// resolveSocket tries to resolve a path to a unix domain socket
// based on the actual file path of the form "/path/to/socket/dbname" returning
// either the original path and the empty string, or the components
// "/path/to/socket" and "dbname", when /path/to/socket/dbname is reported by
// os.Stat as a unix socket.
func resolveSocket(path string) (string, string) {
dir, dbname := path, ""
for dir != "" && dir != "/" && dir != "." {
if m := mode(dir); m&os.ModeSocket != 0 {
return dir, dbname
}
dir, dbname = stdpath.Dir(dir), stdpath.Base(dir)
}
return path, ""
}
// resolveDir resolves a directory with a :port list.
func resolveDir(path string) (string, string, string) {
dir := path
for dir != "" && dir != "/" && dir != "." {
port := ""
i, j := strings.LastIndex(dir, ":"), strings.LastIndex(dir, "/")
if i != -1 && i > j {
port = dir[i+1:]
dir = dir[:i]
}
if mode(dir)&os.ModeDir != 0 {
rest := strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(path, dir), ":"+port), "/")
return dir, port, rest
}
if j != -1 {
dir = dir[:j]
} else {
dir = ""
}
}
return path, "", ""
}