startup-migrate
A service that migrates its own schema before it starts serving, using only
the bunmigrator library -- no urfave/cli, no migratecmd. A service's
entry point rarely wants a sub-command tree just to run a migration at boot.
It walks the library end to end: reg.Plan(), bunmigrator.Discover,
bunmigrator.Apply, then bunmigrator.Changes to report what happened, one
line per migration. A zero group -- nothing to apply -- prints
"database is up to date" instead of an empty list.
signal.NotifyContext means a Ctrl-C mid-migration still lets Apply's
deferred Unlock run, instead of a killed process leaving the lock row
behind for every later start to fail on.
Run it
Needs a real Postgres 14+ database -- this example applies for real, it does
not have a --dry-run:
docker run -d --rm -e POSTGRES_PASSWORD=pg -p 5439:5432 postgres:16
DATABASE_URL='postgres://postgres:pg@localhost:5439/postgres?sslmode=disable' \
go run ./examples/startup-migrate
Run it a second time to see the zero-group path; Ctrl-C once it says it is
serving to see clean shutdown.
What you should see
First run: ADDED TABLE widgets, then serving (stub) -- press Ctrl-C to stop. Second run: database is up to date before it starts serving --
widgets was already created, so Apply has nothing to do. With no
DATABASE_URL and no PG_* variables set, it exits 1 with a plain
pgconn: no DSN given and PG_USER is not set rather than a panic or a stack
trace.