Inferensys

Prompt

Database Migration Rollback Test Prompt

A practical prompt playbook for using Database Migration Rollback Test Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job, the ideal user, required inputs, and the hard boundaries for using the Database Migration Rollback Test Prompt safely.

This prompt is for backend engineers and DBAs who need to verify that a database migration is safe to deploy by generating a targeted test suite. The job-to-be-done is not just to test the forward migration, but to prove that the rollback path is complete, data-preserving, and free of destructive side effects. Use this when you have a migration script written in SQL or an ORM definition, and you need to catch irreversible operations like DROP COLUMN, data type changes that truncate values, or constraint deletions before they reach production.

The ideal user provides the full migration up and down scripts, the current database schema, and the target database engine (e.g., PostgreSQL, MySQL). The prompt works best when you also supply a [CONSTRAINTS] block listing known risky operations to flag, such as DROP TABLE, ALTER COLUMN ... TYPE, or DELETE statements without WHERE clauses. Do not use this prompt for simple schema additions that have no data transformation or for migrations where rollback is explicitly not required by policy. It is also not a substitute for running the actual migration against a production-scale anonymized backup; it generates the test logic, not the execution environment.

The output is a structured test plan, not a passing test suite. You must wire the generated test cases into your CI pipeline, run them against a staging database, and verify that the rollback restores the exact pre-migration state. For high-risk migrations involving financial or healthcare data, require a human DBA to approve the test plan before execution. The next section provides the exact prompt template you will adapt with your schema and migration details.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Database Migration Rollback Test Prompt fits your current workflow, and understand the operational risks before you integrate it.

01

Good Fit: Structured Schema Migrations

Use when: your team runs framework-managed migrations (Alembic, Flyway, ActiveRecord) with explicit up and down steps. The prompt excels at generating tests that verify both directions from a single migration file. Guardrail: always provide the full migration file content and the target database dialect in [CONTEXT] to get accurate rollback SQL.

02

Bad Fit: Data-Only or Ad-Hoc Scripts

Avoid when: the migration is a one-off data backfill, a manual hotfix script, or lacks a defined rollback. The prompt cannot invent safe inverse operations for arbitrary DML without explicit instructions. Guardrail: for data-only changes, use a separate data validation prompt and require a human to author the rollback logic before testing.

03

Required Inputs: Migration & Schema Context

What to watch: the prompt requires the migration DDL, the previous schema state, and any known constraints. Missing context leads to incomplete or incorrect rollback tests. Guardrail: bundle the migration file, a schema.rb or schema.sql snapshot, and a list of foreign key relationships into [CONTEXT] before calling the prompt.

04

Operational Risk: Irreversible Operations

What to watch: DROP COLUMN, DROP TABLE, or data type changes that truncate data are irreversible. The prompt will flag these but cannot guarantee data recovery. Guardrail: add a [CONSTRAINTS] block requiring the prompt to mark any irreversible step with a HUMAN_REVIEW_REQUIRED flag and suggest a backup strategy before the test is considered complete.

05

Operational Risk: Constraint Violations on Rollback

What to watch: rollbacks can fail if new data added after migration violates old constraints (e.g., NOT NULL on a new column). The prompt must test for this. Guardrail: instruct the prompt to generate test cases that insert representative data after the forward migration and assert that the rollback either succeeds or raises a specific, expected error.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating database migration rollback test cases with square-bracket placeholders for your migration context.

This prompt template generates a comprehensive test suite for validating database migration rollback safety. It is designed to be dropped into an AI coding agent or test-generation pipeline where you provide the migration file, schema context, and risk constraints. The template forces the model to reason about data preservation, irreversible operations, constraint violations, and edge cases before producing executable test code. Use it when you need systematic rollback coverage beyond manual review—but never as a replacement for staging environment validation or DBA approval on production migrations.

text
You are a database reliability engineer reviewing a migration for rollback safety.

Generate a complete test suite that validates the forward migration, rollback integrity, and data preservation for the migration defined below.

[MIGRATION_FILE]

[SCHEMA_CONTEXT]

[TEST_FRAMEWORK]

[EXISTING_TEST_PATTERNS]

[CONSTRAINTS]
- Target database: [DATABASE_TYPE]
- Risk level: [RISK_LEVEL]
- Irreversible operations to flag: [IRREVERSIBLE_OPERATIONS]
- Data volume context: [DATA_VOLUME]

