// Command migrate applies the embedded schema migrations once and exits. It // runs as a one-shot service before the API replicas start, so the replicas // never race each other over the schema and need no rights to change it. package main import ( "context" "fmt" "log/slog" "os" "os/signal" "syscall" "messenger/internal/platform/config" "messenger/internal/platform/postgres" ) // poolSize covers the goose session lock and the migration itself. const poolSize = 2 func main() { cfg, err := config.LoadMigrate(os.LookupEnv) if err != nil { fmt.Fprintln(os.Stderr, "configuration error:", err) os.Exit(2) } log := newLogger(cfg) ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) defer stop() if err := run(ctx, log, cfg); err != nil { log.Error("migration failed", "error", err.Error()) os.Exit(1) } } func run(ctx context.Context, log *slog.Logger, cfg config.Migrate) error { pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, poolSize) if err != nil { return err } defer pool.Close() applied, err := postgres.Migrate(ctx, pool) if err != nil { return err } log.Info("migrations applied", "applied_migrations", applied) return nil } func newLogger(cfg config.Migrate) *slog.Logger { opts := &slog.HandlerOptions{Level: cfg.LogLevel} if cfg.Env == "dev" { return slog.New(slog.NewTextHandler(os.Stdout, opts)) } return slog.New(slog.NewJSONHandler(os.Stdout, opts)) }