From c81eeef4b21b83321c436269540b78dbf15e0959 Mon Sep 17 00:00:00 2001 From: Melora Hugues Date: Fri, 16 Aug 2024 11:28:32 +0200 Subject: [PATCH] Allow migrating up and down --- polyculeconnect/cmd/db/migrate.go | 46 +++++++++++++++++++++++++---- polyculeconnect/polyculeconnect.db | Bin 98304 -> 118784 bytes 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/polyculeconnect/cmd/db/migrate.go b/polyculeconnect/cmd/db/migrate.go index 92ca2de..bf5749f 100644 --- a/polyculeconnect/cmd/db/migrate.go +++ b/polyculeconnect/cmd/db/migrate.go @@ -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 m.Steps(multiplier * nbSteps) } - return nil + if up { + return m.Up() + } + return m.Down() } func init() { diff --git a/polyculeconnect/polyculeconnect.db b/polyculeconnect/polyculeconnect.db index 2708fa48bd056ecba49f0434efc9f22189d9f006..870928863414f696e7ae1b0d6937a641a3e79dbd 100644 GIT binary patch delta 576 zcmZo@U~5>wK0#Vgnt_2q7KmX$exi;sqjY1!)&#~S{u)AT&lvcR@{933<-N?iisu5) zMD8=(Gr4NG>^Y`#{^QVM-_7=ny@x$^v!cK*w)#>Dc5!KG#zx1I#H5_mq{QUx)VvfZ zCG8yK>KNjx5aQ_M%2=erG42o3nc8$~l ztH?{tO+`}^>gO34>dK|5E5#=6D9y+)*_cmE9BOd95tJdTD+!XFY{(~350f*5GGuba z*~K;W85{XC^HNeP%2JDpGxPJ}OY<@dOH+%JGg5OC<8w39ixNwK!o^ZhA3&^C@bq(W zjZi?^Y`#{@bi5P|UG?Y6N4pIsmz96kPxS