-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
migrate.go
264 lines (201 loc) · 6.53 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package migrate
import (
"errors"
"fmt"
"sort"
"github.com/rs/zerolog/log"
)
var errNoMigrationVersion = errors.New("migration version not found")
// InfoLogger defines info level logger, passes go-sprintf-friendly format & arguments.
type InfoLogger func(format string, args ...interface{})
// Options define applied migrations options and behavior.
type Options struct {
// DatabaseURI is the database connection string. Format 'postgres://user:password@host:port/database?sslmode=disable'.
DatabaseURI string
// VersionNumberToApply defines target version for migration actions.
VersionNumberToApply uint
// PrintInfoAndExit controls whether the migration should do an early exit after printing out current version info.
PrintInfoAndExit bool
// ForceVersionWithoutMigrations allows to force specific migration version without actually applying the migrations.
ForceVersionWithoutMigrations bool
// RefreshSchema drops and recreates public schema.
RefreshSchema bool
// SchemasToRefresh drops & recreates specified schemas.
SchemasToRefresh []string
// LogInfo handles info logging
LogInfo InfoLogger
}
type migrationTask struct {
migrations []*migration
repo repository
opt Options
}
type Migrate struct {
task *migrationTask
}
// Migrate executes actual migrations based on the specified options.
func (m Migrate) Migrate() error {
return m.task.migrate()
}
// New creates new migration instance.
//
func New(opt Options) (*Migrate, error) {
if err := validateMigrations(migrations); err != nil {
return nil, err
}
if opt.LogInfo == nil {
opt.LogInfo = func(format string, args ...interface{}) {
log.Info().Msgf(format, args...)
}
}
repo, err := newRepo(opt.DatabaseURI)
if err != nil {
return nil, err
}
return &Migrate{
task: &migrationTask{
migrations: mapMigrations(migrations),
repo: repo,
opt: opt,
},
}, nil
}
// Migrate applies actual migrations based on the specified options.
func (m *migrationTask) migrate() error {
if err := m.performPreMigrationTask(); err != nil {
return fmt.Errorf("failed to perform pre-migration task: %w", err)
}
if m.opt.ForceVersionWithoutMigrations {
return m.handleForceVersionWithoutMigrations()
}
lastAppliedMigrationNumber, err := m.repo.GetLatestMigrationNumber()
if err != nil {
return fmt.Errorf("failed to get the number of the latest migration: %w", err)
}
if m.opt.PrintInfoAndExit {
m.opt.LogInfo("currently applied version: %d", lastAppliedMigrationNumber)
return nil
}
if err := m.applyMigrations(lastAppliedMigrationNumber); err != nil {
return fmt.Errorf("failed to apply migrations: %w", err)
}
return nil
}
func (m *migrationTask) performPreMigrationTask() error {
switch {
case m.opt.RefreshSchema:
if err := m.refreshSchema("public"); err != nil {
return fmt.Errorf("refreshing schema 'public': %w", err)
}
case len(m.opt.SchemasToRefresh) > 0:
for _, schemaName := range m.opt.SchemasToRefresh {
if err := m.refreshSchema(schemaName); err != nil {
return fmt.Errorf("refreshing schema %s: %w", schemaName, err)
}
}
default:
err := m.repo.EnsureMigrationTable()
if err != nil {
return fmt.Errorf("failed to automatically Migrate migrations table: %w", err)
}
}
return nil
}
func (m *migrationTask) handleForceVersionWithoutMigrations() error {
for _, migration := range m.migrations {
if migration.Number != m.opt.VersionNumberToApply {
continue
}
if err := m.repo.RemoveMigrationsAfter(migration.Number); err != nil {
return fmt.Errorf("failed to remove migrations: %w", err)
}
if err := m.repo.InsertMigration(migration); err != nil {
return fmt.Errorf("failed insert migration: %w", err)
}
return nil
}
return errNoMigrationVersion
}
func (m *migrationTask) refreshSchema(schemaName string) error {
m.opt.LogInfo("refreshing database")
err := m.repo.DropSchema(schemaName)
if err != nil {
return fmt.Errorf("failed to DropSchema (running with 'refresh' flag): %w", err)
}
m.opt.LogInfo("ensuring migrations table is present")
err = m.repo.EnsureMigrationTable()
if err != nil {
return fmt.Errorf("failed to automatically Migrate migrations table: %w", err)
}
return nil
}
func (m *migrationTask) applyMigrations(lastAppliedMigrationNumber uint) error {
if len(m.migrations) == 0 {
m.opt.LogInfo("no migrations to apply.")
return nil
}
if m.opt.VersionNumberToApply == 0 {
m.opt.VersionNumberToApply = m.getLastMigrationNumber()
}
if m.opt.VersionNumberToApply < lastAppliedMigrationNumber {
return m.applyBackwardMigrations(lastAppliedMigrationNumber)
}
return m.applyForwardMigrations(lastAppliedMigrationNumber)
}
func (m *migrationTask) applyBackwardMigrations(lastAppliedMigrationNumber uint) error {
m.sortMigrationsDesc()
for _, migration := range m.migrations {
if migration.Number > lastAppliedMigrationNumber {
continue
}
if migration.Number <= m.opt.VersionNumberToApply {
break
}
m.opt.LogInfo("applying backwards migration %d (%s)", migration.Number, migration.Name)
if err := m.repo.ApplyMigration(migration.Backwards); err != nil {
return fmt.Errorf("failed to apply the migration (BackwardMigration): %w", err)
}
if err := m.repo.RemoveMigrationsAfter(migration.Number); err != nil {
return fmt.Errorf("failed to remove migrations: %w", err)
}
}
return nil
}
func (m *migrationTask) applyForwardMigrations(lastAppliedMigrationNumber uint) error {
m.sortMigrationsAsc()
for _, migration := range m.migrations {
if migration.Number <= lastAppliedMigrationNumber {
continue
}
if migration.Number > m.opt.VersionNumberToApply && m.opt.VersionNumberToApply != 0 {
break
}
m.opt.LogInfo("applying forward migration %d (%s)", migration.Number, migration.Name)
if err := m.repo.ApplyMigration(migration.Forwards); err != nil {
return fmt.Errorf("failed to apply the migration (ForwardMigration): %w", err)
}
if err := m.repo.InsertMigration(migration); err != nil {
return fmt.Errorf("failed to create migration record: %w", err)
}
}
return nil
}
func (m *migrationTask) sortMigrationsAsc() {
sort.SliceStable(m.migrations, func(i, j int) bool {
return m.migrations[i].Number < m.migrations[j].Number
})
}
func (m *migrationTask) sortMigrationsDesc() {
sort.SliceStable(m.migrations, func(i, j int) bool {
return m.migrations[i].Number > m.migrations[j].Number
})
}
func (m *migrationTask) getLastMigrationNumber() uint {
var lastNumber uint
for i := range m.migrations {
if m.migrations[i].Number > lastNumber {
lastNumber = m.migrations[i].Number
}
}
return lastNumber
}