Skip to content
Back to skills

Database Migrations

ASecurity

Postgres-first rules for schema and data changes - one new migration per change, never edit applied ones, expand/contract for renames, concurrent indexes, batched backfills, reversible downs - plus tool workflows (golang-migrate, goose, Alembic, Prisma) and the sqlc generate/vet loop. Use when a job changes schema, queries or data.

  • 5 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 27, 2026
developmentgobashsqlgitdatabase

Security analysis

A100/100

Scanned November 27, 2026

npx -y skills add Nabwinsaud/forgeline --skill database-migrations --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Database Migrations?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Database Migrations
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nabwinsaud-database-migrations/badge)](https://www.skillsdirectory.com/skills/nabwinsaud-database-migrations)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: database-migrations
description: Postgres-first rules for schema and data changes - one new migration per change, never edit applied ones, expand/contract for renames, concurrent indexes, batched backfills, reversible downs - plus tool workflows (golang-migrate, goose, Alembic, Prisma) and the sqlc generate/vet loop. Use when a job changes schema, queries or data.
---

# Database migrations

Migrations are a protected path: any job that adds one goes to a human for approval. Make that
review easy - small, boring, reversible, safe on a big table while the old code is still running.

## Ground rules

- **One new migration file per logical change.** Use the repo's tool to create it so naming and
  numbering are right.
- **Never edit a migration that may have been applied anywhere** (merged to base, deployed to
  dev/stg). Fix forward with a new migration.
- **Every up has a down** that restores the previous schema. If a down would destroy data, say so
  in a comment and in the spec's Risk section.
- **Old code must keep working** after the migration runs, because deploys roll and the migration
  usually runs before the new code is live.
- **No data-changing logic in application startup.** Schema and backfills go through migrations or
  explicit one-off jobs.
- Test the migration: run up, down, up against a real Postgres (testcontainers or the compose DB).

## Safe vs dangerous operations (Postgres)

| Operation | Safe? | Do instead |
|---|---|---|
| Add nullable column | yes | - |
| Add column with constant default (PG 11+) | yes | - |
| Add NOT NULL column without default | no | add nullable -> backfill -> add constraint |
| Add index | locks writes | `CREATE INDEX CONCURRENTLY` (outside a transaction) |
| Add foreign key | scans table | `ADD CONSTRAINT ... NOT VALID`, then `VALIDATE CONSTRAINT` separately |
| Add CHECK / NOT NULL on big table | scans | `CHECK (...) NOT VALID` -> validate -> then `SET NOT NULL` |
| Rename column/table | breaks old code | expand/contract |
| Change column type | rewrites table | new column + backfill + switch |
| Drop column | breaks old code | stop reading it first, drop in a later release |

Set `lock_timeout` (e.g. `SET lock_timeout = '5s'`) in migrations that take locks, so a blocked
migration fails fast instead of queueing every query behind it.

## Expand / contract (renames and type changes)

Spread across separate jobs/releases:

1. **Expand** - add the new column/table. Code writes both old and new, reads old.
2. **Backfill** - copy old -> new in batches.
3. **Switch** - code reads new, still writes both.
4. **Contract** - code stops using old; a later migration drops it.

Never do all four in one PR.

## Concurrent indexes

```sql
-- +goose NO TRANSACTION
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_customer_created
    ON orders (customer_id, created_at DESC);
```

golang-migrate: put it in its own file (it runs each file as given; do not wrap in BEGIN).
Alembic: use `with op.get_context().autocommit_block():`. Prisma: write raw SQL in the migration.
A failed concurrent build leaves an INVALID index - the down/retry must `DROP INDEX CONCURRENTLY IF EXISTS`.

## Batched backfills

Never `UPDATE big_table SET ...` in one statement. Batch by key, commit per batch:

```sql
UPDATE orders SET status_v2 = status
WHERE id IN (
  SELECT id FROM orders WHERE status_v2 IS NULL ORDER BY id LIMIT 5000
);
-- repeat until 0 rows
```

Make backfills idempotent and restartable. Large backfills belong in a job/script, not a
schema migration that runs inside the deploy.

## Tool workflows

```bash
# golang-migrate
migrate create -ext sql -dir db/migrations -seq add_orders_status_v2
migrate -path db/migrations -database "$DATABASE_URL" up

# goose
goose -dir db/migrations create add_orders_status_v2 sql
goose -dir db/migrations postgres "$DATABASE_URL" up

# Alembic
alembic revision -m "add orders status_v2"          # review autogenerate output by hand
alembic upgrade head && alembic downgrade -1 && alembic upgrade head

# Prisma
npx prisma migrate dev --name add_orders_status_v2  # local only
npx prisma migrate deploy                           # CI/deploy, never `migrate reset` on shared DBs
```

Autogenerated migrations (Alembic, Prisma) are drafts: read them, remove drops you did not intend,
and add `CONCURRENTLY` where needed.

## sqlc workflow

sqlc turns SQL into typed Go. The SQL is the source of truth; the Go is output.

1. Schema comes from the migrations directory (`schema:` in `sqlc.yaml`).
2. Write or change queries in `.sql` files under the configured `queries:` path:

```sql
-- name: ListOrdersByCustomer :many
SELECT id, customer_id, total_cents, created_at
FROM orders
WHERE customer_id = $1 AND tenant_id = $2
ORDER BY created_at DESC, id DESC
LIMIT $3;
```

3. Regenerate and check:

```bash
sqlc generate
sqlc vet          # if configured
go build ./... && go test ./...
git status --porcelain   # generated files changed -> commit them with the SQL
```

- **Never hand-edit generated files** (`*.sql.go`, `models.go`, `db.go`). If the output is wrong,
  change the SQL, the schema, or `sqlc.yaml` overrides.
- Use named params (`sqlc.arg(name)`) when positional ones get confusing.
- `:one` returns `pgx.ErrNoRows` when missing - map it to a not-found domain error.
- Keep tenant/ownership predicates in the query itself, not filtered in Go after loading.

## Checklist

- [ ] New migration file created with the repo's tool; no applied migration edited.
- [ ] Up and down both run cleanly on a real Postgres.
- [ ] No long locks: concurrent indexes, NOT VALID constraints, lock_timeout set.
- [ ] Old code compatible with the new schema.
- [ ] Backfill batched and idempotent (or split into a follow-up).
- [ ] Generated code regenerated and committed; tree clean after regeneration.
- [ ] Spec Risk section mentions the migration.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.