-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
postgresqlhelper.go
74 lines (62 loc) · 1.69 KB
/
postgresqlhelper.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
package postgresql
import (
"context"
"database/sql"
"fmt"
"net/url"
"os"
"testing"
"github.com/hashicorp/vault/helper/testhelpers/docker"
)
func PrepareTestContainer(t *testing.T, version string) (func(), string) {
return prepareTestContainer(t, version, "secret", "database")
}
func PrepareTestContainerWithPassword(t *testing.T, version, password string) (func(), string) {
return prepareTestContainer(t, version, password, "database")
}
func prepareTestContainer(t *testing.T, version, password, db string) (func(), string) {
if os.Getenv("PG_URL") != "" {
return func() {}, os.Getenv("PG_URL")
}
if version == "" {
version = "11"
}
runner, err := docker.NewServiceRunner(docker.RunOptions{
ImageRepo: "postgres",
ImageTag: version,
Env: []string{
"POSTGRES_PASSWORD=" + password,
"POSTGRES_DB=" + db,
},
Ports: []string{"5432/tcp"},
})
if err != nil {
t.Fatalf("Could not start docker Postgres: %s", err)
}
svc, err := runner.StartService(context.Background(), connectPostgres(password))
if err != nil {
t.Fatalf("Could not start docker Postgres: %s", err)
}
return svc.Cleanup, svc.Config.URL().String()
}
func connectPostgres(password string) docker.ServiceAdapter {
return func(ctx context.Context, host string, port int) (docker.ServiceConfig, error) {
u := url.URL{
Scheme: "postgres",
User: url.UserPassword("postgres", password),
Host: fmt.Sprintf("%s:%d", host, port),
Path: "postgres",
RawQuery: "sslmode=disable",
}
db, err := sql.Open("postgres", u.String())
if err != nil {
return nil, err
}
defer db.Close()
err = db.Ping()
if err != nil {
return nil, err
}
return docker.NewServiceURL(u), nil
}
}