github.com/retailcrm/mg-bot-helper@v0.0.0-20201229112329-a17255681a84/src/migrate.go (about) 1 package main 2 3 import ( 4 "errors" 5 "fmt" 6 "strconv" 7 8 "github.com/golang-migrate/migrate" 9 ) 10 11 func init() { 12 parser.AddCommand("migrate", 13 "Migrate database to defined migrations version", 14 "Migrate database to defined migrations version.", 15 &MigrateCommand{}, 16 ) 17 } 18 19 // MigrateCommand struct 20 type MigrateCommand struct { 21 Version string `short:"v" long:"version" default:"up" description:"Migrate to defined migrations version. Allowed: up, down, next, prev and integer value."` 22 Path string `short:"p" long:"path" default:"" description:"Path to migrations files."` 23 } 24 25 // Execute method 26 func (x *MigrateCommand) Execute(args []string) error { 27 botConfig := LoadConfig(options.Config) 28 29 err := Migrate(botConfig.Database.Connection, x.Version, x.Path) 30 if err != nil && err.Error() == "no change" { 31 fmt.Println("No changes detected. Skipping migration.") 32 err = nil 33 } 34 35 return err 36 } 37 38 // Migrate function 39 func Migrate(database string, version string, path string) error { 40 m, err := migrate.New("file://"+path, database) 41 if err != nil { 42 fmt.Printf("Migrations path %s does not exist or permission denied\n", path) 43 return err 44 } 45 46 defer m.Close() 47 48 currentVersion, _, err := m.Version() 49 if "up" == version { 50 fmt.Printf("Migrating from %d to last\n", currentVersion) 51 return m.Up() 52 } 53 54 if "down" == version { 55 fmt.Printf("Migrating from %d to 0\n", currentVersion) 56 return m.Down() 57 } 58 59 if "next" == version { 60 fmt.Printf("Migrating from %d to next\n", currentVersion) 61 return m.Steps(1) 62 } 63 64 if "prev" == version { 65 fmt.Printf("Migrating from %d to previous\n", currentVersion) 66 return m.Steps(-1) 67 } 68 69 ver, err := strconv.ParseUint(version, 10, 32) 70 if err != nil { 71 fmt.Printf("Invalid migration version %s\n", version) 72 return err 73 } 74 75 if ver != 0 { 76 fmt.Printf("Migrating from %d to %d\n", currentVersion, ver) 77 return m.Migrate(uint(ver)) 78 } 79 80 fmt.Printf("Migrations not found in path %s\n", path) 81 82 return errors.New("migrations not found") 83 }