-
Notifications
You must be signed in to change notification settings - Fork 1
/
migration.go
75 lines (59 loc) · 1.49 KB
/
migration.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
package migrationkit
import (
"context"
"errors"
"os"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/tsw303005/Dcard-URL-Shortener/pkg/logkit"
"go.uber.org/zap"
)
type MigrationConfig struct {
// Source is the migration files source directory,
Source string `long:"source" env:"SOURCE" description:"the migration files source directory" required:"true"`
// URL is the migration database URL,
URL string `long:"url" env:"URL" description:"the database url" required:"true"`
}
type Migration struct {
*migrate.Migrate
logger *logkit.Logger
}
func (m *Migration) Up() error {
if err := m.Migrate.Up(); err != nil {
if errors.Is(err, migrate.ErrNoChange) {
m.logger.Info("no change to migrate")
return nil
}
return err
}
return nil
}
func (m *Migration) Close() error {
serr, derr := m.Migrate.Close()
if serr != nil {
return serr
}
if derr != nil {
return derr
}
return nil
}
func NewMigration(ctx context.Context, conf *MigrationConfig) *Migration {
if url := os.ExpandEnv(conf.URL); url != "" {
conf.URL = url
}
logger := logkit.FromContext(ctx).With(
zap.String("source", conf.Source),
zap.String("url", conf.URL),
)
m, err := migrate.New(conf.Source, conf.URL)
if err != nil {
logger.Fatal("failed to create migration", zap.Error(err))
}
logger.Info("create migration successfully")
return &Migration{
Migrate: m,
logger: logger,
}
}