[OUTPUT_SCHEMA]
{
  "test_suite_name": "string",
  "forward_migration_tests": [
    {
      "test_name": "string",
      "description": "string",
      "setup_sql": "string | null",
      "migration_sql": "string",
      "assertions": ["string"],
      "expected_state": "string"
    }
  ],
  "rollback_tests": [
    {
      "test_name": "string",
      "description": "string",
      "pre_migration_state": "string",
      "post_migration_state": "string",
      "rollback_sql": "string",
      "assertions": ["string"],
      "data_preservation_check": "string"
    }
  ],
  "irreversible_operations": [
    {
      "operation": "string",
      "location_in_migration": "string",
      "risk_description": "string",
      "mitigation_suggestion": "string",
      "requires_manual_review": true
    }
  ],
  "constraint_violation_risks": [
    {
      "constraint_type": "string",
      "table_column": "string",
      "violation_scenario": "string",
      "rollback_impact": "string"
    }
  ],
  "edge_cases": [
    {
      "scenario": "string",
      "test_approach": "string",
      "expected_behavior": "string"
    }
  ],
  "execution_order": ["string"],
  "warnings": ["string"]
}

[EXAMPLES]
Example rollback test for a column drop migration:
{
  "test_name": "rollback_restores_dropped_column_data",
  "description": "Verify that rolling back a DROP COLUMN restores the column with original data intact",
  "pre_migration_state": "Table 'users' has columns: id, email, temporary_flag",
  "post_migration_state": "Table 'users' has columns: id, email",
  "rollback_sql": "ALTER TABLE users ADD COLUMN temporary_flag BOOLEAN DEFAULT false;",
  "assertions": [
    "Column 'temporary_flag' exists after rollback",
    "Row count matches pre-migration count",
    "Default value applied correctly for rows inserted during migration window"
  ],
  "data_preservation_check": "Rows inserted between forward migration and rollback must not lose data; default value applied to new column for those rows"
}

Generate the complete test suite following the output schema above. For each irreversible operation detected, flag it with requires_manual_review: true and explain why rollback cannot guarantee data recovery. Include edge cases for: empty tables, tables with null values, concurrent writes during migration, and large table performance thresholds.

Adapt this template by replacing each square-bracket placeholder with concrete values from your migration context. [MIGRATION_FILE] should contain the full migration SQL or file path. [SCHEMA_CONTEXT] needs the relevant table definitions, indexes, constraints, and foreign key relationships before and after the migration. [TEST_FRAMEWORK] specifies your target test runner—pytest, Jest, Go testing, or a database-specific framework like pgTAP. [EXISTING_TEST_PATTERNS] should include snippets of your team's current test conventions so the generated tests match your codebase style. For high-risk migrations where [RISK_LEVEL] is set to critical, always route the output through human DBA review before execution and add a pre-flight check that validates the test suite against a staging clone. Never skip the irreversible operations section—migrations that drop columns, truncate tables, or reshape data types require explicit acknowledgment that rollback cannot fully recover lost data without a backup.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Database Migration Rollback Test Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed and safe to use.

PlaceholderPurposeExampleValidation Notes

[MIGRATION_SQL]

The forward migration DDL statements to be tested

ALTER TABLE orders ADD COLUMN refund_reason VARCHAR(255);

Parse check: must contain valid DDL. Reject if empty or contains only comments. Schema check: verify table and column names exist in target environment.

[ROLLBACK_SQL]

The rollback DDL statements that should reverse the forward migration

ALTER TABLE orders DROP COLUMN refund_reason;

Parse check: must contain valid DDL. Pairwise check: each forward operation must have a corresponding rollback operation. Flag irreversible operations (DROP without backup, TRUNCATE) for human review.

[SCHEMA_SNAPSHOT]

Current database schema definition before migration is applied

CREATE TABLE orders (id INT PRIMARY KEY, total DECIMAL(10,2));

Schema check: must match target environment schema version. Timestamp check: snapshot must be taken within 5 minutes of test execution. Null allowed: false.

[SEED_DATA_QUERIES]

INSERT statements or query references for test data that exercises the migration

INSERT INTO orders (id, total) VALUES (1, 99.99), (2, 0.00), (3, NULL);

Coverage check: must include boundary values (NULL, zero, max length, negative where allowed). Referential integrity check: foreign key values must exist in parent tables. Row count: minimum 3 rows per affected table.

[CONSTRAINT_DEFINITIONS]

Existing constraints, indexes, and triggers on affected tables

{"orders": {"pk": "id", "fk": ["customer_id"], "indexes": ["idx_orders_total"], "triggers": ["trg_audit_orders"]}}

Schema check: must match current catalog. Completeness check: all constraints on affected tables must be listed. Null allowed: true if table has no constraints beyond PK.

