-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate.go
213 lines (176 loc) · 4.31 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/go-logr/logr"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/sqlite3"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/spf13/cobra"
)
const (
tableNameMigrations = "__sqlite_rest_migrations"
migrationDirectionUp = "up"
migrationDirectionDown = "down"
migrationStepAll = -1
)
func isApplyAllStep(step int) bool {
return step <= 0
}
func createMigrateCmd() *cobra.Command {
var (
flagDirection string
flagStep int
)
cmd := &cobra.Command{
Use: "migrate migrations-dir",
Short: "Apply database migrations",
SilenceUsage: true,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
logger, err := createLogger(cmd)
if err != nil {
setupLogger.Error(err, "failed to create logger")
return err
}
db, err := openDB(cmd)
if err != nil {
setupLogger.Error(err, "create db")
return err
}
defer db.Close()
opts := &MigrateOptions{
Logger: logger,
DB: db.DB,
SourceDIR: args[0],
}
migrator, err := NewMigrator(opts)
if err != nil {
setupLogger.Error(err, "failed to create migrator")
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var migrateErr error
switch flagDirection {
case migrationDirectionUp:
migrateErr = migrator.Up(ctx, flagStep)
case migrationDirectionDown:
migrateErr = migrator.Down(ctx, flagStep)
default:
// defaults to up
migrateErr = migrator.Up(ctx, flagStep)
}
if migrateErr != nil {
return migrateErr
}
return nil
},
}
bindDBDSNFlag(cmd.Flags())
return cmd
}
type MigrateOptions struct {
Logger logr.Logger
DB *sql.DB
SourceDIR string
}
func (opts *MigrateOptions) defaults() error {
if opts.Logger.GetSink() == nil {
opts.Logger = logr.Discard()
}
if opts.DB == nil {
return fmt.Errorf(".DB is required")
}
if opts.SourceDIR == "" {
return fmt.Errorf(".SourceDIR is required")
}
if s, err := filepath.Abs(opts.SourceDIR); err == nil {
opts.SourceDIR = s
} else {
return fmt.Errorf("failed to resolve SourceDIR %q: %w", opts.SourceDIR, err)
}
stat, err := os.Stat(opts.SourceDIR)
if err != nil {
return fmt.Errorf("%s: %w", opts.SourceDIR, err)
}
if !stat.IsDir() {
return fmt.Errorf("migrations source dir %q is not a dir", opts.SourceDIR)
}
return nil
}
type dbMigrator struct {
logger logr.Logger
migrator *migrate.Migrate
}
func NewMigrator(opts *MigrateOptions) (*dbMigrator, error) {
if err := opts.defaults(); err != nil {
return nil, err
}
driver, err := sqlite3.WithInstance(opts.DB, &sqlite3.Config{
MigrationsTable: tableNameMigrations,
})
if err != nil {
return nil, err
}
migrator, err := migrate.NewWithDatabaseInstance(
"file://"+opts.SourceDIR,
"sqlite3", driver,
)
if err != nil {
return nil, err
}
rv := &dbMigrator{
logger: opts.Logger.WithName("db-migrator"),
migrator: migrator,
}
return rv, nil
}
func handleMigrateError(logger logr.Logger, op string, migrateErr error) error {
if migrateErr == nil {
logger.Info("applied operation")
return nil
}
if errors.Is(migrateErr, migrate.ErrNoChange) {
// no update
logger.V(8).Info("no pending migrations")
return nil
}
var pathErr *fs.PathError
if errors.As(migrateErr, &pathErr) {
// no migrations set
if pathErr.Op == "first" && errors.Is(pathErr.Err, fs.ErrNotExist) {
logger.Info("no migrations to apply")
return nil
}
}
logger.Error(migrateErr, "failed to apply operation")
return fmt.Errorf("%s: %w", op, migrateErr)
}
func (m *dbMigrator) Up(ctx context.Context, step int) error {
logger := m.logger.WithName("up")
logger.Info("applying operation")
var migrateErr error
if isApplyAllStep(step) {
migrateErr = m.migrator.Up()
} else {
migrateErr = m.migrator.Steps(step)
}
return handleMigrateError(logger, "up", migrateErr)
}
func (m *dbMigrator) Down(ctx context.Context, step int) error {
logger := m.logger.WithName("down")
logger.Info("applying operation")
var migrateErr error
if isApplyAllStep(step) {
migrateErr = m.migrator.Down()
} else {
migrateErr = m.migrator.Steps(-step)
}
return handleMigrateError(logger, "up", migrateErr)
}