Blog

Claude Code database migration: A safe, practical workflow

Goon Nguyen•Claude Code Guides••15 min read

Claude Code database migration: A safe, practical workflow

A Claude Code database migration workflow uses AI assistance to draft plans, generate assets, and prepare validation while enforcing strict human controls. Because faulty migration code can trigger table locks or data loss, production write credentials must stay strictly isolated from the agent. This eight-stage framework ensures all changes undergo rigorous local testing and human approval before running through controlled deployment automation.

Claude Code database migration: A safe, practical workflow

What Claude Code can and cannot do for a Claude Code database migration

The following matrix describes recommended workflow policy, not universal product restrictions.

Operation

Claude Code role

Human approval

Read repository schema and migrations

Inspect authorized files

Repository scope

Review sanitized metadata

Compare supplied evidence

Data-sharing scope

Draft plans and migrations

Propose changes

Plan before editing

Generate tests and validation queries

Prepare reviewable assets

Coverage and query review

Run disposable-environment commands

Execute approved tests

Commands and environment

Access staging

Only within explicit scope

Separate authorization

Read production, optionally

Restricted, reviewed access

Privacy and query limits

Obtain production write access

Excluded

Keep credentials external

Deploy to production

Prepare artifacts only

Protected deployment approval

Repair production

Support authorized analysis

Incident owner controls repair

Appropriate Claude Code responsibilities

Claude Code can draft SQL migration scripts and support ORM synchronization—keeping object-relational mapping models aligned with schema changes. Schema introspection requires supplied metadata or authorized tools.

Mandatory human responsibilities

Humans confirm production assumptions, review material changes, authorize deployment and recovery, and verify business outcomes. An AI-generated explanation is not independent verification. Read-only access still risks sensitive-data exposure and expensive queries. Anthropic’s Claude Code documentation on permissions and security provides the product-level reference; access policy remains your responsibility.

Context Claude Code needs before generating a migration

Plausible migration code can be wrong when the environment description is incomplete. Supply evidence before requesting changes.

Input

Why it matters

Safe way to provide it

Database engine and exact version

Determines operation behavior

Reviewed environment manifest

ORM/migration tool and version

Establishes framework compatibility

Dependency files and conventions

Schema and migration paths

Locates definitions and history

Scoped repository access

Applied migration state and drift

Reveals deployment differences

Sanitized status export

Affected models, queries, APIs, jobs

Identifies readers and writers

Relevant application files

Table size and distributions

Informs testing and execution

Approved aggregates

Deployment order and compatibility

Exposes release overlap

Release plan and version inventory

Technical context

Repository migration history is not proof of applied state. Stale schema files, unapplied migrations, and manual database changes require reconciliation. Include Prisma, Alembic, Flyway, or your actual framework’s conventions in the CLAUDE.md context. Do not substitute generic commands.

Production reality

Record volume, nulls, duplicates, legacy values, concurrent writes, and lock sensitivity shape production-like data. For users.timezone, identify every writer - including older application instances - and the product-approved source of existing users’ values. Missing inputs become questions, not assumptions.

Security and access boundaries

Prefer schema-only exports and sanitized aggregates. Sanitization should preserve useful distributions without exposing customers.

Privacy boundary: Keep credentials and customer records out of prompts, screenshots, and committed files. MCP (Model Context Protocol, a tool-connection interface) integrations require the same access review.

A safe Claude Code database migration workflow

  1. Inspect the existing state.
  2. Classify the migration risk.
  3. Require a written migration plan.
  4. Generate the migration and supporting assets.
  5. Review the generated change.
  6. Test against a disposable production-like database.
  7. Approve and deploy through controlled automation.
  8. Monitor and verify the result.

This Claude Code migration workflow separates drafting, verification, and production authority.

Claude Code database migration: A safe, practical workflow

Step 1 - Inspect the existing state

Ask Claude Code to inspect schema, migrations, application dependencies, and supplied deployed-state evidence without editing files. Compare definitions with actual applied state.

For users.timezone, identify missing values and every process creating users. A human confirms evidence freshness and resolves conflicting inputs. Proceed with a current-state summary listing dependencies, assumptions, and unanswered questions - not an inferred production schema.

Step 2 - Classify the migration risk

Have Claude Code assess data loss, locks, table rewrites, backfill volume, compatibility, and recovery feasibility. A backfill populates existing records separately from the schema change.

