-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
79 lines (69 loc) · 1.6 KB
/
connection.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
package pgtest
import (
"context"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
// Since you shouldn't create a pgx.ConnConfig from scratch, ConnectionSettings exists to hold all the
// parameters we'll need to work with throughout the lifecycle of a postgres database throughout tests.
type ConnectionSettings struct {
Host string
Port string
User string
Password string
Database string
DisableSSL bool
MaxOpenConns int
}
func (cs *ConnectionSettings) DSN() string {
sslmode := "require"
if cs.DisableSSL {
sslmode = "disable"
}
return fmt.Sprintf("host=%v port=%v user=%v password=%v dbname=%v sslmode=%v",
cs.Host,
cs.Port,
cs.User,
cs.Password,
cs.Database,
sslmode,
)
}
func (cs *ConnectionSettings) URL() string {
sslmode := "require"
if cs.DisableSSL {
sslmode = "disable"
}
return fmt.Sprintf("postgresql://%v:%v@%v:%v/%v?sslmode=%v",
cs.User,
cs.Password,
cs.Host,
cs.Port,
cs.Database,
sslmode,
)
}
func (cs *ConnectionSettings) String() string {
return cs.DSN()
}
func (cs *ConnectionSettings) Config() (*pgx.ConnConfig, error) {
return pgx.ParseConfig(cs.String())
}
func (cs *ConnectionSettings) PoolConfig() (*pgxpool.Config, error) {
return pgxpool.ParseConfig(cs.String())
}
func (cs *ConnectionSettings) Copy() *ConnectionSettings {
s := *cs
return &s
}
func (cs *ConnectionSettings) Connect(ctx context.Context) (*pgx.Conn, error) {
conn, err := pgx.Connect(ctx, cs.String())
if err != nil {
return nil, err
}
if err := conn.Ping(ctx); err != nil {
return nil, err
}
return conn, nil
}