generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driverpostgres.go
94 lines (73 loc) · 1.66 KB
/
driverpostgres.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
package sqltest
import (
"errors"
"net"
"net/url"
"strings"
)
// postgresDriver is the implementation of Driver for the "postgres" driver.
type postgresDriver struct{}
func (postgresDriver) Name() string {
return "postgres"
}
func (postgresDriver) IsAvailable() bool {
return true
}
func (postgresDriver) ParseDSN(dsn string) (DataSource, error) {
u, err := url.Parse(dsn)
if err != nil {
return nil, err
}
if u.Scheme != "postgres" {
return nil, errors.New("unexpected URL scheme, must be 'postgres'")
}
if u.Port() == "" {
u.Host = net.JoinHostPort(u.Host, "5432")
}
return postgresDataSource{u}, nil
}
func (d postgresDriver) DataSourceForPostgres(
user, pass,
host, port,
database string,
) (DataSource, error) {
u := &url.URL{
Scheme: "postgres",
Host: host,
}
q := url.Values{
"sslmode": []string{"disable"},
}
u.RawQuery = q.Encode()
if user != "" || pass != "" {
u.User = url.UserPassword(user, pass)
}
if port != "" {
u.Host = net.JoinHostPort(u.Host, port)
}
if database != "" {
u.Path = "/" + database
}
return postgresDataSource{u}, nil
}
// postgresDataSource is an implementation of DataSource for "postgres" driver.
type postgresDataSource struct {
url *url.URL
}
func (ds postgresDataSource) DriverName() string {
return "postgres"
}
func (ds postgresDataSource) DSN() string {
return ds.url.String()
}
func (ds postgresDataSource) DatabaseName() string {
return strings.TrimPrefix(ds.url.Path, "/")
}
func (ds postgresDataSource) WithDatabaseName(database string) DataSource {
u := *ds.url
u.Path = "/" + database
return postgresDataSource{&u}
}
func (ds postgresDataSource) Close() error {
return nil
}