From 1a51ec2e964cf07e608af262f162034dc7594233 Mon Sep 17 00:00:00 2001 From: "Vojtech Vitek (V-Teq)" Date: Mon, 20 Jun 2016 15:24:25 -0400 Subject: [PATCH] Add up-by-one goose command --- goose.go | 4 ++++ migrate.go | 31 +++++++++++++++++++++++++++++++ up.go | 14 ++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/goose.go b/goose.go index 21039bb..1f2a75b 100644 --- a/goose.go +++ b/goose.go @@ -11,6 +11,10 @@ func Run(command string, db *sql.DB, dir string) error { if err := Up(db, dir); err != nil { return err } + case "up-by-one": + if err := UpByOne(db, dir); err != nil { + return err + } case "down": if err := Down(db, dir); err != nil { return err diff --git a/migrate.go b/migrate.go index c1f8fa4..c0bb42a 100644 --- a/migrate.go +++ b/migrate.go @@ -17,6 +17,7 @@ import ( var ( ErrNoPreviousVersion = errors.New("no previous version found") + ErrNoNextVersion = errors.New("no next version found") goMigrations []*Migration ) @@ -56,6 +57,11 @@ func RunMigrations(db *sql.DB, dir string, target int64) (err error) { return err } + if current == target { + fmt.Printf("goose: no migrations to run. current version: %d. target version: %d\n", current, target) + return nil + } + migrations, err := CollectMigrations(dir, current, target) if err != nil { return err @@ -322,6 +328,31 @@ func GetPreviousDBVersion(dirpath string, version int64) (previous int64, err er return } +func GetNextDBVersion(dirpath string, version int64) (next int64, err error) { + + next = 9223372036854775807 // max(int64) + + filepath.Walk(dirpath, func(name string, info os.FileInfo, walkerr error) error { + + if !info.IsDir() { + if v, e := NumericComponent(name); e == nil { + if v < next && v > version { + next = v + } + } + } + + return nil + }) + + if next == 9223372036854775807 { + next = version + err = ErrNoNextVersion + } + + return +} + // helper to identify the most recent possible version // within a folder of migration scripts func GetMostRecentDBVersion(dirpath string) (version int64, err error) { diff --git a/up.go b/up.go index 79c9807..6788164 100644 --- a/up.go +++ b/up.go @@ -15,3 +15,17 @@ func Up(db *sql.DB, dir string) error { } return nil } + +func UpByOne(db *sql.DB, dir string) error { + current, err := GetDBVersion(db) + if err != nil { + return err + } + + next, _ := GetNextDBVersion(dir, current) + if err = RunMigrations(db, dir, next); err != nil { + return err + } + + return nil +}