The reviewer assigns a conditional risk rating and required controls. Record the reasons, not just a label. Unknown row counts or unresolved deployment overlap should block approval rather than receive optimistic estimates.

Step 3 - Require a written migration plan

Require operation order, application releases, validation, monitoring, stop conditions, recovery, and anticipated files. Approve this plan before generation.

For the timezone change, use expand–migrate–contract: introduce a compatible schema, transition application behavior and data, then enforce stricter requirements. Explicitly account for old writers and concurrent writes. A one-time backfill cannot establish completeness while incompatible writers remain active.

Step 4 - Generate the migration and supporting assets

Claude Code generates framework-aligned migrations, model changes, tests, validation queries, and recovery notes. Never silently rewrite already-applied migration files. Humans confirm package scope. Large backfills should be bounded and restartable where appropriate, with reviewed retry behavior and progress tracking. Choose batch limits from environment evidence; no universal batch size or dry-run command applies across frameworks.

Step 5 - Review the generated change

Compare the patch with the approved request. Review defaults, constraints, types, cascades, indexes, and generated SQL where available.

A human checks database-specific behavior against the deployed version’s documentation. Transactions and DDL (data definition language) operations behave differently across engines. PostgreSQL’s ALTER TABLE and CREATE INDEX references illustrate why operation-level review matters. Record concerns and resolutions against an identifiable artifact.

Step 6 - Test against a disposable production-like database

Test fresh setup and upgrades from the deployed schema. An empty-database test does not validate existing-record behavior.

Include missing and invalid timezone values, overlapping application versions, concurrent writes, interruption, and restart. Require data integrity validation, application tests, and recovery evidence. Rollback verification applies only when reversal is the chosen strategy. Staging timing informs planning; it does not guarantee production timing.

Illustrative validation artifact - not executed evidence: Environment: disposable database matching the target engine/version.Dataset: synthetic existing users, missing timezones, invalid legacy values, and concurrent writers. Checks: upgrade, reader/writer compatibility, restartability, constraint readiness, recovery. Observed outcomes: not measured; deployment remains blocked pending recorded results.

Step 7 - Approve and deploy through controlled automation

Verify the target environment, artifact identity, recovery readiness, approver, incident owner, and deployment mechanism. Approval covers a specific revision; material changes require renewed review.

Established deployment automation executes the migration without giving the agent production write credentials. Capture execution records and apply predefined stop conditions. A backup’s existence alone is insufficient: recovery must be feasible within the change’s operational requirements.

Step 8 - Monitor and verify the result

Check application behavior and records, not merely exit status. Monitor errors, lock waits, latency, replication lag where relevant, and scheduled jobs.

For timezone changes, verify that new writes remain complete and notifications follow the approved policy. Humans decide whether to proceed, pause, or recover. Delay transitional-code removal until compatibility is demonstrated and the observation criteria are satisfied.

Stage

Claude Code contribution

Human decision

Evidence

Inspect

Compare context

Resolve unknowns

State summary

Classify

Identify hazards

Set controls

Risk rationale

Plan

Sequence work

Approve approach

Approved plan

Generate

Draft assets

Confirm scope

Migration package

Review

Explain changes

Accept patch

Reviewed revision

Test

Run permitted checks

Accept coverage

Test/recovery report

Deploy

Prepare handoff

Authorize release

Execution record

Verify

Summarize evidence

Proceed/pause/recover

Outcome report

Risk classification and migration review checklist

Migration risk assessment starts with provisional categories. Engine/version, workload, table size, deployment method, and application dependencies can change any rating.

Risk level

Typical examples

Minimum controls

Low

Additive, backward-compatible changes

Review, upgrade tests, recovery consideration

Medium

Indexes, constraints, bounded backfills

Lock assessment, realistic testing, monitoring

High

Destructive changes, conversions, large rewrites, sensitive transformations, engine changes

Specialist review, staged execution, tested recovery, explicit authorization

Low-risk migrations

An additive column may be a low-risk starting classification. Defaults, dependencies, and engine behavior can still introduce blocking or correctness problems.

Medium-risk migrations

Indexes, constraints, and backfills can become high risk on large or busy tables. Assess table locks and resource pressure before choosing execution methods.

High-risk migrations

Destructive DDL can remove structures and data. A live-column rename also creates compatibility risk, even without deleting records.

Cross-engine migration requires a separate plan, behavioral compatibility checks, and specialist review. This schema-change workflow is not sufficient.

