/* Package cmd Copyright © 2024 Shane C. */ package cmd import ( "context" "fmt" "github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/stdlib" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/pgdialect" "github.com/uptrace/bun/migrate" "log" "omnibill.net/omnibill/migrations" "omnibill.net/omnibill/shared" "github.com/spf13/cobra" ) // rollbackCmd represents the rollback command var rollbackCmd = &cobra.Command{ Use: "rollback", Short: "Rollback db migrations", Run: func(cmd *cobra.Command, args []string) { dsn := shared.GetPostgresURI() config, err := pgxpool.ParseConfig(dsn) if err != nil { log.Fatalln(err) } pool, err := pgxpool.NewWithConfig(context.Background(), config) if err != nil { log.Fatalln(err) } sqldb := stdlib.OpenDBFromPool(pool) db := bun.NewDB(sqldb, pgdialect.New()) migrator := migrate.NewMigrator(db, migrations.Migrations) ctx := context.Background() if err := migrator.Init(ctx); err != nil { log.Fatalln(err) } if err := migrator.Lock(ctx); err != nil { log.Fatalln(err) } defer migrator.Unlock(ctx) group, err := migrator.Rollback(ctx) if err != nil { log.Fatalln(err) } if group.IsZero() { fmt.Printf("there is nothing to rollback\n") return } fmt.Printf("rolled back to %s\n", group) }, } func init() { migrateCmd.AddCommand(rollbackCmd) }