The Complete Production SOP: How to Deploy and Run Migra PostgreSQL Schema Diff & Declarative Migrations in Autonomous AI Agents
Step-by-step SOP to install and run Migra PostgreSQL schema diffing in Codex, Claude Code, and Cursor. Generate safe DDL migrations deterministically.
Technical Overview & Architectural Context
Autonomous coding agents frequently corrupt PostgreSQL schema migrations when generating raw DDL from mental models or unstructured diffs. LLMs routinely miscalculate foreign key dependency order, omit cascading constraints, generate locking ALTER TABLE rewrites, or issue destructive DROP COLUMN statements that wipe production columns. Without deterministic schema diffing tooling, agents hallucinate nonexistent column states or fail to account for multi-schema namespaces and custom ENUM types. The postgres-schema-diff-migra skill constrains autonomous agents within a verifiable declarative migration pipeline. By delegating schema state comparison to Migra and its underlying schemainspect engine, the agent analyzes actual PostgreSQL system catalogs rather than approximate ORM definitions. The skill enforces procedural inspection gates, wrapping diffs in transactional verification blocks and preventing destructive schema mutations without explicit human approval.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules.
To make the skill discoverable across Cursor, Windsurf, Codex, and Claude Code, initialize the skills configuration directory within your repository or user agent root. Claude Code discovers nested skills in .claude/skills/ or ~/.agents/skills/, while Cursor and Windsurf ingest skills configured within .cursor/rules/ or the unified .agents/skills/ registry.
mkdir -p .agents/skills/postgres-schema-diff-migra && curl -fsSL https://askills.dev/api/skills/postgres-schema-diff-migra/raw -o .agents/skills/postgres-schema-diff-migra/SKILL.md---
name: "postgres-schema-diff-migra"
description: "Generate safe, automated DDL migration scripts by diffing PostgreSQL database states."
metadata:
author: "djrobstep"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "diff postgres schemas"
- "generate ddl migration migra"
- "declarative postgres migrations"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: true
net_access: true
---Mount SKILL.md directly inside repository root (.agents/skills/) so team members and automated agent CI pipelines share identical migration invariants without redundant token overhead.
Ensure shell_exec and net_access are permitted in agent execution policies if the agent needs to invoke the migra CLI directly against external shadow databases.
Environment Secrets & Dependency Validation
Inject required database connection URIs safely without leaking credentials into agent context.
Migra requires two PostgreSQL connection strings: the target state (desired schema, e.g., local dev or migrations container) and the source state (current baseline, e.g., staging shadow database). Export these via standardized environment variables or inject them into an uncommitted .env.local file. Agents must read these variables from the environment rather than emitting raw password strings in chat traces.
python -m venv .venv && source .venv/bin/activate && pip install "migra[pg]" sqlfluff && echo "SOURCE_DB_URL=postgresql://postgres:postgres@localhost:5432/baseline_db" >> .env.local && echo "TARGET_DB_URL=postgresql://postgres:postgres@localhost:5432/target_db" >> .env.local#!/usr/bin/env bash
set -euo pipefail
if [ -f .env.local ]; then
export $(grep -v '^#' .env.local | xargs)
fi
migra --unsafe "${SOURCE_DB_URL}" "${TARGET_DB_URL}" > migrations/pending_diff.sql
if [ ! -s migrations/pending_diff.sql ]; then
echo "Schemas are in sync. No DDL generated."
exit 0
fi
echo "Generated DDL migration in migrations/pending_diff.sql"Run baseline schemas in temporary throwaway Docker containers or a dedicated shadow schema within the same PostgreSQL instance to avoid network round-trips during local agent diff iterations.
Never allow agents to run migra with target pointing directly to production without a dry-run flag, as raw sync flags apply uninspected mutations directly.
Intent Matching & Trigger Invocation
Verify deterministic activation using tested natural language prompts.
When working in Claude Code CLI, Cursor Composer, or Codex Desktop, use the specific trigger phrases defined in the SKILL.md frontmatter. Phrasing queries with 'diff postgres schemas' or 'generate ddl migration migra' guarantees the agent loads this specific SOP and bypasses hallucinated schema alteration strategies.
diff postgres schemas between local dev and the staging baseline database using migra. Store the output in migrations/20260330_add_user_preferences.sql and inspect for lock-inducing column defaults.Specify schema names explicitly (e.g., --schema=public) if your database uses multi-tenant schemas, reducing generated diff noise and saving agent context tokens.
Migra assumes source is transformed into target. Inverting the arguments (TARGET SOURCE) produces reversible downgrade scripts instead of upgrade scripts.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks and SQL linting before accepting agent deliverables.
The skill mandates that the agent wrap all output DDL in a safe transaction block (BEGIN...COMMIT), validate syntax with sqlfluff, and dry-run the execution against an ephemeral PostgreSQL shadow container before reporting completion.
sqlfluff lint migrations/pending_diff.sql --dialect postgres && psql "${SOURCE_DB_URL}" --single-transaction --set ON_ERROR_STOP=1 -f migrations/pending_diff.sqlBEGIN;
-- Automated diff generated via migra
ALTER TABLE "public"."users" ADD COLUMN "preferences" jsonb DEFAULT '{}'::jsonb NOT NULL;
CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_users_preferences" ON "public"."users" USING gin ("preferences");
COMMIT;Instruct the agent to flag any ALTER TABLE ... ADD COLUMN without a constant default, as older PostgreSQL versions or non-concurrent index additions trigger exclusive table locks.
CONCURRENTLY index creation cannot be executed inside a single BEGIN/COMMIT transaction block in PostgreSQL. Agents must break concurrent index operations into isolated steps.
Real-World Scenario: Automated Zero-Downtime PostgreSQL Schema Migration Generation
“We modified the user profile models in Prisma/SQLAlchemy to add a multi-tenant organization_id foreign key and a soft-delete status column. diff postgres schemas between our dev container and the staging replica using migra, generate a safe zero-downtime DDL script, and ensure dropped constraints don't break referential integrity.”
Runtime Troubleshooting & Failure Modes
Root Cause: By default, migra exits with status code 2 when differences exist if run without redirection or when invoked in assertion/CI checking mode.
Use standard redirection or the --unsafe flag depending on intent: migra --unsafe "$SOURCE_DB_URL" "$TARGET_DB_URL" > migrations/migration.sqlRoot Cause: Autonomous agent environment did not inherit workspace environment variables or sandbox blocked local loopback networking.
Verify PostgreSQL socket or localhost access and export credentials explicitly in the agent execution subshell: export SOURCE_DB_URL="postgresql://postgres:[email protected]:5432/app_db"Frequently Asked Questions (Migra PostgreSQL Schema Diff & Declarative Migrations SOP)
Q:Can I use Migra PostgreSQL Schema Diff & Declarative Migrations across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. Placing it in .agents/skills/postgres-schema-diff-migra allows Claude Code, Cursor, Windsurf, and OpenAI Codex runtimes to discover and execute identical declarative migration SOPs.
Q:How does Migra PostgreSQL Schema Diff & Declarative Migrations prevent context window overflow during long agent sessions?
By offloading the schema diffing logic to the deterministic migra engine. Instead of dumping megabytes of database catalog JSON or CREATE TABLE scripts into the agent's LLM context window, migra produces minimal, exact DDL diffs, consuming only a fraction of prompt tokens.
Q:Does this skill require escalated root or container permissions?
No. The skill operates with a 98/100 security score. It requires only standard workspace file read/write permissions to save generated migration SQL files and standard network/socket access to connect to developer-specified PostgreSQL instances.
Ready to equip your autonomous agent with Migra PostgreSQL Schema Diff & Declarative Migrations?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.