-
Notifications
You must be signed in to change notification settings - Fork 522
/
migrate.go
373 lines (340 loc) · 10.7 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package goose
import (
"context"
"database/sql"
"errors"
"fmt"
"io/fs"
"math"
"path"
"sort"
"strings"
"time"
)
var (
// ErrNoMigrationFiles when no migration files have been found.
ErrNoMigrationFiles = errors.New("no migration files found")
// ErrNoCurrentVersion when a current migration version is not found.
ErrNoCurrentVersion = errors.New("no current version found")
// ErrNoNextVersion when the next migration version is not found.
ErrNoNextVersion = errors.New("no next version found")
// MaxVersion is the maximum allowed version.
MaxVersion int64 = math.MaxInt64
)
// Migrations slice.
type Migrations []*Migration
// helpers so we can use pkg sort
func (ms Migrations) Len() int { return len(ms) }
func (ms Migrations) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
func (ms Migrations) Less(i, j int) bool {
if ms[i].Version == ms[j].Version {
panic(fmt.Sprintf("goose: duplicate version %v detected:\n%v\n%v", ms[i].Version, ms[i].Source, ms[j].Source))
}
return ms[i].Version < ms[j].Version
}
// Current gets the current migration.
func (ms Migrations) Current(current int64) (*Migration, error) {
for i, migration := range ms {
if migration.Version == current {
return ms[i], nil
}
}
return nil, ErrNoCurrentVersion
}
// Next gets the next migration.
func (ms Migrations) Next(current int64) (*Migration, error) {
for i, migration := range ms {
if migration.Version > current {
return ms[i], nil
}
}
return nil, ErrNoNextVersion
}
// Previous : Get the previous migration.
func (ms Migrations) Previous(current int64) (*Migration, error) {
for i := len(ms) - 1; i >= 0; i-- {
if ms[i].Version < current {
return ms[i], nil
}
}
return nil, ErrNoNextVersion
}
// Last gets the last migration.
func (ms Migrations) Last() (*Migration, error) {
if len(ms) == 0 {
return nil, ErrNoNextVersion
}
return ms[len(ms)-1], nil
}
// Versioned gets versioned migrations.
func (ms Migrations) versioned() (Migrations, error) {
var migrations Migrations
// assume that the user will never have more than 19700101000000 migrations
for _, m := range ms {
// parse version as timestamp
versionTime, err := time.Parse(timestampFormat, fmt.Sprintf("%d", m.Version))
if versionTime.Before(time.Unix(0, 0)) || err != nil {
migrations = append(migrations, m)
}
}
return migrations, nil
}
// Timestamped gets the timestamped migrations.
func (ms Migrations) timestamped() (Migrations, error) {
var migrations Migrations
// assume that the user will never have more than 19700101000000 migrations
for _, m := range ms {
// parse version as timestamp
versionTime, err := time.Parse(timestampFormat, fmt.Sprintf("%d", m.Version))
if err != nil {
// probably not a timestamp
continue
}
if versionTime.After(time.Unix(0, 0)) {
migrations = append(migrations, m)
}
}
return migrations, nil
}
func (ms Migrations) String() string {
str := ""
for _, m := range ms {
str += fmt.Sprintln(m)
}
return str
}
func collectMigrationsFS(
fsys fs.FS,
dirpath string,
current, target int64,
registered map[int64]*Migration,
) (Migrations, error) {
if _, err := fs.Stat(fsys, dirpath); err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("%s directory does not exist", dirpath)
}
return nil, err
}
var migrations Migrations
// SQL migration files.
sqlMigrationFiles, err := fs.Glob(fsys, path.Join(dirpath, "*.sql"))
if err != nil {
return nil, err
}
for _, file := range sqlMigrationFiles {
v, err := NumericComponent(file)
if err != nil {
return nil, fmt.Errorf("could not parse SQL migration file %q: %w", file, err)
}
if versionFilter(v, current, target) {
migrations = append(migrations, &Migration{
Version: v,
Next: -1,
Previous: -1,
Source: file,
})
}
}
// Go migration files.
goMigrations, err := collectGoMigrations(fsys, dirpath, registered, current, target)
if err != nil {
return nil, err
}
migrations = append(migrations, goMigrations...)
if len(migrations) == 0 {
return nil, ErrNoMigrationFiles
}
return sortAndConnectMigrations(migrations), nil
}
// CollectMigrations returns all the valid looking migration scripts in the
// migrations folder and go func registry, and key them by version.
func CollectMigrations(dirpath string, current, target int64) (Migrations, error) {
return collectMigrationsFS(baseFS, dirpath, current, target, registeredGoMigrations)
}
func sortAndConnectMigrations(migrations Migrations) Migrations {
sort.Sort(migrations)
// now that we're sorted in the appropriate direction,
// populate next and previous for each migration
for i, m := range migrations {
prev := int64(-1)
if i > 0 {
prev = migrations[i-1].Version
migrations[i-1].Next = m.Version
}
migrations[i].Previous = prev
}
return migrations
}
func versionFilter(v, current, target int64) bool {
if target > current {
return v > current && v <= target
}
if target < current {
return v <= current && v > target
}
return false
}
// EnsureDBVersion retrieves the current version for this DB.
// Create and initialize the DB version table if it doesn't exist.
func EnsureDBVersion(db *sql.DB) (int64, error) {
ctx := context.Background()
return EnsureDBVersionContext(ctx, db)
}
// EnsureDBVersionContext retrieves the current version for this DB.
// Create and initialize the DB version table if it doesn't exist.
func EnsureDBVersionContext(ctx context.Context, db *sql.DB) (int64, error) {
dbMigrations, err := store.ListMigrations(ctx, db, TableName())
if err != nil {
return 0, createVersionTable(ctx, db)
}
// The most recent record for each migration specifies
// whether it has been applied or rolled back.
// The first version we find that has been applied is the current version.
//
// TODO(mf): for historic reasons, we continue to use the is_applied column,
// but at some point we need to deprecate this logic and ideally remove
// this column.
//
// For context, see:
// https://github.com/pressly/goose/pull/131#pullrequestreview-178409168
//
// The dbMigrations list is expected to be ordered by descending ID. But
// in the future we should be able to query the last record only.
skipLookup := make(map[int64]struct{})
for _, m := range dbMigrations {
// Have we already marked this version to be skipped?
if _, ok := skipLookup[m.VersionID]; ok {
continue
}
// If version has been applied we are done.
if m.IsApplied {
return m.VersionID, nil
}
// Latest version of migration has not been applied.
skipLookup[m.VersionID] = struct{}{}
}
return 0, ErrNoNextVersion
}
// createVersionTable creates the db version table and inserts the
// initial 0 value into it.
func createVersionTable(ctx context.Context, db *sql.DB) error {
txn, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := store.CreateVersionTable(ctx, txn, TableName()); err != nil {
_ = txn.Rollback()
return err
}
if err := store.InsertVersion(ctx, txn, TableName(), 0); err != nil {
_ = txn.Rollback()
return err
}
return txn.Commit()
}
// GetDBVersion is an alias for EnsureDBVersion, but returns -1 in error.
func GetDBVersion(db *sql.DB) (int64, error) {
ctx := context.Background()
return GetDBVersionContext(ctx, db)
}
// GetDBVersionContext is an alias for EnsureDBVersion, but returns -1 in error.
func GetDBVersionContext(ctx context.Context, db *sql.DB) (int64, error) {
version, err := EnsureDBVersionContext(ctx, db)
if err != nil {
return -1, err
}
return version, nil
}
// collectGoMigrations collects Go migrations from the filesystem and merges them with registered
// migrations.
//
// If Go migrations have been registered globally, with [goose.AddNamedMigration...], but there are
// no corresponding .go files in the filesystem, add them to the migrations slice.
//
// If Go migrations have been registered, and there are .go files in the filesystem dirpath, ONLY
// include those in the migrations slices.
//
// Lastly, if there are .go files in the filesystem but they have not been registered, raise an
// error. This is to prevent users from accidentally adding valid looking Go files to the migrations
// folder without registering them.
func collectGoMigrations(
fsys fs.FS,
dirpath string,
registeredGoMigrations map[int64]*Migration,
current, target int64,
) (Migrations, error) {
// Sanity check registered migrations have the correct version prefix.
for _, m := range registeredGoMigrations {
if _, err := NumericComponent(m.Source); err != nil {
return nil, fmt.Errorf("could not parse go migration file %s: %w", m.Source, err)
}
}
goFiles, err := fs.Glob(fsys, path.Join(dirpath, "*.go"))
if err != nil {
return nil, err
}
// If there are no Go files in the filesystem and no registered Go migrations, return early.
if len(goFiles) == 0 && len(registeredGoMigrations) == 0 {
return nil, nil
}
type source struct {
fullpath string
version int64
}
// Find all Go files that have a version prefix and are within the requested range.
var sources []source
for _, fullpath := range goFiles {
v, err := NumericComponent(fullpath)
if err != nil {
continue // Skip any files that don't have version prefix.
}
if strings.HasSuffix(fullpath, "_test.go") {
continue // Skip Go test files.
}
if versionFilter(v, current, target) {
sources = append(sources, source{
fullpath: fullpath,
version: v,
})
}
}
var (
migrations Migrations
)
if len(sources) > 0 {
for _, s := range sources {
migration, ok := registeredGoMigrations[s.version]
if ok {
migrations = append(migrations, migration)
} else {
// TODO(mf): something that bothers me about this implementation is it will be
// lazily evaluated and the error will only be raised if the user tries to run the
// migration. It would be better to raise an error much earlier in the process.
migrations = append(migrations, &Migration{
Version: s.version,
Next: -1,
Previous: -1,
Source: s.fullpath,
Registered: false,
})
}
}
} else {
// Some users may register Go migrations manually via AddNamedMigration_ functions but not
// provide the corresponding .go files in the filesystem. In this case, we include them
// wholesale in the migrations slice.
//
// This is a valid use case because users may want to build a custom binary that only embeds
// the SQL migration files and some other mechanism for registering Go migrations.
for _, migration := range registeredGoMigrations {
v, err := NumericComponent(migration.Source)
if err != nil {
return nil, fmt.Errorf("could not parse go migration file %s: %w", migration.Source, err)
}
if versionFilter(v, current, target) {
migrations = append(migrations, migration)
}
}
}
return migrations, nil
}