#!/usr/bin/env bash # Migrations<->schema parity gate. Fails when the Prisma schema contains # objects that no committed migration creates (the AD-21 footgun: feature # branches use `prisma db push`, so a forgotten merge migration only surfaces # as P2021 at runtime on deploy-managed databases — see # prisma/migrations/20260703150000_ak_schema_parity_catchup). # # Replays the full migration history into an ephemeral PostgreSQL container # (shadow DB) and diffs the result against prisma/schema. Any non-empty diff # means "schema changed but no migration was written" and blocks the PR. # # Usage: # ./scripts/verify-migrations-schema-parity.sh # # Requires: docker, pnpm. set -euo pipefail PARITY_NAME="hivegrid-migrations-parity-$$" PARITY_USER="parity" PARITY_PASSWORD="parity" PARITY_DB="parity" PG_IMAGE="${PARITY_PG_IMAGE:-postgres:16-alpine}" require_cmd() { if ! command -v "$1" >/dev/null 2>&1; then echo "MISSING $1" >&2 echo "The migrations/schema parity gate requires '$1' locally." >&2 exit 127 fi } require_cmd docker require_cmd pnpm cleanup() { docker rm -f "$PARITY_NAME" >/dev/null 2>&1 || true } trap cleanup EXIT docker run -d --name "$PARITY_NAME" -p 127.0.0.1::5432 \ -e POSTGRES_USER="$PARITY_USER" \ -e POSTGRES_PASSWORD="$PARITY_PASSWORD" \ -e POSTGRES_DB="$PARITY_DB" \ "$PG_IMAGE" >/dev/null PARITY_PORT="$(docker port "$PARITY_NAME" 5432/tcp | awk -F: 'NR == 1 { print $NF }')" SHADOW_URL="postgresql://${PARITY_USER}:${PARITY_PASSWORD}@127.0.0.1:${PARITY_PORT}/${PARITY_DB}?schema=public" for attempt in $(seq 1 30); do if docker exec "$PARITY_NAME" pg_isready -U "$PARITY_USER" -d "$PARITY_DB" >/dev/null 2>&1; then break fi if [[ "$attempt" == "30" ]]; then echo "Parity gate Postgres did not become ready" >&2 docker logs "$PARITY_NAME" >&2 || true exit 1 fi sleep 1 done # prisma.config.ts resolves DATABASE_URL at load time; point it at the # ephemeral DB so the gate does not depend on a local .env. The diff itself # only uses the migrations dir, the schema dir and the shadow DB. set +e DATABASE_URL="$SHADOW_URL" SHADOW_DATABASE_URL="$SHADOW_URL" \ pnpm exec prisma migrate diff \ --from-migrations prisma/migrations \ --to-schema prisma/schema \ --exit-code \ --config prisma.config.ts DIFF_EXIT=$? set -e if [[ "$DIFF_EXIT" == "0" ]]; then echo "OK migrations and prisma/schema are in parity" exit 0 fi if [[ "$DIFF_EXIT" == "2" ]]; then echo "" >&2 echo "FAIL prisma/schema contains changes no migration covers (AD-21: write the merge migration)." >&2 echo "Drift script:" >&2 DATABASE_URL="$SHADOW_URL" SHADOW_DATABASE_URL="$SHADOW_URL" \ pnpm exec prisma migrate diff \ --from-migrations prisma/migrations \ --to-schema prisma/schema \ --script \ --config prisma.config.ts >&2 || true exit 2 fi echo "FAIL prisma migrate diff errored (exit ${DIFF_EXIT})" >&2 exit "$DIFF_EXIT"