-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresql.go
80 lines (67 loc) · 1.79 KB
/
postgresql.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
package postgresql
import (
"errors"
"github.com/go-gdbc/gdbc"
_ "github.com/jackc/pgx/v4/stdlib"
"strings"
)
const DefaultHost = "localhost"
const DefaultPort = "5432"
const DefaultUser = "postgres"
func init() {
gdbc.Register("pgx", "postgresql", &PostgresDataSourceNameAdapter{})
}
type PostgresDataSourceNameAdapter struct {
}
func (dsnAdapter PostgresDataSourceNameAdapter) GetDataSourceName(dataSource gdbc.DataSource) (string, error) {
dsn := ""
host := DefaultHost
port := DefaultPort
user := DefaultUser
password := ""
databaseName := ""
dataSourceUrl := dataSource.GetURL()
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)
}
dsn = dsn + "host=" + host + " port=" + port + " user=" + user + " password=" + password + " dbname=" + databaseName
arguments := dataSourceUrl.Query()
if arguments != nil {
for argumentName, values := range arguments {
dsn = dsn + " " + argumentName + "=" + values[0]
}
}
return dsn, nil
}