Allow migrating up and down
Some checks failed
ci/woodpecker/push/test Pipeline failed
ci/woodpecker/push/deploy unknown status

This commit is contained in:
Melora Hugues 2024-08-16 11:28:32 +02:00
parent d5aa640df0
commit c81eeef4b2
2 changed files with 41 additions and 5 deletions

View file

@ -2,6 +2,7 @@ package db
import ( import (
"fmt" "fmt"
"strconv"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils" "git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config" "git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
@ -19,13 +20,40 @@ var migrateCmd = &cobra.Command{
Long: `Run the database migrations.`, Long: `Run the database migrations.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
conf := utils.InitConfig("") conf := utils.InitConfig("")
if err := runMigrations(conf); err != nil { up, nbSteps := parseArgs(args)
if err := runMigrations(conf, up, nbSteps); err != nil {
utils.Failf("Failed to run migrations: %s", err.Error()) utils.Failf("Failed to run migrations: %s", err.Error())
} }
}, },
} }
func runMigrations(conf *config.AppConfig) error { func parseArgs(args []string) (bool, int) {
if len(args) == 0 {
return true, 0
}
var actionUp bool
switch args[0] {
case "up":
actionUp = true
case "down":
actionUp = false
default:
actionUp = true
}
nbSteps := 0
if len(args) > 1 {
var err error
nbSteps, err = strconv.Atoi(args[1])
if err != nil {
return actionUp, 0
}
}
return actionUp, nbSteps
}
func runMigrations(conf *config.AppConfig, up bool, nbSteps int) error {
storage, err := db.New(*conf) storage, err := db.New(*conf)
if err != nil { if err != nil {
return fmt.Errorf("failed to connect to db: %w", err) return fmt.Errorf("failed to connect to db: %w", err)
@ -39,10 +67,18 @@ func runMigrations(conf *config.AppConfig) error {
if err != nil { if err != nil {
return fmt.Errorf("failed to init migrator: %w", err) return fmt.Errorf("failed to init migrator: %w", err)
} }
if err := m.Up(); err != nil {
return fmt.Errorf("failed to run migrations: %w", err) if nbSteps > 0 {
multiplier := 1
if !up {
multiplier = -1
} }
return nil return m.Steps(multiplier * nbSteps)
}
if up {
return m.Up()
}
return m.Down()
} }
func init() { func init() {

Binary file not shown.