-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
56 lines (52 loc) · 1.35 KB
/
migrate.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
package devroach
import (
"context"
"github.com/go-logr/logr"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/require"
"io/fs"
"testing"
)
// MigrateT runs all migrations against the given connection.
func MigrateT(t *testing.T, pool *pgxpool.Pool, migrationsFS fs.FS, globs ...string) {
t.Helper()
err := Migrate(context.TODO(), pool, migrationsFS, globs...)
require.NoError(t, err)
}
// Migrate runs all migrations against the given connection.
func Migrate(ctx context.Context, pool *pgxpool.Pool, migrationsFS fs.FS, globs ...string) error {
log := logr.FromContextOrDiscard(ctx).V(10)
if migrationsFS == nil {
return nil
}
all, err := allContents(log, migrationsFS, globs...)
if err != nil {
return err
}
log.Info("applying migrations", "count", len(all))
for _, sql := range all {
_, err = pool.Exec(ctx, sql)
if err != nil {
return err
}
}
return nil
}
func allContents(log logr.Logger, migrationsFS fs.FS, globs ...string) ([]string, error) {
var contents []string
for _, glob := range globs {
matches, err := fs.Glob(migrationsFS, glob)
if err != nil {
return nil, err
}
for _, file := range matches {
c, err := fs.ReadFile(migrationsFS, file)
if err != nil {
return nil, err
}
log.Info("found migration file", "file", file)
contents = append(contents, string(c))
}
}
return contents, nil
}