2020-07-16 01:20:08 +02:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-08-01 03:01:14 +02:00
|
|
|
|
2020-07-16 01:20:08 +02:00
|
|
|
"github.com/spf13/cobra"
|
2020-08-13 05:17:42 +02:00
|
|
|
"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"
|
2020-07-19 23:10:07 +02:00
|
|
|
"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"
|
|
|
|
)
|
|
|
|
|
2020-08-21 01:11:24 +02:00
|
|
|
// MigrateLog is a logger for go migrate
|
2020-07-16 01:20:08 +02:00
|
|
|
type MigrateLog struct {
|
|
|
|
verbose bool
|
|
|
|
}
|
|
|
|
|
2020-08-21 01:11:24 +02:00
|
|
|
// 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 {
|
2020-08-13 05:17:42 +02:00
|
|
|
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 {
|
2020-10-21 01:52:09 +02:00
|
|
|
connection := fmt.Sprintf("user=%s password=%s host=%s dbname=%s port=%s sslmode=disable",
|
2020-08-13 05:17:42 +02:00
|
|
|
viper.GetString("database.user"),
|
|
|
|
viper.GetString("database.password"),
|
|
|
|
viper.GetString("database.host"),
|
|
|
|
viper.GetString("database.name"),
|
2020-10-21 01:52:09 +02:00
|
|
|
viper.GetString("database.port"),
|
2020-07-16 01:20:08 +02:00
|
|
|
)
|
|
|
|
db, err := sqlx.Connect("postgres", connection)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer db.Close()
|
2020-08-13 05:17:42 +02:00
|
|
|
|
2020-07-16 01:20:08 +02:00
|
|
|
driver, err := postgres.WithInstance(db.DB, &postgres.Config{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-07-19 23:10:07 +02:00
|
|
|
|
2020-08-01 03:01:14 +02:00
|
|
|
src, err := httpfs.New(migration, "./")
|
2020-07-19 23:10:07 +02:00
|
|
|
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()
|
2020-08-13 05:17:42 +02:00
|
|
|
if err != nil && err != migrate.ErrNoChange {
|
2020-07-16 01:20:08 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
2020-08-13 05:17:42 +02:00
|
|
|
return c
|
2020-07-16 01:20:08 +02:00
|
|
|
}
|