package cmd import ( "fmt" "github.com/spf13/cobra" "anchorage/internal/pkg/config" "anchorage/internal/pkg/store/postgres" ) // newMigrateCmd groups schema-migration subcommands under `anchorage migrate`. func newMigrateCmd(flags *globalFlags) *cobra.Command { migrate := &cobra.Command{ Use: "migrate", Short: "Manage the anchorage Postgres schema", } migrate.AddCommand(newMigrateUpCmd(flags)) migrate.AddCommand(newMigrateDownCmd(flags)) migrate.AddCommand(newMigrateStatusCmd(flags)) return migrate } func newMigrateUpCmd(flags *globalFlags) *cobra.Command { return &cobra.Command{ Use: "up", Short: "Apply all pending migrations", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { cfg, err := loadConfigForMigrate(flags) if err != nil { return err } if err := postgres.MigrateDSN(cmd.Context(), cfg.Postgres.DSN, postgres.MigrateUp, postgres.MigrateOptions{}); err != nil { return fmt.Errorf("migrate up: %w", err) } fmt.Fprintln(cmd.OutOrStdout(), "migrate: up OK") return nil }, } } func newMigrateDownCmd(flags *globalFlags) *cobra.Command { var yes bool c := &cobra.Command{ Use: "down", Short: "Revert every applied migration (destructive; dev/test only)", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { if !yes { return fmt.Errorf("refusing to run destructive migration; pass --yes to confirm") } cfg, err := loadConfigForMigrate(flags) if err != nil { return err } if err := postgres.MigrateDSN(cmd.Context(), cfg.Postgres.DSN, postgres.MigrateDown, postgres.MigrateOptions{}); err != nil { return fmt.Errorf("migrate down: %w", err) } fmt.Fprintln(cmd.OutOrStdout(), "migrate: down OK") return nil }, } c.Flags().BoolVar(&yes, "yes", false, "confirm that you understand this drops the whole schema") return c } func newMigrateStatusCmd(flags *globalFlags) *cobra.Command { return &cobra.Command{ Use: "status", Short: "Print the currently-applied migration version", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { cfg, err := loadConfigForMigrate(flags) if err != nil { return err } v, dirty, err := postgres.MigrationVersion(cmd.Context(), cfg.Postgres.DSN) if err != nil { return fmt.Errorf("read migration version: %w", err) } fmt.Fprintf(cmd.OutOrStdout(), "migrate: version=%d dirty=%v\n", v, dirty) return nil }, } } // loadConfigForMigrate loads the config with AllowMissing=true (so --config // being absent is fine if the DSN comes from env) but rejects the run if // there's still no DSN. func loadConfigForMigrate(flags *globalFlags) (*config.Config, error) { cfg, err := config.Load(config.LoadOptions{Path: flags.configPath, AllowMissing: true}) if err != nil { return nil, fmt.Errorf("load config: %w", err) } if cfg.Postgres.DSN == "" { return nil, fmt.Errorf("postgres.dsn is required (config file or ANCHORAGE_POSTGRES_DSN)") } return cfg, nil }