/
conex_postgres.go
86 lines (67 loc) · 1.64 KB
/
conex_postgres.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
package postgres
import (
"database/sql"
"fmt"
"testing"
"time"
"github.com/omeid/conex"
// The driver.
_ "github.com/lib/pq"
)
var (
// Image to use for the box.
Image = "postgres:alpine"
// Port used for connect to postgres server.
Port = "5432"
// PostgresUpWaitTime dectiates how long we should wait for post Postgresql to accept connections on {{Port}}.
PostgresUpWaitTime = 10 * time.Second
)
func init() {
conex.Require(func() string { return Image })
}
// Config used to connect to the database.
type Config struct {
User string
Password string
Database string // defaults to `postgres` as service db.
host string
port string
}
func (c *Config) url() string {
if c.Database == "" {
c.Database = "postgres"
}
return fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
c.User, c.Password, c.host, c.port, c.Database,
)
}
// Box returns an sql.DB connection and the container running the Postgresql
// instance. It will call t.Fatal on errors.
func Box(t testing.TB, config *Config) (*sql.DB, conex.Container) {
c := conex.Box(t, &conex.Config{
Image: Image,
Expose: []string{Port},
})
if config == nil {
config = &Config{
Database: "postgres",
User: "postgres",
}
}
config.host = c.Address()
config.port = Port
t.Logf("Waiting for Postgresql to accept connections")
err := c.Wait(Port, PostgresUpWaitTime)
if err != nil {
c.Drop() // return the container
t.Fatal("Postgres failed to start.", err)
}
t.Log("Postgresql is now accepting connections")
db, err := sql.Open("postgres", config.url())
if err != nil {
c.Drop() // return the container
t.Fatal(err)
}
return db, c
}