Verified SOP & TutorialAudited Score 98/100

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.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

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

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with active workspace
Python 3.10+ with pip and virtualenv support in the workspace host
PostgreSQL 14+ local instance or accessible staging/shadow database instances
Migra CLI installed with psycopg2 or psycopg3 backend (pip install 'migra[pg]')

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install postgres-schema-diff-migra in cursor ide#claude code postgres-schema-diff-migra rules#migra schema diff automation for postgresql agents#generate ddl migration migra windsurf prompt#codex desktop postgres declarative migration tutorial#how to fix migra database connection error in autonomous agent#zero downtime postgres ddl diff agent workflow#declarative postgres migrations skill security permissions

Step-by-Step Execution Playbook

1

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.

Terminal Command
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
.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
---
Production Pro-Tip

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.

Sandbox Gotcha

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.

2

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.

Terminal Command
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
scripts/diff_schema.sh
#!/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"
Production Pro-Tip

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.

Sandbox Gotcha

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.

3

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.

prompt.txt
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.
Production Pro-Tip

Specify schema names explicitly (e.g., --schema=public) if your database uses multi-tenant schemas, reducing generated diff noise and saving agent context tokens.

Sandbox Gotcha

Migra assumes source is transformed into target. Inverting the arguments (TARGET SOURCE) produces reversible downgrade scripts instead of upgrade scripts.

4

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.

Terminal Command
sqlfluff lint migrations/pending_diff.sql --dialect postgres && psql "${SOURCE_DB_URL}" --single-transaction --set ON_ERROR_STOP=1 -f migrations/pending_diff.sql
migrations/pending_diff.sql
BEGIN;

-- 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;
Production Pro-Tip

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.

Sandbox Gotcha

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

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“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.”

Deterministic Agent Verification Pipeline:
Activates postgres-schema-diff-migra skill matching trigger 'diff postgres schemas'.
Validates PostgreSQL connection strings from .env.local without exposing credentials in chat.
Executes migra CLI comparing baseline staging against local development database.
Analyzes generated statements: detects new organization_id column and foreign key addition.
Restructures output: converts blocking index creations to CONCURRENTLY statements outside transaction blocks.
Wraps constraint creations and idempotent column mutations in a BEGIN/COMMIT safety envelope.
Performs a dry-run application against a local scratch database and confirms exit code 0.

Runtime Troubleshooting & Failure Modes

Error: migra.exceptions.DifferencesFound: Differences found between schemas

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.

Resolution Command / Fix:
Use standard redirection or the --unsafe flag depending on intent: migra --unsafe "$SOURCE_DB_URL" "$TARGET_DB_URL" > migrations/migration.sql
Error: psycopg2.OperationalError: connection to server at "localhost" failed: FATAL: password authentication failed for user

Root Cause: Autonomous agent environment did not inherit workspace environment variables or sandbox blocked local loopback networking.

Resolution Command / Fix:
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.

Get 1-Click Install Spec