feat/epic-48-replace-dex #20

Merged
faercol merged 20 commits from feat/epic-48-replace-dex into main 2024-10-27 15:16:40 +00:00
2 changed files with 41 additions and 5 deletions
Showing only changes of commit 9ba477174d - Show all commits

View file

@ -2,6 +2,7 @@ package db
import (
"fmt"
"strconv"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
@ -19,13 +20,40 @@ var migrateCmd = &cobra.Command{
Long: `Run the database migrations.`,
Run: func(cmd *cobra.Command, args []string) {
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())
}
},
}
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)
if err != nil {
return fmt.Errorf("failed to connect to db: %w", err)
@ -39,10 +67,18 @@ func runMigrations(conf *config.AppConfig) error {
if err != nil {
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() {

Binary file not shown.