forked from go-gdbc/gdbc-mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
118 lines (97 loc) · 2.35 KB
/
mysql.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
package mysql
import (
"errors"
"github.com/go-gdbc/gdbc"
_ "github.com/go-sql-driver/mysql"
"strings"
)
const DefaultHost = "localhost"
const DefaultPort = "3306"
const DefaultUsername = "root"
const DefaultPassword = ""
func init() {
gdbc.Register("mysql", "mysql", &MySQLDataSourceNameAdapter{})
}
type MySQLDataSourceNameAdapter struct {
}
func (dsnAdapter MySQLDataSourceNameAdapter) GetDataSourceName(dataSource gdbc.DataSource) (string, error) {
dsn := ""
host := DefaultHost
port := DefaultPort
user := DefaultUsername
password := DefaultPassword
databaseName := ""
dataSourceUrl := dataSource.GetURL()
arguments := dataSourceUrl.Query()
socketArgument := ""
if arguments != nil {
socketArgument = arguments.Get("socket")
if socketArgument != "" {
user = ""
arguments.Del("socket")
}
}
if dataSourceUrl.Opaque != "" {
databaseName = dataSourceUrl.Opaque
} else {
if dataSourceUrl.Hostname() != "" {
host = dataSourceUrl.Hostname()
}
if dataSourceUrl.Port() != "" {
port = dataSourceUrl.Port()
}
if dataSourceUrl.User != nil {
if dataSourceUrl.User.Username() != "" {
user = dataSourceUrl.User.Username()
}
userPassword, _ := dataSourceUrl.User.Password()
if userPassword != "" {
password = userPassword
}
} else {
if dataSource.GetUsername() != "" {
user = dataSource.GetUsername()
}
if dataSource.GetPassword() != "" {
password = dataSource.GetPassword()
}
}
if dataSourceUrl.Path != "" {
databaseName = dataSourceUrl.Path
}
}
if strings.HasPrefix(databaseName, "/") {
databaseName = databaseName[1:]
}
if strings.Contains(databaseName, "/") {
return "", errors.New("database name format is wrong : " + databaseName)
}
if user != "" {
if password != "" {
dsn = user + ":" + password
} else if password == "" {
dsn = user
}
} else {
if password != "" {
return "", errors.New("user must not be empty when a password is specified")
}
}
if dsn != "" {
dsn = dsn + "@"
}
if socketArgument != "" {
dsn = dsn + "unix(" + socketArgument + ")/" + databaseName
} else {
dsn = dsn + "tcp(" + host + ":" + port + ")/" + databaseName
}
if len(arguments) == 0 {
return dsn, nil
}
dsn = dsn + "?"
for argumentName, values := range arguments {
dsn = dsn + argumentName + "=" + values[0] + "&"
}
dsn = dsn[:len(dsn)-1]
return dsn, nil
}