-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
84 lines (62 loc) · 2.06 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
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 migrate
import (
"context"
"errors"
"github.com/alexfalkowski/go-service/meta"
"github.com/alexfalkowski/migrieren/migrate/migrator"
"github.com/alexfalkowski/migrieren/migrate/telemetry/tracer"
"github.com/golang-migrate/migrate/v4"
// These are here to make sure we can use migrate. Add here to extend it.
_ "github.com/golang-migrate/migrate/v4/database/mysql"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/golang-migrate/migrate/v4/source/github"
)
var (
// ErrInvalidConfig for source or db.
ErrInvalidConfig = errors.New("invalid config")
// ErrInvalidMigration happened.
ErrInvalidMigration = errors.New("invalid migration")
// ErrInvalidPing happened.
ErrInvalidPing = errors.New("invalid ping")
)
// NewMigrator for databases.
func NewMigrator(t tracer.Tracer) migrator.Migrator {
var m migrator.Migrator = &Migrator{}
m = tracer.NewMigrator(m, t)
return m
}
// Migrator using migrate.
type Migrator struct{}
// Migrate a database to a version and returning the database logs.
func (m *Migrator) Migrate(ctx context.Context, source, db string, version uint64) ([]string, error) {
mig, err := migrate.New(source, db)
if err != nil {
meta.WithAttribute(ctx, "migrate.error", err.Error())
return nil, ErrInvalidConfig
}
defer mig.Close()
logger := &logger{logs: make([]string, 0)}
mig.Log = logger
if err := mig.Migrate(uint(version)); err != nil {
if errors.Is(err, migrate.ErrNoChange) {
return []string{err.Error()}, nil
}
meta.WithAttribute(ctx, "migrate.error", err.Error())
return nil, ErrInvalidMigration
}
return logger.logs, nil
}
// Ping the migrator.
func (m *Migrator) Ping(ctx context.Context, source, db string) error {
mig, err := migrate.New(source, db)
if err != nil {
meta.WithAttribute(ctx, "ping.error", err.Error())
return ErrInvalidConfig
}
if _, _, err := mig.Version(); err != nil && !errors.Is(err, migrate.ErrNilVersion) {
meta.WithAttribute(ctx, "ping.error", err.Error())
return ErrInvalidPing
}
return nil
}