-
Notifications
You must be signed in to change notification settings - Fork 18
/
dbfixture.go
316 lines (265 loc) · 7.21 KB
/
dbfixture.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package dbfixture
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net/url"
"os"
"sync"
"time"
"github.com/jackc/pgx/v4"
"github.com/jmoiron/sqlx"
"gotest.tools/v3/assert"
"github.com/circleci/ex/config/secret"
"github.com/circleci/ex/db"
"github.com/circleci/ex/o11y"
"github.com/circleci/ex/testing/internal/types"
)
var globalFixture = &SharedFixture{}
var mustRunAllTests = os.Getenv("CI") == "true"
type SharedFixture struct {
once sync.Once
m *Manager
}
func (s *SharedFixture) Manager() *Manager {
return s.m
}
// SetupSystem prepares the running system for use
// callers should not rely on the fact this currently uses a package global
func SetupSystem(t types.TestingTB, con Connection) *SharedFixture {
return setupSystem(t, con)
}
// setupSystem prepares the running system for use
func setupSystem(t types.TestingTB, con Connection) *SharedFixture {
globalFixture.once.Do(func() {
var err error
globalFixture.m, err = newManager(con)
if err != nil {
var noDBError *NoDBError
if errors.As(err, &noDBError) && !mustRunAllTests {
t.Skip(noDBError.Error())
}
t.Fatal(err.Error())
}
})
if globalFixture.m == nil {
t.Skip("global fixtures failed setup")
}
return globalFixture
}
type Connection struct {
Host string
User string
Password secret.String
}
func SetupDB(ctx context.Context, t types.TestingTB, schema string, con Connection) (db *Fixture) {
t.Helper()
shared := SetupSystem(t, con)
db, err := shared.Manager().NewDB(ctx, con, t.Name(), schema)
assert.Assert(t, err)
t.Cleanup(func() {
p := o11y.FromContext(ctx)
ctx, cancel := context.WithTimeout(o11y.WithProvider(context.Background(), p), 10*time.Second)
defer cancel()
if r := recover(); r != nil {
_ = db.Cleanup(ctx)
panic(r)
}
assert.Assert(t, db.Cleanup(ctx))
})
return db
}
type Manager struct {
db *sqlx.DB
}
// NewManager returns a DB manager
func NewManager(con Connection) (*Manager, error) {
return newManager(con)
}
func newManager(con Connection) (*Manager, error) {
m := &Manager{}
var err error
m.db, err = newDB(con, "postgres")
if err != nil {
return nil, err
}
return m, nil
}
// NewDB returns a new database fixture. The database name is generated from dbName with a random suffix.
func (m *Manager) NewDB(ctx context.Context, con Connection, dbName, schema string) (*Fixture, error) {
s := fmt.Sprintf("%s-%s", randomSuffix(), dbName)
l := len(s)
if l > 63 {
l = 63
}
s = s[:l]
return m.newDB(ctx, m.db, con, s, schema)
}
func (m *Manager) newDB(ctx context.Context, d *sqlx.DB, con Connection, dbName, schema string) (
_ *Fixture, err error) {
ctx, span := o11y.StartSpan(ctx, "dbfixture: newDB")
defer o11y.End(span, &err)
fix := &Fixture{DBName: dbName, Host: con.Host, User: con.User, Password: con.Password}
span.AddField("dbname", fix.DBName)
span.AddField("host", con.Host)
span.AddField("user", con.User)
createDB := fmt.Sprintf("CREATE DATABASE %s", pgx.Identifier{fix.DBName}.Sanitize())
_, err = d.ExecContext(ctx, createDB)
if err != nil {
return nil, err
}
fix.DB, err = newDB(con, fix.DBName)
if err != nil {
return nil, err
}
fix.TX = db.NewTxManager(fix.DB)
fix.Cleanup = func(ctx context.Context) error {
return m.cleanup(ctx, d, fix)
}
err = fix.DB.Ping()
if err != nil {
return nil, err
}
o11y.Log(ctx, "applying schema")
_, err = fix.DB.ExecContext(ctx, schema)
if err != nil {
return nil, fmt.Errorf("failed to apply schema: %w", err)
}
err = fix.DB.SelectContext(ctx, &fix.tables, `
SELECT
table_name,
table_schema
FROM
information_schema.tables
WHERE
table_type = 'BASE TABLE'
AND
table_schema NOT IN ('pg_catalog', 'information_schema')
`)
if err != nil {
return nil, fmt.Errorf("could not get list of tables: %w", err)
}
// pg_dump blanks 'search_path' for security reasons, we need to set it back
// https://www.postgresql.org/message-id/ace62b19-f918-3579-3633-b9e19da8b9de%40aklaver.com
_, err = fix.DB.ExecContext(ctx, "SELECT pg_catalog.set_config('search_path', 'public', false);")
if err != nil {
return nil, err
}
return fix, nil
}
func (m *Manager) Close() error {
return m.db.Close()
}
type NoDBError struct {
err error
}
func (e *NoDBError) Error() string {
return fmt.Sprintf("no database available: %s", e.err)
}
func (e *NoDBError) Unwrap() error {
return e.err
}
func newDB(con Connection, name string) (db *sqlx.DB, err error) {
params := url.Values{}
params.Set("connect_timeout", "5")
params.Set("sslmode", "disable")
uri := url.URL{
Scheme: "postgres",
User: url.UserPassword(con.User, con.Password.Value()),
Host: con.Host,
Path: name,
RawQuery: params.Encode(),
}
db, err = sqlx.Open("pgx", uri.String())
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(time.Hour)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
err = db.Ping()
if err != nil {
return nil, &NoDBError{err: err}
}
return db, nil
}
func (m *Manager) cleanup(ctx context.Context, db *sqlx.DB, fixture *Fixture) error {
err := fixture.DB.Close()
if err != nil {
o11y.LogError(ctx, "db: cleanup", err)
}
if os.Getenv("TEST_PRESERVE_DB") != "" {
return nil
}
// attempt to kick out any melingering connections before dropping the database
_, err = db.ExecContext(ctx,
fmt.Sprintf("REVOKE CONNECT ON DATABASE %s FROM public;", pgx.Identifier{fixture.DBName}.Sanitize()))
if err != nil {
return fmt.Errorf("revoke con: %w", err)
}
killConSQL := `
SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = '%s' AND pid <> pg_backend_pid();
`
_, err = db.ExecContext(ctx, fmt.Sprintf(killConSQL, fixture.DBName))
if err != nil {
o11y.LogError(ctx, "db: cleanup drop con", err)
}
dbName := pgx.Identifier{fixture.DBName}.Sanitize()
_, err = db.ExecContext(ctx, fmt.Sprintf("DROP DATABASE %s", dbName))
if err != nil {
return fmt.Errorf("drop db: %w", err)
}
return nil
}
func randomSuffix() string {
bytes := make([]byte, 3)
if _, err := rand.Read(bytes); err != nil {
return "not-random--i-hope-thats-ok"
}
return hex.EncodeToString(bytes)
}
type Fixture struct {
DBName string
Host string
User string
Password secret.String
DB *sqlx.DB
TX *db.TxManager
Cleanup func(ctx context.Context) error
tables []table
}
type table struct {
Schema string `db:"table_schema"`
Name string `db:"table_name"`
}
func (f *Fixture) Reset(ctx context.Context) (err error) {
return f.TX.WithTx(ctx, func(ctx context.Context, tx db.Querier) error {
_, err = tx.ExecContext(ctx, `SET session_replication_role = 'replica';`)
if squelchNopError(err) != nil {
return fmt.Errorf("could not disable contraint checks: %w", err)
}
for _, table := range f.tables {
// nolint: gosec
_, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s`,
pgx.Identifier{table.Schema, table.Name}.Sanitize()))
if squelchNopError(err) != nil {
return fmt.Errorf("could not delete from table: %w", err)
}
}
_, err = tx.ExecContext(ctx, `SET session_replication_role = 'origin';`)
if squelchNopError(err) != nil {
return fmt.Errorf("could not enable contraint checks: %w", err)
}
return nil
})
}
func squelchNopError(err error) error {
if err != nil && !errors.Is(err, db.ErrNop) {
return err
}
return nil
}