/
up.go
103 lines (78 loc) · 2.6 KB
/
up.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
99
100
101
102
103
package migrate
import (
"fmt"
"github.com/ory/x/cmdx"
"github.com/ory/x/flagx"
"github.com/ory/x/popx"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/ory/keto/internal/driver"
"github.com/ory/keto/ketoctx"
)
const (
FlagYes = "yes"
)
func newUpCmd(opts []ketoctx.Option) *cobra.Command {
cmd := &cobra.Command{
Use: "up",
Short: "Migrate the database up",
Long: `Run this command on a fresh SQL installation and when you upgrade Ory Keto from version v0.7.x and later.
It is recommended to run this command close to the SQL instance (e.g. same subnet) instead of over the public internet.
This decreases risk of failure and decreases time required.
### WARNING ###
Before running this command on an existing database, create a back up!
`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
reg, err := driver.NewDefaultRegistry(ctx, cmd.Flags(), true, opts...)
if err != nil {
return err
}
mb, err := reg.MigrationBox(ctx)
if err != nil {
return err
}
if err := BoxUp(cmd, mb); err != nil {
return err
}
return nil
},
}
RegisterYesFlag(cmd.Flags())
cmdx.RegisterFormatFlags(cmd.Flags())
return cmd
}
func RegisterYesFlag(flags *pflag.FlagSet) {
flags.BoolP(FlagYes, "y", false, "yes to all questions, no user input required")
}
func BoxUp(cmd *cobra.Command, mb *popx.MigrationBox) error {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Current status:")
s, err := mb.Status(cmd.Context())
if err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not get migration status: %+v\n", err)
return cmdx.FailSilently(cmd)
}
cmdx.PrintTable(cmd, s)
if !s.HasPending() {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "All migrations are already applied, there is nothing to do.")
return nil
}
if !flagx.MustGetBool(cmd, FlagYes) && !cmdx.AskForConfirmation("Are you sure that you want to apply this migration? Make sure to check the CHANGELOG.md for breaking changes beforehand.", cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Aborting")
return nil
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Applying migrations...")
if err := mb.Up(cmd.Context()); err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not apply migrations: %+v\n", err)
return cmdx.FailSilently(cmd)
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Successfully applied all migrations:")
s, err = mb.Status(cmd.Context())
if err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not get migration status: %+v\n", err)
return cmdx.FailSilently(cmd)
}
cmdx.PrintTable(cmd, s)
return nil
}