-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
preset.go
187 lines (151 loc) 路 4.05 KB
/
preset.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Package postgres provides a Gnomock Preset for PostgreSQL database.
package postgres
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
_ "github.com/lib/pq" // postgres driver
"github.com/orlangure/gnomock"
"github.com/orlangure/gnomock/internal/registry"
)
const (
defaultUser = "postgres"
defaultPassword = "password"
defaultDatabase = "postgres"
defaultSSLMode = "disable"
defaultPort = 5432
defaultVersion = "12.5"
)
func init() {
registry.Register("postgres", func() gnomock.Preset { return &P{} })
}
// Preset creates a new Gmomock Postgres preset. This preset includes a Postgres
// specific healthcheck function, default Postgres image and port, and allows to
// optionally set up initial state.
//
// By default, this preset uses `postgres` user with `password` password, with
// default database `postgres`. Default PostgresQL version is 12.5.
func Preset(opts ...Option) gnomock.Preset {
p := &P{}
for _, opt := range opts {
opt(p)
}
return p
}
// P is a Gnomock Preset implementation of PostgreSQL database.
type P struct {
DB string `json:"db"`
Queries []string `json:"queries"`
QueriesFiles []string `json:"queries_files"`
User string `json:"user"`
Password string `json:"password"`
Timezone string `json:"timezone"`
Version string `json:"version"`
}
// Image returns an image that should be pulled to create this container.
func (p *P) Image() string {
return fmt.Sprintf("docker.io/library/postgres:%s", p.Version)
}
// Ports returns ports that should be used to access this container.
func (p *P) Ports() gnomock.NamedPorts {
return gnomock.DefaultTCP(defaultPort)
}
// Options returns a list of options to configure this container.
func (p *P) Options() []gnomock.Option {
p.setDefaults()
if p.User != "" && p.Password != "" {
q := fmt.Sprintf(
`create user %s with superuser password '%s'`,
p.User, p.Password,
)
p.Queries = append(p.Queries, q)
}
opts := []gnomock.Option{
gnomock.WithHealthCheck(p.healthcheck),
gnomock.WithEnv("POSTGRES_PASSWORD=" + defaultPassword),
gnomock.WithEnv("TZ=" + p.Timezone),
gnomock.WithInit(p.initf()),
}
if p.Timezone != "" {
opts = append(opts, gnomock.WithEnv("TZ="+p.Timezone))
}
return opts
}
func (p *P) healthcheck(_ context.Context, c *gnomock.Container) error {
db, err := connect(c, defaultDatabase)
if err != nil {
return err
}
defer func() {
_ = db.Close()
}()
var one int
return db.QueryRow(`select 1`).Scan(&one)
}
func (p *P) initf() gnomock.InitFunc {
return func(ctx context.Context, c *gnomock.Container) error {
if p.DB != defaultDatabase {
db, err := connect(c, defaultDatabase)
if err != nil {
return err
}
_, err = db.Exec("create database " + p.DB)
if err != nil {
isDuplicateDB := strings.Contains(err.Error(), fmt.Sprintf(`pq: database "%s" already exists`, p.DB))
if !isDuplicateDB {
return err
}
}
_ = db.Close()
}
db, err := connect(c, p.DB)
if err != nil {
return err
}
defer func() { _ = db.Close() }()
if err := p.executeQueries(db); err != nil {
return fmt.Errorf("can't execute setup queries: %w", err)
}
return nil
}
}
func (p *P) setDefaults() {
if p.DB == "" {
p.DB = defaultDatabase
}
if p.Version == "" {
p.Version = defaultVersion
}
}
func (p *P) executeQueries(db *sql.DB) error {
if len(p.QueriesFiles) > 0 {
for _, f := range p.QueriesFiles {
bs, err := os.ReadFile(f) // nolint:gosec
if err != nil {
return fmt.Errorf("can't read queries file '%s': %w", f, err)
}
p.Queries = append([]string{string(bs)}, p.Queries...)
}
}
for _, q := range p.Queries {
_, err := db.Exec(q)
if err != nil {
return err
}
}
return nil
}
func connect(c *gnomock.Container, db string) (*sql.DB, error) {
connStr := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
c.Host, c.Port(gnomock.DefaultPort),
defaultUser, defaultPassword, db, defaultSSLMode,
)
conn, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
return conn, conn.Ping()
}