This prompt is designed for backend engineers and data platform teams who need to review auto-generated ORM migration diffs before applying them to a database. The core job is to catch implicit, dangerous, or incorrect schema changes that an ORM's migration generator can silently introduce—such as missing index operations, unexpected default value changes, or operations that the ORM generated incorrectly based on incomplete model metadata. The ideal user is an engineer who understands the application's data model and can interpret raw SQL, but who wants a structured, human-readable review that highlights risks the ORM's diff output obscures.
Prompt
ORM Migration Diff Review Prompt

When to Use This Prompt
Define the job, reader, and constraints for reviewing auto-generated ORM migration diffs before they reach production.
Use this prompt when you have a raw SQL diff produced by an ORM's migration tool (e.g., Alembic, Prisma Migrate, TypeORM, Entity Framework, or Django migrations exported as SQL) and you need a pre-flight review before executing the migration. The prompt requires the raw SQL diff as its primary input, along with optional context about the application's data model, known sensitive tables, and any business rules that should constrain schema changes. Do not use this prompt for reviewing hand-written migration scripts where the author's intent is explicit in comments, for performance tuning of query plans, or for post-migration data reconciliation—those are separate workflows with their own dedicated playbooks in this pillar.
This prompt is not a replacement for a full migration review by a senior engineer, nor does it execute the migration or validate it against a live database. It is a structured analysis layer that surfaces what the ORM's diff output implies but does not explicitly state. For high-risk migrations—those involving large tables, column drops, data type changes, or constraint additions—always pair this prompt's output with the sibling playbooks for rollback safety, transaction boundary review, and large-table ALTER assessment. The prompt's value is in making implicit changes explicit before they become expensive production incidents.
Use Case Fit
Where the ORM Migration Diff Review Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your workflow before wiring it into a CI pipeline or review harness.
Good Fit: Auto-Generated ORM Diffs
Use when: your migration was produced by an ORM (Prisma, Alembic, TypeORM, Django, etc.) and you need a second pair of eyes on implicit changes. Why: ORMs silently add or drop indexes, change column defaults, and reorder operations. This prompt surfaces those surprises before they reach production.
Bad Fit: Hand-Written DDL with Business Logic
Avoid when: the migration contains complex procedural logic, application-level data transformations, or business rule enforcement. Why: the prompt reviews structural SQL changes, not whether a backfill script correctly calculates lifetime value. Use the Data Backfill Script Validation Prompt for that case.
Required Input: Raw SQL Diff
What you must provide: the full SQL diff output, not just the ORM's summary or the migration file name. Guardrail: if your harness cannot extract the raw DDL statements (CREATE, ALTER, DROP), do not run this prompt. Incomplete input produces false confidence.
Operational Risk: False Negatives on Implicit Changes
What to watch: the prompt may miss implicit behaviors that are not visible in the SQL diff itself, such as trigger recompilation or statistics invalidation. Guardrail: pair this prompt with a dry-run execution against a production-like schema and feed any warnings back into the review.
Pipeline Fit: Pre-Merge CI Check
Use when: you want to block or flag migration PRs before merge. Guardrail: treat the prompt output as a review comment, not a merge gate. A human must confirm index drops, default value changes, and destructive operations before the migration ships.
Not a Replacement for Migration Testing
What to watch: teams treating prompt output as a substitute for running the migration against a staging or ephemeral database. Guardrail: always execute the migration in a pre-production environment. Use this prompt to decide what to scrutinize during that test run, not to skip it.
Copy-Ready Prompt Template
A reusable prompt template for reviewing ORM-generated migration diffs, identifying hidden risks, and producing structured, actionable review feedback.
The following prompt template is designed to be copied directly into your AI harness, prompt library, or evaluation framework. It accepts a raw SQL diff as its primary input and instructs the model to act as a senior database engineer reviewing an auto-generated migration. The template uses square-bracket placeholders for all dynamic inputs, ensuring you can swap in different diffs, risk profiles, and output schemas without modifying the core instructions. Every placeholder is documented so you know what to provide and why it matters for the review quality.
textYou are a senior database reliability engineer reviewing an auto-generated ORM migration diff before it is applied to production. Your job is to identify implicit changes, missing operations, default value surprises, and incorrect ORM-generated SQL that could cause data loss, downtime, or correctness bugs. ## INPUT Review the following raw SQL migration diff: ```sql [RAW_SQL_DIFF]
CONTEXT
- ORM Framework: [ORM_NAME_AND_VERSION]
- Source ORM Models: [ORM_MODEL_DEFINITIONS]
- Target Database: [DATABASE_ENGINE_AND_VERSION]
- Table Sizes (approximate rows): [TABLE_SIZE_ESTIMATES]
- Deployment Strategy: [DEPLOYMENT_STRATEGY]
- Known Application Constraints: [APPLICATION_CONSTRAINTS]
OUTPUT SCHEMA
Return a JSON object with the following structure: { "summary": "string (one-paragraph executive summary of risks found)", "findings": [ { "severity": "critical | high | medium | low", "category": "data_loss | downtime | correctness | performance | missing_operation | implicit_change | default_surprise", "location": "string (line reference or operation description)", "description": "string (what the ORM generated and why it's problematic)", "impact": "string (what happens if this migrates as-is)", "suggested_fix": "string (specific SQL or ORM config change to resolve)", "rollback_safe": true | false } ], "missing_operations": [ { "operation": "string (e.g., CREATE INDEX, ANALYZE, UPDATE)", "reason": "string (why this operation is needed based on the schema change)", "suggested_sql": "string (the missing SQL statement)" } ], "rollback_plan": "string (step-by-step rollback instructions or null if fully reversible)", "overall_risk": "safe_to_apply | needs_review | do_not_apply" }
CONSTRAINTS
- Flag any DROP COLUMN, DROP TABLE, or TRUNCATE as critical severity.
- Flag any ALTER COLUMN with type changes that could truncate data or lose precision.
- Flag any new NOT NULL constraint without a DEFAULT value on a table with existing rows.
- Flag any missing index on new foreign key columns.
- Flag any operation that acquires an ACCESS EXCLUSIVE lock on large tables.
- If the ORM generated a table rename as DROP + CREATE, flag it as data loss.
- If the deployment strategy is blue-green or zero-downtime, flag any operation incompatible with that strategy.
- Do not invent findings. Only report issues present in the provided diff.
EXAMPLES
Example finding for a missing index: { "severity": "high", "category": "missing_operation", "location": "new column 'user_id' on table 'orders'", "description": "ORM added foreign key column 'user_id' but did not generate a corresponding index.", "impact": "Joins and lookups on user_id will perform sequential scans on the orders table, causing performance degradation under load.", "suggested_fix": "Add 'CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);' as a separate migration step.", "rollback_safe": true }
TOOLS
You have access to the following tool:
validate_sql_syntax(sql: string): Returns syntax errors or confirms validity for the target database engine. Use this tool to verify any suggested fix SQL before including it in your output.
RISK_LEVEL
[RISK_LEVEL] If RISK_LEVEL is "high", require explicit human approval before any destructive operation is suggested. If RISK_LEVEL is "medium", flag but do not block. If RISK_LEVEL is "low", focus on correctness and performance only.
To adapt this template for your stack, replace each placeholder with concrete values before sending it to the model. The [RAW_SQL_DIFF] should be the exact output of your ORM's migration generation command (e.g., alembic upgrade --sql, prisma migrate diff, or django makemigrations --dry-run). The [ORM_MODEL_DEFINITIONS] should include the before and after model definitions so the model can cross-reference intent against the generated SQL. For [TABLE_SIZE_ESTIMATES], provide approximate row counts so the model can assess lock duration and index creation time. The [DEPLOYMENT_STRATEGY] field is critical: if you use blue-green or rolling deployments, the model will flag operations that break backward compatibility between old and new application versions. The [RISK_LEVEL] parameter controls the review's conservatism—set it to "high" for financial or healthcare data, and "low" for internal development databases. After copying the template, run it through your evaluation suite with known-good and known-bad migration diffs to calibrate the model's sensitivity before trusting it on production migrations.
Prompt Variables
Required inputs for the ORM Migration Diff Review Prompt. Each variable must be populated before the prompt is assembled and sent. Missing or malformed inputs are the most common cause of false negatives in migration review.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_SQL_DIFF] | The complete SQL diff generated by the ORM migration tool, including both up and down migrations | ALTER TABLE orders ADD COLUMN tax_rate DECIMAL(5,4) DEFAULT 0.0000; | Must contain valid SQL statements. Reject if empty, if only comments, or if diff is truncated. Parse check: at least one DDL or DML statement required. |
[ORM_NAME] | The ORM or migration tool that generated the diff, to contextualize known generator quirks | Prisma, Alembic, Flyway, Django ORM, TypeORM | Must match a known ORM from the allowed list. Used to load ORM-specific heuristics for implicit operations and known misgenerations. |
[DATABASE_ENGINE] | Target database engine and version to validate syntax and feature compatibility | PostgreSQL 15, MySQL 8.0, SQLite 3.40 | Must include engine name and major version. Used to check for engine-specific DDL support, lock behavior, and syntax validity. |
[TABLE_METADATA] | Current schema metadata for tables affected by the migration, including row counts, index definitions, and constraint details | {"orders": {"row_count": 2450000, "indexes": ["idx_orders_user_id"], "constraints": ["fk_orders_user_id"]}} | JSON object keyed by table name. Row count must be a non-negative integer. Index and constraint arrays may be empty. Null allowed if table is new. |
[EXISTING_SCHEMA_DDL] | The current DDL for all objects referenced in the migration diff, used to detect conflicts and redundant operations | CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INT NOT NULL); | Must contain valid DDL matching the [TABLE_METADATA] tables. Reject if DDL references tables not in metadata. Parse check: CREATE TABLE or equivalent statements required. |
[APPLICATION_CODE_CONTEXT] | Relevant ORM model definitions, entity classes, or schema declaration files that the ORM used to generate the diff | model Order { id Int @id, userId Int, taxRate Decimal? @default(0.0000) } | Optional but strongly recommended. When absent, the review cannot detect intent mismatches between model changes and generated SQL. Null allowed with degraded review quality. |
[PREVIOUS_MIGRATION_HISTORY] | List of recently applied migrations in order, to detect ordering issues and conflicting prior changes | ["20240101_add_users", "20240115_add_orders", "20240201_add_order_status"] | Array of migration identifiers in application order. May be empty for first migration. Used to check for missing prerequisites and out-of-order operations. |
Implementation Harness Notes
How to wire the ORM migration diff review prompt into a CI/CD pipeline or pre-deployment workflow with validation, retries, and human approval gates.
The ORM Migration Diff Review Prompt is designed to sit inside a pre-apply review gate, not as a standalone chat interaction. The typical integration point is a CI pipeline step that triggers when a new migration file is added to a pull request. The harness extracts the raw SQL diff from the ORM's migration output (e.g., alembic upgrade --sql, prisma migrate diff, or django-admin sqlmigrate), feeds it into the prompt as [RAW_SQL_DIFF], and posts the structured review as a comment on the PR. This ensures every migration gets a consistent, automated first-pass review before a human ever looks at it.
The harness must validate the model's output against the expected [OUTPUT_SCHEMA] before posting results. At minimum, validate that the response is valid JSON, that the findings array contains objects with the required severity, category, location, and explanation fields, and that severity values are constrained to the allowed enum (CRITICAL, HIGH, MEDIUM, LOW, INFO). If validation fails, retry once with the same input and an explicit instruction appended: 'Your previous response failed schema validation. Return ONLY valid JSON matching the output schema exactly.' If the second attempt also fails, post a failure notification to the PR and escalate to the on-call channel. Do not silently swallow malformed reviews.
For model selection, prefer a model with strong SQL reasoning and structured output discipline. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well on this task when given the raw SQL diff and a clear output schema. Avoid smaller or older models that may hallucinate index operations or misidentify generated SQL patterns. Set temperature to 0 or a very low value (0.1 maximum) to reduce variability in severity classification. If your ORM generates exceptionally large diffs (over 8,000 tokens of SQL), split the diff by table or operation type and run the prompt in parallel batches, then merge the findings arrays. Always log the full prompt, raw SQL input, model response, and validation result to your prompt observability platform for audit and regression testing.
The human approval gate is critical. The prompt's output should be treated as a review assistant, not an auto-approver. Configure your CI pipeline to block merge if any CRITICAL finding is detected, and to require a human reviewer to explicitly acknowledge HIGH severity findings before the migration can be applied. For MEDIUM and below, the findings should be visible in the PR but not blocking. This tiered gating prevents the most dangerous migration mistakes—implicit schema changes, missing index operations, and default value surprises—from reaching production while keeping the review workflow fast for low-risk changes. Pair this prompt with the Migration Rollback Safety Review Prompt for a complete pre-deployment safety net.
Expected Output Contract
Fields, types, and validation rules for the structured review output. Use this contract to parse, validate, and route findings before they reach a human reviewer or CI check.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
review_summary | string (max 500 chars) | Must be non-empty. Reject if length > 500 or contains only whitespace. | |
overall_risk | enum: LOW, MEDIUM, HIGH, CRITICAL | Must match one of the four allowed values exactly. Reject on case mismatch or unknown value. | |
findings | array of finding objects | Must be a non-null array. Reject if empty when overall_risk is HIGH or CRITICAL. | |
findings[].severity | enum: INFO, WARNING, ERROR, BLOCKER | Must match allowed enum. Reject if BLOCKER is present but overall_risk is not CRITICAL. | |
findings[].category | enum: IMPLICIT_CHANGE, MISSING_INDEX, DEFAULT_SURPRISE, INCORRECT_GENERATION, ROLLBACK_SAFETY, DATA_LOSS_RISK, LOCK_ESCALATION, CONSTRAINT_VIOLATION | Must match one of the allowed categories. Reject unknown values to prevent downstream routing errors. | |
findings[].source_sql | string (valid SQL snippet) | Must be a non-empty string containing SQL keywords (SELECT, ALTER, CREATE, DROP, INSERT, UPDATE, DELETE, or ADD). Reject if no SQL keyword detected. | |
findings[].description | string (max 1000 chars) | Must be non-empty. Reject if it contains only the source_sql repeated without explanation. | |
findings[].suggested_fix | string or null | If present, must contain at least one SQL keyword. If null, severity must be INFO only. Reject if non-null and empty string. |
Common Failure Modes
ORM-generated migration diffs hide dangerous assumptions. These are the most common failures when reviewing them with an LLM and how to prevent each one.
Implicit Default Value Changes
What to watch: The ORM diff shows a column addition without an explicit DEFAULT, but the model infers a default from application code or an enum definition. This can lock tables on large datasets or produce incorrect values for existing rows. Guardrail: Require the prompt to flag any column addition that lacks an explicit DEFAULT clause and cross-reference against the application model's default attribute. If the raw SQL diff and ORM model disagree, escalate for human review.
Missing Index Operations
What to watch: The ORM generates a column rename or type change but drops the associated index without recreating it, or adds a foreign key without a corresponding index on the referencing column. This causes silent query performance degradation in production. Guardrail: The prompt must explicitly compare index sets before and after the migration. Any index present in the pre-migration schema but absent in the post-migration schema without a documented reason should be flagged as a high-severity finding.
Destructive Operation Misclassification
What to watch: The ORM represents a DROP COLUMN, DROP TABLE, or TRUNCATE as a routine schema change. The LLM reviews it without recognizing the data loss risk because the operation is syntactically valid. Guardrail: The prompt must categorize every DDL statement by risk level (destructive, blocking, safe). Any destructive operation must be accompanied by a rollback plan and a confirmation that backups exist. The harness should reject reviews that don't include this categorization.
Enum Value Reordering Surprise
What to watch: The ORM diff shows an enum modification that adds or removes values. The LLM treats it as a simple ALTER but misses that reordering enum values (or inserting in the middle) changes the ordinal mapping, breaking application code that relies on ordinal position. Guardrail: The prompt must require the model to list the before and after enum value ordering explicitly. Any change in ordinal position must be flagged with a warning that application code using .ordinal() or integer mapping will break.
Transaction Boundary Blindness
What to watch: The ORM splits what should be an atomic migration into multiple separate statements without an explicit transaction wrapper. The LLM reviews each statement individually and misses that partial failure leaves the schema in an inconsistent state. Guardrail: The prompt must check whether the migration is wrapped in a single transaction. If the ORM or database (e.g., MySQL with implicit commits on DDL) does not support transactional DDL, the prompt must recommend a rollback script for each statement and a pre-execution checkpoint.
Hallucinated ORM Behavior Explanation
What to watch: The LLM confidently explains why the ORM generated a particular SQL statement based on its training data, but the explanation is wrong for the specific ORM version in use. This leads the reviewer to accept a dangerous change based on a plausible but false rationale. Guardrail: The prompt must instruct the model to cite specific lines from the provided raw SQL diff and ORM model definition, not from its general knowledge. Any statement that begins with 'This ORM typically...' or 'In most frameworks...' without grounding in the provided input must be treated as low-confidence and flagged for human verification.
Evaluation Rubric
Criteria for evaluating the quality and safety of the ORM migration diff review output before merging or applying the migration.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Implicit Change Detection | All operations not explicitly authored by the developer (e.g., auto-added defaults, unexpected column drops) are flagged in a dedicated section. | Output contains only a raw SQL diff or describes only the developer's stated intent without identifying auto-generated surprises. | Diff the developer's intended schema changes against the ORM's generated SQL. Confirm the review output lists every discrepancy. |
Missing Index Identification | Any foreign key column lacking a corresponding index is flagged, along with any new query patterns that would benefit from a composite index. | Output does not mention indexes, or only suggests indexes for primary keys while ignoring join/filter columns. | Parse the SQL diff for ADD FOREIGN KEY statements. Cross-reference with CREATE INDEX statements. Verify the review output flags any FK without an index. |
Default Value Risk Assessment | Every new column with a default value is assessed for backfill risk, lock duration, and application compatibility. | Output ignores default values or treats all defaults as safe without considering table size or existing data. | Extract all DEFAULT clauses from the SQL diff. For each, check if the review output includes a note on backfill behavior and risk level. |
Destructive Operation Flagging | DROP COLUMN, DROP TABLE, TRUNCATE, and ALTER COLUMN TYPE operations are highlighted with a severity rating and rollback difficulty. | A DROP COLUMN operation is present in the diff but not mentioned in the review summary or risk section. | Scan the SQL diff for destructive DDL keywords. Assert that each instance appears in the review output with an explicit severity label. |
Rollback Feasibility Statement | For each migration step, a rollback strategy is stated (e.g., reversible, requires backup, irreversible without data loss). | Output provides a generic 'test before deploying' warning without per-operation rollback guidance. | For each top-level statement in the SQL diff, verify the review output contains a corresponding rollback note or an explicit 'no safe rollback' declaration. |
ORM Error Pattern Recognition | Common ORM misbehaviors (e.g., recreating a table instead of altering, incorrect column ordering, missing IF NOT EXISTS) are checked and reported. | Output treats the ORM-generated SQL as correct by default and only comments on business logic. | Inject a known ORM error pattern (e.g., a table rename implemented as DROP/CREATE) into the test diff. Confirm the review output identifies the pattern and explains why it is dangerous. |
Output Schema Compliance | The response strictly follows the defined [OUTPUT_SCHEMA] with all required fields populated and no extra commentary. | Output is a free-text paragraph, or required fields like 'severity' or 'rollback_risk' are missing or null. | Validate the raw model response against the [OUTPUT_SCHEMA] JSON Schema. Retry if validation fails. |
No Hallucinated Operations | The review references only operations present in the provided [SQL_DIFF]. It does not invent missing migrations or schema objects. | The review warns about a table or column that does not appear in the input diff. | Extract all database object names from the review output. Assert that each is a substring match in the [SQL_DIFF] input. Flag any unmatched names as hallucinations. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a strict JSON output schema with severity levels, line references, and fix suggestions. Include a harness that validates the output structure before surfacing to the developer. Add retry logic for malformed responses.
Prompt snippet
codeReview this ORM migration diff. Output valid JSON matching [OUTPUT_SCHEMA]. Diff: [RAW_SQL_DIFF] Model change description: [MODEL_CHANGE_DESCRIPTION] For each finding, include: - "severity": "critical" | "warning" | "info" - "line_reference": the SQL line or statement - "category": "implicit_change" | "missing_index" | "default_surprise" | "incorrect_generation" | "rollback_risk" - "description": human-readable explanation - "suggested_fix": actionable correction or verification step
Watch for
- Silent format drift where the model drops fields or changes enum values
- Missing human review gate for critical severity findings
- Schema validation failures that require a repair prompt before retry

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us