-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pgmigration.go
98 lines (90 loc) · 2.2 KB
/
pgmigration.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
package services
import (
"github.com/go-pg/migrations/v8"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
type PGMigration struct {
db *PG
}
func NewPGMigration(db *PG) *PGMigration {
return &PGMigration{db: db}
}
func (s *PGMigration) Run(a ...string) error {
db := s.db.Get()
col := migrations.NewCollection()
col.DiscoverSQLMigrations("migrations")
_, _, err := col.Run(db, "init")
if err != nil {
return errors.Wrap(err, "failed to init DB PGMigrations")
}
oldVersion, newVersion, err := col.Run(db, a...)
if err != nil {
return errors.Wrap(err, "failed to perform PGMigration")
}
if newVersion != oldVersion {
log.Infof("DB migrated from version %d to %d", oldVersion, newVersion)
} else {
log.Infof("DB PGMigration version is %d", oldVersion)
}
return nil
}
func MakePGMigrationCMD() cli.Command {
migrateCmd := cli.Command{
Name: "migrate",
Aliases: []string{"m"},
Usage: "Migrates database",
}
configurePGMigration(&migrateCmd)
return migrateCmd
}
func configurePGMigration(c *cli.Command) {
upCmd := cli.Command{
Name: "up",
Usage: "Runs all available migrations",
Aliases: []string{"u"},
Action: func(c *cli.Context) error {
return pgMigrate(c, "up")
},
}
downCmd := cli.Command{
Name: "down",
Usage: "Reverts last migration",
Aliases: []string{"d"},
Action: func(c *cli.Context) error {
return pgMigrate(c, "down")
},
}
resetCmd := cli.Command{
Name: "reset",
Usage: "Reverts all migrations",
Aliases: []string{"r"},
Action: func(c *cli.Context) error {
return pgMigrate(c, "reset")
},
}
versionCmd := cli.Command{
Name: "version",
Usage: "Prints current db version",
Aliases: []string{"v"},
Action: func(c *cli.Context) error {
return pgMigrate(c, "version")
},
}
c.Subcommands = []cli.Command{upCmd, downCmd, resetCmd, versionCmd}
for k, _ := range c.Subcommands {
configureSubPGMigration(&c.Subcommands[k])
}
}
func configureSubPGMigration(c *cli.Command) {
c.Flags = RegisterPGFlags(c.Flags)
}
func pgMigrate(c *cli.Context, a ...string) error {
// Setting DB
db := NewPG(c)
defer db.Close()
// Setting PGMigrations
m := NewPGMigration(db)
return m.Run(a...)
}