[EXPECTED_POST_MIGRATION_STATE]

Assertions about schema and data after forward migration succeeds

Column refund_reason exists, nullable, type VARCHAR(255). Row count unchanged. Existing data preserved.

Schema check: assertions must reference valid objects. Data check: row count and checksum assertions must be testable. Human approval required: true for assertions involving data integrity.

[EXPECTED_POST_ROLLBACK_STATE]

Assertions about schema and data after rollback completes

Schema matches [SCHEMA_SNAPSHOT] exactly. Row count matches pre-migration count. No residual columns or constraints.

Schema check: must reference [SCHEMA_SNAPSHOT] as baseline. Diff check: post-rollback schema diff against snapshot must be empty. Data check: row-level checksum comparison required.

[IRREVERSIBLE_OPERATIONS_FLAG]

Boolean indicating whether the migration contains operations that cannot be rolled back without data loss

Type check: must be boolean. Approval check: if true, rollback test must include data backup verification step and human sign-off. Retry condition: if true, prompt must include warning language about data loss risk.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the migration rollback test prompt into a CI pipeline or developer workflow with validation, retries, and safety checks.

This prompt is designed to be called programmatically as part of a pre-commit hook, CI pipeline stage, or a developer CLI tool. The primary integration point is a script that extracts the migration file content and the target database schema, injects them into the prompt's [MIGRATION_SQL] and [SCHEMA_SNAPSHOT] placeholders, and then parses the structured output for downstream actions. The model's response should be treated as a test plan generator, not an executor—the generated SQL test cases must be reviewed and run in a sandboxed environment.

Integration workflow: 1) A git hook or CI trigger detects a new migration file. 2) The harness extracts the migration's UP and DOWN SQL blocks. 3) A schema dump is captured from a staging or ephemeral database that matches the target state. 4) The prompt is rendered with these inputs and sent to a capable model (e.g., GPT-4o, Claude 3.5 Sonnet). 5) The response is parsed into a structured object containing forward_tests, rollback_tests, data_preservation_checks, and irreversible_operations arrays. 6) Each test case is written to a temporary SQL file and executed against an isolated database instance. 7) Results are logged, and any test failure blocks the pipeline or flags the PR. Model choice: Use a model with strong SQL reasoning and structured output support. For cost-sensitive pipelines, a smaller model can be used if the output is validated with a strict JSON schema and retried on parse failure.

Validation and safety: Before executing any generated SQL, validate that all statements are read-only or run within a transaction that rolls back. The harness must reject any generated test that contains DROP, TRUNCATE, or unqualified DELETE without explicit review. Implement a retry loop: if the model's output fails JSON schema validation or contains SQL syntax errors, retry up to two times with the validation error appended to the prompt as [PREVIOUS_ERROR]. Logging and review: Log every prompt version, model response, validation result, and test execution outcome. For migrations tagged with [RISK_LEVEL]: HIGH (e.g., those involving column drops, type changes, or large data backfills), require a human approval step before the generated tests are merged. The harness should post a summary comment on the PR with the count of generated tests, any flagged irreversible operations, and a link to the full execution log.

What to avoid: Do not run generated tests directly against production or shared development databases. Do not skip the schema snapshot step—stale schema context is the most common cause of incorrect test generation. Do not treat the model's output as a substitute for manual review of rollback logic, especially for migrations that involve data transformations where semantic correctness matters more than syntactic validity.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact shape of the test plan object the model must return. Use this contract to build a post-generation validator before feeding the output into a test harness.

Field or ElementType or FormatRequiredValidation Rule

test_plan_id

string (slug)

Must match pattern migration-rollback-[timestamp]. Parse check.

migration_target

object

Must contain up_sql and down_sql string fields. Schema check.

test_cases

array[object]

Minimum 3 items. Each object must conform to the test_case sub-schema.

test_cases[].name

string

Must be non-empty and unique within the array. Duplicate check.

test_cases[].phase

enum

Must be one of pre-migration, post-up, post-rollback. Enum check.

test_cases[].assertion

string (SQL)

Must be a valid SQL SELECT statement that returns a boolean or countable result. Syntax check.

test_cases[].expected_outcome

string

Must be one of rows_exist, no_rows, specific_value, error_expected. Enum check.

irreversible_operations

array[string]

If present, each string must reference a specific SQL command flagged as irreversible. Null allowed.

rollback_data_integrity_checks

array[object]

Minimum 1 check. Each object must contain description (string) and validation_query (string, valid SQL). Schema check.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating database migration rollback tests and how to guard against it.

01

Irreversible Operation Detection Gap

