Skip to content

Commit

Permalink
fix(migrations): ensure migrations are ran in version order
Browse files Browse the repository at this point in the history
  • Loading branch information
l3uddz committed Apr 13, 2022
1 parent 6746c0e commit 383efb0
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 8 deletions.
9 changes: 5 additions & 4 deletions migrate/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"embed"
"errors"
"fmt"

"github.com/oriser/regroup"
"modernc.org/sqlite"
)
Expand Down Expand Up @@ -63,15 +64,15 @@ func (m *Migrator) Migrate(fs *embed.FS, component string) error {
}

// migrate
for _, migration := range migrations {
for _, mg := range migrations {
// already have this version?
if _, exists := versions[migration.Version]; exists {
if _, exists := versions[mg.Version]; exists {
continue
}

// migrate
if err := m.exec(component, migration); err != nil {
return fmt.Errorf("migrate: %v: %w", migration.Filename, err)
if err := m.exec(component, mg); err != nil {
return fmt.Errorf("migrate: %v: %w", mg.Filename, err)
}
}

Expand Down
12 changes: 9 additions & 3 deletions migrate/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"embed"
"fmt"
"path/filepath"
"sort"
)

type migration struct {
Expand Down Expand Up @@ -77,15 +78,15 @@ func (m *Migrator) exec(component string, migration *migration) (err error) {
return nil
}

func (m *Migrator) parse(fs *embed.FS) (map[int]*migration, error) {
func (m *Migrator) parse(fs *embed.FS) ([]*migration, error) {
// parse migrations from filesystem
files, err := fs.ReadDir(m.dir)
if err != nil {
return nil, fmt.Errorf("read migrations: %w", err)
}

// parse migrations
migrations := make(map[int]*migration)
migrations := make([]*migration, 0)
for _, f := range files {
// skip dirs
if f.IsDir() {
Expand All @@ -106,9 +107,14 @@ func (m *Migrator) parse(fs *embed.FS) (map[int]*migration, error) {
md.Filename = f.Name()

// set migration
migrations[md.Version] = md
migrations = append(migrations, md)
}

// sort migrations
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].Version < migrations[j].Version
})

return migrations, nil
}

Expand Down
1 change: 0 additions & 1 deletion radarr/migrations/1_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@ CREATE TABLE IF NOT EXISTS movies (
"movie" INTEGER NOT NULL,
"release_date" DATETIME NOT NULL,
"search_date" DATETIME NULL,
"type" VARCHAR(10),
PRIMARY KEY(movie)
)
File renamed without changes.

0 comments on commit 383efb0

Please sign in to comment.