Copyable migration review checklist

  • Correct database engine and exact version recorded.
  • Deployed schema and applied migration state verified.
  • Existing records checked against intended requirements.
  • Destructive operations and conversions explicitly reviewed.
  • Defaults and timezone value policy justified.
  • Backfills bounded, observable, and restartable where needed.
  • Lock and rewrite behavior assessed.
  • Old and new application versions remain compatible.
  • Concurrent writes and background jobs covered.
  • Fresh setup and realistic upgrade tests completed.
  • Change-specific recovery tested.
  • Post-deployment validation and stop conditions defined.
  • Named reviewer approves the artifact and environment.
Local success is not production proof. If production contains unexpected nulls, reassess test distributions and incoming writers - not just the constraint statement.

Copy this checklist into the migration pull request and attach evidence to each approval-critical item.

Claude Code guardrails for database changes

Use three layers: instructions guide behavior, automated checks detect problems, and external controls enforce boundaries. CLAUDE.md guardrails are not a security boundary.

Claude Code database migration: A safe, practical workflow

Copy-ready CLAUDE.md rules

## Database migration rules
- Do not connect to production or execute production migrations.
- Never request, store, or use production write credentials.
- Inspect schema, migration history, and supplied applied-state evidence first.
- State assumptions and missing information; do not invent inputs.
- Obtain written plan approval before changing files.
- Flag destructive operations, conversions, constraints, indexes,
and large backfills for explicit review.
- Prefer staged, backward-compatible changes.
- Never silently rewrite already-applied migrations.
- Generate tests, validation queries, and change-specific recovery notes.
- Execute tests only in explicitly approved disposable environments.
- Stop autonomous actions immediately on uncertain state or an
unexpected production migration failure; notify the incident owner.
- Never equate successful execution with proven safety.

Deterministic verification hooks

Run framework validation, SQL linting, disposable-database migration tests, and integration tests. CI (continuous integration) should check prohibited patterns and required review. Pattern detection can miss semantic hazards. Passing a linter does not establish correct timezone values, acceptable locking, or recoverability.

Local hooks are not equivalent to protected CI gates. Anthropic’s Claude Code hooks documentation describes configuration mechanisms; verify supported behavior for your installed release before implementing hooks.

Credential and MCP Boundaries

Separate environments, use least privilege, restrict tools, protect secrets, and audit access. Check inherited shell variables and connection profiles, not only explicit agent configuration. MCP is optional and does not automatically supply deployment controls. A connected database tool inherits the risks of its credentials and exposed operations.

Keep protected deployment approvals outside agent-editable configuration. Copy the repository rules, then verify the external controls that make the production boundary enforceable.

How to respond when an AI-generated migration fails

Stop autonomous retries and repairs immediately after an unexpected production failure or uncertain database state. Do not allow a speculative repair attempt first.

Stop, preserve and diagnose

  1. Stop automated retries and further agent-issued changes.
  2. Assign an incident owner.
  3. Preserve errors, logs, commands, migration artifacts, and available state evidence.
  4. Determine whether the migration never applied, fully rolled back, partially applied, or completed incorrectly.

A failed database migration does not imply automatic reversal. Transactional behavior depends on the engine, framework, and operations involved. Preserve evidence before altering migration status records.

Choose the recovery path

Path

Decision requirement

Rollback

Reversal is verified and data-preserving; schema reversal alone cannot recover deleted or overwritten data.

Restore

A validated recovery point exists; subsequent writes may be lost or require reconciliation.

Forward repair

Correcting observed state presents less risk than reversing the change.

Incident recovery requires owner approval for production repair. Not every framework provides safe automatic down migrations. There is no universal rescue command. Controlled experimentation in a disposable database is separate from production recovery.

Validate before reopening traffic

Perform data integrity validation, application read/write tests, and operational monitoring. For timezone changes, verify notification behavior as well as field completeness.

If traffic was restricted, reopen it against explicit acceptance criteria. Do not indiscriminately stop a shared production database.

Reusable prompt for planning a Claude Code database migration

This Claude Code migration prompt separates planning from editing and execution. Replace placeholders with approved context, not credentials.

Migration planning prompt

Plan a database migration. Do not edit files or execute changes.

Context:
- Database engine and exact version: <engine/version>
- ORM/migration tool and version: <tool/version>
- Schema path: <path>
- Migration history path: <path>
- Applied-state/drift evidence: <approved evidence>
- Requested change: <change>
- Approximate production size and distributions: <details>
- Deployment and compatibility constraints: <constraints>
- Relevant application files and jobs: <paths>
- Approved value policy: <policy or unresolved question>

