-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_migrate.go
92 lines (75 loc) · 2.28 KB
/
cmd_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
85
86
87
88
89
90
91
92
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"path/filepath"
"github.com/google/subcommands"
"github.com/jacobbrewer1/goschema/pkg/migrations"
)
type migrateCmd struct {
// up is the flag to migrate up.
up bool
// down is the flag to migrate down.
down bool
// migrationLocation is where the migrations are located.
migrationLocation string
// steps is the number of steps to migrate.
steps int
}
func (m *migrateCmd) Name() string {
return "migrate"
}
func (m *migrateCmd) Synopsis() string {
return "Migrate the database"
}
func (m *migrateCmd) Usage() string {
return `migrate:
Migrate the database.
`
}
func (m *migrateCmd) SetFlags(f *flag.FlagSet) {
f.BoolVar(&m.up, "up", false, "Migrate up.")
f.BoolVar(&m.down, "down", false, "Migrate down.")
f.StringVar(&m.migrationLocation, "loc", ".", "The location of the migrations.")
f.IntVar(&m.steps, "steps", 0, "The number of steps to migrate (0 means all).")
}
func (m *migrateCmd) Execute(ctx context.Context, _ *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
if m.up && m.down {
slog.Error("Cannot migrate up and down at the same time")
return subcommands.ExitUsageError
} else if !m.up && !m.down {
slog.Error("Must specify up or down")
return subcommands.ExitUsageError
}
if e := os.Getenv(migrations.DbEnvVar); e == "" {
slog.Error(fmt.Sprintf("Environment variable %s is not set", migrations.DbEnvVar))
return subcommands.ExitFailure
}
absPath, err := filepath.Abs(m.migrationLocation)
if err != nil {
slog.Error("Error getting absolute path", slog.String("error", err.Error()))
return subcommands.ExitFailure
}
db, err := migrations.ConnectDB()
if err != nil {
slog.Error("Error connecting to the database", slog.String("error", err.Error()))
return subcommands.ExitFailure
}
switch {
case m.up:
if err := migrations.NewVersioning(db, absPath, m.steps).MigrateUp(); err != nil {
slog.Error("Error migrating up", slog.String("error", err.Error()))
return subcommands.ExitFailure
}
case m.down:
if err := migrations.NewVersioning(db, absPath, m.steps).MigrateDown(); err != nil {
slog.Error("Error migrating down", slog.String("error", err.Error()))
return subcommands.ExitFailure
}
}
slog.Info("Migration complete")
return subcommands.ExitSuccess
}