What to watch: The model fails to flag DROP COLUMN, DROP TABLE, or data-destructive operations that cannot be rolled back without a snapshot. The generated test assumes rollback is always possible. Guardrail: Pre-scan the migration SQL for irreversible DDL and require the prompt to classify each operation's rollback feasibility before generating test cases.

02

Data Preservation Assertion Blindness

What to watch: Rollback tests verify schema structure but skip row-count and checksum comparisons, missing silent data loss or truncation during rollback. Guardrail: Require explicit before-and-after data assertions in the output schema, including row counts, checksums, and sampled value comparisons for critical columns.

03

Constraint Violation During Rollback

What to watch: The rollback script succeeds in isolation but fails in production because foreign key constraints, unique indexes, or not-null constraints are violated when data is restored. The generated test doesn't exercise constraints. Guardrail: Include constraint validation steps in the test template that verify all foreign keys, unique constraints, and check constraints remain satisfied after rollback.

04

Transaction Boundary Misalignment

What to watch: The migration and rollback are tested inside a single transaction that auto-rolls back, masking real commit-time failures like deferred constraint checks or lock timeouts. Guardrail: Require the test harness to commit the forward migration before attempting rollback, and include explicit lock timeout and deadlock detection checks.

05

Default Value and Type Coercion Drift

What to watch: Rollback restores columns but with different default values, type widths, or precision than the original schema, causing subtle application errors that pass basic schema checks. Guardrail: Add column metadata comparison assertions covering type, precision, default expression, and nullability before and after the full migration-rollback cycle.

06

Sequence and Auto-Increment State Loss

What to watch: Rollback resets sequences or auto-increment counters to incorrect values, causing primary key collisions on subsequent inserts. The generated test doesn't capture sequence state. Guardrail: Include sequence current-value snapshot and restoration verification in the test template, with explicit collision-detection inserts after rollback.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of generated database migration rollback tests before integrating them into a CI/CD pipeline.

CriterionPass StandardFailure SignalTest Method

Forward Migration Completeness

All DDL changes from the migration file are exercised in the forward test setup.

Test setup omits a new column, index, or constraint defined in the migration.

Diff the test's DDL execution log against the migration file's schema changes.

Rollback Integrity

The rollback test restores the schema to a state identical to the pre-migration snapshot.

Post-rollback schema dump differs from the pre-migration dump; residual objects remain.

Compare pg_dump --schema-only or equivalent before forward migration and after rollback.

Data Preservation

All pre-existing rows in affected tables are identical before migration and after rollback.

Row counts differ or checksums for pre-existing data do not match after rollback.

Run a COUNT(*) and a CHECKSUM or hash aggregate on affected tables before and after the full cycle.

Constraint Reinstatement

All unique, foreign key, and check constraints dropped in the forward migration are recreated with the same definition.

A constraint is missing or has a different name, column set, or condition after rollback.

Query information_schema.table_constraints and check_constraints before and after the cycle.

Irreversible Operation Detection

The prompt output explicitly flags any operation marked as irreversible or missing a down method.

The generated test silently passes or ignores a migration step that lacks a rollback definition.

Scan the test output for a dedicated warning section or a non-zero exit code for irreversible migrations.

Seed Data Isolation

Test data inserted during the forward phase is fully removed or isolated and does not contaminate the rollback verification.

Seed data rows are counted as pre-existing data, causing a false preservation failure.

Use a unique prefix or a dedicated schema for seed data and exclude it from the preservation checksum.

Transaction Wrapping

The entire forward-and-rollback cycle is wrapped in a transaction that is rolled back, leaving the database unchanged.

The test commits changes, requiring manual cleanup or leaving the database in a modified state.

Check the test harness for a BEGIN...ROLLBACK block or a framework-level transaction decorator.

Error Handling

The test fails with a clear message if the forward migration, rollback, or verification step encounters a SQL error.

The test hangs, times out, or reports a generic pass despite a mid-cycle constraint violation.

Introduce a deliberate syntax error in a copy of the migration and confirm the test exits non-zero.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON output schema with required fields: test_id, phase, description, expected_state, rollback_verification_query. Include retry logic for malformed outputs and log every generated test case with a trace ID.

Prompt modification

Add to [CONSTRAINTS]: Output must conform to the schema. If a migration contains DROP COLUMN, DROP TABLE, or TRUNCATE, flag it as IRREVERSIBLE and generate a data backup verification step before the rollback test.

Watch for

  • Silent format drift when models change
  • Missing human review gates for irreversible operations
  • Rollback tests that don't verify data preservation with actual row counts
Prasad Kumkar

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.