Requirements:
1. Inspect supplied files and evidence before proposing changes.
2. Summarize current state, readers, writers, and dependencies.
3. List assumptions, missing information, and conflicting evidence.
Do not invent missing inputs.
4. Classify risk and explain locks, rewrites, compatibility,
data correctness, and recovery concerns.
5. Propose an ordered schema/application/data rollout.
6. Plan production-like testing, validation, monitoring,
stop conditions, and change-specific recovery validation.
Distinguish planned tests from tests actually executed.
7. List anticipated file changes.
8. Wait for explicit plan approval before editing.

Boundaries:
- No production connections or modifications.
- No destructive execution.
- Stop when database state is uncertain and request clarification.

How to adapt the prompt

  • Include framework conventions and explicitly approved commands.
  • Add realistic distributions, concurrent writers, and release-overlap constraints.
  • Escalate cross-engine work to a separate migration plan with behavioral compatibility testing.

Worked example - Adding a required field without breaking existing data

Illustrative scenario: A B2B SaaS application introduces users.timezone for scheduled notifications. This is a design example, not a documented deployment result.

Unsafe one-step approach

Immediately enforcing a required field can fail when existing users lack values or older writers still omit them. A large data backfill may create operational pressure.

An automatic UTC default may satisfy a constraint while scheduling notifications incorrectly. A valid identifier is not necessarily the user’s correct timezone.

Safer staged approach

Apply expand–migrate–contract through four phases:

  1. Expand: Add a compatible nullable column.
  2. Transition application behavior: Deploy compatible readers and writers using a product-approved source or documented fallback policy.
  3. Migrate: Backfill in controlled batches; reconcile writes occurring during the transition.
  4. Contract: Retire incompatible writers, verify completeness, and approve the non-null constraint. Remove transitional logic later.

Claude Code drafts the plan, code, tests, and validation assets. Humans approve value semantics and release gates. Do not infer timezone from weak signals merely to complete records.

Evidence required before contracting

Require:

  • No unexpected nulls.
  • Valid identifiers and a justified value policy.
  • Complete new writes.
  • Retired incompatible application versions.
  • Acceptable observed performance.
  • Recovery readiness and human approval.

If these conditions fail, postpone the constraint rather than manufacture values.

Claude Code database migration: A safe, practical workflow

Frequently asked questions

What is Claude Code database migration?

Claude Code database migration is the process of leveraging Anthropic’s terminal-based coding agent to inspect, plan, draft, and validate database schema changes. It automates repetitive SQL generation, ORM synchronization, and test-case creation while relying on human oversight for production deployment and data-integrity validation.

Can Claude Code execute migrations directly on my production database?

Technically, Claude Code can be configured to execute commands, but it is highly recommended to isolate production environments. Always keep write-access credentials restricted. Use Claude Code to draft migration files in a local, disposable environment, then deploy through your standard, authorized CI/CD release pipeline.

Is Claude Code capable of handling cross-engine database migrations?

Claude Code can help draft translated schemas and queries, but cross-engine migration is a separate project. It needs its own plan, behavioral compatibility testing against the source system, and specialist review; this schema-change workflow is not sufficient.

What should I do if an AI-generated migration fails in production?

Immediately stop all automated retries or further agent-issued changes. Identify the incident owner to preserve logs, executed commands, and state evidence. Depending on the observed damage, choose between a verified data-preserving rollback, a clean restoration from a known good point, or a manual forward-repair authorized by your engineering lead.

How can I ensure Claude Code's migrations are reversible?

Decide the recovery strategy first: rollback, restore, or forward repair. If reversal is chosen, test it in a disposable production-like environment and confirm it preserves data, since schema reversal alone cannot recover deleted or overwritten values.

Does Claude Code understand my production data scale?

No, Claude Code is typically blind to live production row counts, index fragmentation, and data distribution. Because an operation that is fast on 1,000 rows can lock a table of 80 million rows, you must verify all migration plans against realistic staging data volumes before proceeding to production.

Read more:

Conclusion

A reliable Claude Code migration workflow turns AI assistance into reviewable artifacts rather than unchecked production access. Because generated code is only part of a safe release, production credentials must stay isolated from the agent. By requiring staged changes, realistic tests, and post-deployment proof, this process ensures every database modification is backed by verified evidence rather than confident claims.

Share this article