/
connstr.go
95 lines (92 loc) · 1.94 KB
/
connstr.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
package main
import (
"fmt"
"net/url"
"strings"
)
type connectionConfig struct {
Type string // postgres, mysql, sqlserver
Name string
Host string
Port int
User string
Password string
Database string
TLS bool
}
// connectionString returns an URL or connection string that can be passed to sql.Open.
func (c connectionConfig) connectionString(dbName string) string {
switch c.Type {
case "postgres":
quote := func(s string) string {
s = strings.Replace(s, `\`, `\\`, -1)
s = strings.Replace(s, `'`, `\'`, -1)
if s == "" || strings.ContainsAny(s, " '\\") {
s = "'" + s + "'"
}
return s
}
sslmode := "disable"
if c.TLS {
sslmode = "verify-full"
}
s := fmt.Sprintf("host=%s sslmode=%s application_name=duitsql", quote(c.Host), sslmode)
if c.Port != 0 {
s += fmt.Sprintf(" port=%d", c.Port)
}
if c.User != "" {
s += fmt.Sprintf(" user=%s", quote(c.User))
}
if c.Password != "" {
s += fmt.Sprintf(" password=%s", quote(c.Password))
}
if dbName != "" {
s += fmt.Sprintf(" dbname=%s", quote(dbName))
}
return s
case "mysql":
s := ""
if c.User != "" || c.Password != "" {
s += c.User
if c.Password != "" {
s += ":" + c.Password
}
s += "@"
}
address := c.Host
port := c.Port
if port == 0 {
port = 3306
}
address += fmt.Sprintf(":%d", port)
s += fmt.Sprintf("tcp(%s)", address)
s += "/"
if dbName != "" {
s += dbName
}
if c.TLS {
s += "?tls=true"
}
return s
case "sqlserver":
host := c.Host
if c.Port != 0 {
host += fmt.Sprintf(":%d", c.Port)
}
qs := []string{}
if dbName != "" {
qs = append(qs, "database="+url.QueryEscape(dbName))
}
if c.TLS {
qs = append(qs, "encrypt=true", "TrustServerCertificate=false")
}
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword(c.User, c.Password),
Host: host,
RawQuery: strings.Join(qs, "&"),
}
return u.String()
}
panic("missing case")
}