taskcafe/internal/commands/migrate.go

73 lines
1.6 KiB
Go
Raw Permalink Normal View History

2020-07-16 01:20:08 +02:00
package commands
import (
"fmt"
2020-07-16 01:20:08 +02:00
"github.com/spf13/cobra"
"github.com/spf13/viper"
2020-07-16 01:20:08 +02:00
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/httpfs"
2020-07-16 01:20:08 +02:00
"github.com/jmoiron/sqlx"
log "github.com/sirupsen/logrus"
)
// MigrateLog is a logger for go migrate
2020-07-16 01:20:08 +02:00
type MigrateLog struct {
verbose bool
}
// Printf logs to logrus
2020-07-16 01:20:08 +02:00
func (l *MigrateLog) Printf(format string, v ...interface{}) {
log.Printf("%s", v)
}
// Verbose shows if verbose print enabled
func (l *MigrateLog) Verbose() bool {
return l.verbose
}
func newMigrateCmd() *cobra.Command {
c := &cobra.Command{
2020-07-16 01:20:08 +02:00
Use: "migrate",
Short: "Run the database schema migrations",
Long: "Run the database schema migrations",
RunE: func(cmd *cobra.Command, args []string) error {
connection := fmt.Sprintf("user=%s password=%s host=%s dbname=%s sslmode=disable",
viper.GetString("database.user"),
viper.GetString("database.password"),
viper.GetString("database.host"),
viper.GetString("database.name"),
2020-07-16 01:20:08 +02:00
)
db, err := sqlx.Connect("postgres", connection)
if err != nil {
return err
}
defer db.Close()
2020-07-16 01:20:08 +02:00
driver, err := postgres.WithInstance(db.DB, &postgres.Config{})
if err != nil {
return err
}
src, err := httpfs.New(migration, "./")
if err != nil {
return err
}
m, err := migrate.NewWithInstance("httpfs", src, "postgres", driver)
2020-07-16 01:20:08 +02:00
if err != nil {
return err
}
logger := &MigrateLog{}
m.Log = logger
err = m.Up()
if err != nil && err != migrate.ErrNoChange {
2020-07-16 01:20:08 +02:00
return err
}
return nil
},
}
return c
2020-07-16 01:20:08 +02:00
}