-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
84 lines (73 loc) · 2.19 KB
/
database.go
File metadata and controls
84 lines (73 loc) · 2.19 KB
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
package tmppg
import (
"context"
"fmt"
"log/slog"
"math/rand/v2"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type Instance struct {
connString string
log *slog.Logger
}
func NewInstance(connString string) *Instance {
return &Instance{
connString: connString,
log: slog.Default(),
}
}
func (i *Instance) WithDatabase(ctx context.Context, fn func(pool *pgxpool.Pool) error) (err error) {
var conn *pgx.Conn
conn, err = pgx.Connect(ctx, i.connString+" dbname=postgres")
if err != nil {
return fmt.Errorf("connect to admin database: %w", err)
}
defer conn.Close(ctx)
dbname := fmt.Sprintf("test%d", rand.Uint32())
i.log.Info("creating database", slog.String("name", dbname))
_, err = conn.Exec(ctx, "CREATE DATABASE "+dbname)
if err != nil {
return fmt.Errorf("create database %q: %w", dbname, err)
}
// run database removal deferred, so the database also gets removed on
// runtime.Goexit() and t.FailNow()
defer func() {
i.log.Info("dropping database", slog.String("name", dbname))
_, dropError := conn.Exec(ctx, "DROP DATABASE "+dbname+" WITH (FORCE)")
if dropError != nil {
if err == nil {
err = fmt.Errorf("drop database %q: %w", dbname, dropError)
} else {
err = fmt.Errorf("drop database %q: %w; previous error: %w", dbname, dropError, err)
}
}
}()
pool, err := pgxpool.New(ctx, i.connString+" dbname="+dbname)
if err != nil {
return fmt.Errorf("connect to database %q: %w", dbname, err)
}
defer pool.Close()
if err = fn(pool); err != nil {
return fmt.Errorf("in function: %w", err)
}
return nil
}
func (i *Instance) WithDatabaseSchema(ctx context.Context, schemaSQL string, fn func(pool *pgxpool.Pool) error) error {
return i.WithDatabase(ctx, func(pool *pgxpool.Pool) error {
// run DDL on its own connection in case it does any weird stuff like `SET search_path`
// closing the connection afterwards ensures that `SET`s are discarded
err := pool.AcquireFunc(ctx, func(conn *pgxpool.Conn) error {
_, err := conn.Exec(ctx, schemaSQL)
if err != nil {
return err
}
err = conn.Conn().Close(ctx)
return err
})
if err != nil {
return fmt.Errorf("create schema: %w", err)
}
return fn(pool)
})
}