Claude Code से Production DB Migration सुरक्षित कैसे करें
Claude Code के साथ production DB migration: expand/contract, Prisma, CI, backfill, locks और rollback limits.
Production database migration को Claude Code को सिर्फ “schema बदल दो” कहकर नहीं सौंपना चाहिए। असली जोखिम SQL syntax में कम, और sequence में अधिक होता है। App deploy, database lock, backup, data backfill, feature flag, CI check और rollback decision एक-दूसरे से जुड़े होते हैं।
Claude Code तब उपयोगी है जब आप उसे पहले reviewer की तरह इस्तेमाल करते हैं, फिर implementation assistant की तरह। यह guide PostgreSQL और Prisma Migrate इस्तेमाल करने वाली teams के लिए है, लेकिन SQL migration folder चलाने वाली teams भी यही model अपना सकती हैं।
Review के समय official docs साथ रखें: Claude Code documentation, PostgreSQL के explicit locking और ALTER TABLE, Prisma के development and production और CLI reference, तथा GitHub Actions workflow syntax।
Expand/Contract Model
Production migration का सबसे सुरक्षित mental model expand/contract है। Expand का मतलब है database को पहले इतना बढ़ाना कि old app और new app दोनों चल सकें। Contract का मतलब है old column, old read path या temporary constraint को तब हटाना जब new path production में stable हो चुका हो।
flowchart LR
A["Backup and review"]
B["Expand: add nullable column or new table"]
C["Deploy code with dual write or feature flag"]
D["Backfill data in small batches"]
E["Validate staging and production metrics"]
F["Contract: add NOT NULL, remove old path"]
A --> B --> C --> D --> E --> F
Common mistake यह है कि Claude Code एक ही migration में column add, data copy, NOT NULL, और old column drop कर देता है। Local small database पर यह pass हो सकता है, लेकिन 80 lakh या 2 crore rows वाली table पर long lock, write block, timeout और data loss ला सकता है।
कुछ terms साफ रखें। Lock database का wait mechanism है ताकि incompatible operations एक ही table को एक साथ न बदलें। Backfill existing rows में new column values भरने की process है। Shadow database Prisma का temporary dev database है जिसमें migration history replay करके drift check होता है। यह production safety guarantee नहीं है।
पहले Review Prompt दें
पहला prompt file edit नहीं, review माँगना चाहिए। Table size, deploy style, ORM और recovery expectation साफ लिखें।
Review this database migration plan before editing files.
Context:
- Production database: PostgreSQL
- ORM: Prisma Migrate
- Hot tables: users has about 8 million rows, orders has about 25 million rows
- Deploy style: blue/green app deploy, database migration runs in CI/CD
- Requirement: split users.name into users.full_name and users.display_name
Check:
1. Can old and new app versions run at the same time?
2. Which SQL statements may take strong locks or scan the whole table?
3. Which steps must be expand, backfill, validate, and contract?
4. What backup or point-in-time recovery check is needed before deploy?
5. What can be rolled back by app deploy, and what can only be rolled forward?
Return a migration plan first. Do not edit files yet.
आखिरी line बहुत जरूरी है। Claude Code तेज है, पर database migration में deliberate pause चाहिए। अगर plan risky steps मिलाता है, तो उसे फिर constrain करें।
Rewrite the plan so that no step drops a column, rewrites a large table, or sets NOT NULL before the backfill is verified. Include a staging rehearsal and a production abort condition.
इससे Claude Code migration reviewer बनता है। Human risk decide करता है, और agent files, commands, SQL, CI checks और monitoring questions को व्यवस्थित करता है।
Expand SQL
मान लें users.name को आगे चलकर full_name और display_name से replace करना है। Expand migration केवल nullable columns और index add करती है। Backfill, NOT NULL, और old column drop अभी नहीं होते।
-- 20260602090000_expand_users_names.sql
-- Keep this migration small. Do not backfill and do not drop users.name here.
ALTER TABLE users
ADD COLUMN full_name text,
ADD COLUMN display_name text;
-- Run outside a transaction in PostgreSQL migration tools that support it.
-- CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
CREATE INDEX CONCURRENTLY IF NOT EXISTS users_display_name_idx
ON users (display_name);
PostgreSQL ALTER TABLE docs बताते हैं कि subcommand के आधार पर lock level बदलता है। अगर हल्का lock explicitly documented नहीं है, तो conservative review करें। Claude Code से lock level guess न करवाएँ, बल्कि official docs के आधार पर risk लिखवाएँ।
Prisma में migration पहले create करें, apply न करें।
npx prisma migrate dev --name expand-users-names --create-only
npx prisma validate
Prisma guide के अनुसार test और production में npx prisma migrate deploy इस्तेमाल होता है। वही guide यह भी बताती है कि migrate deploy pending migrations apply करता है, लेकिन drift detect नहीं करता और shadow database पर निर्भर नहीं रहता। इसलिए command pass होना full production rehearsal नहीं है।
npx prisma migrate deploy
App को compatible रखें
Expand के बाद app को old और new schema दोनों handle करने चाहिए। Read में fallback हो, और transition period में write old तथा new fields दोनों भरे।
// src/domain/userName.ts
type UserNameRow = {
name: string | null;
fullName: string | null;
displayName: string | null;
};
export function readDisplayName(user: UserNameRow): string {
return user.displayName ?? user.fullName ?? user.name ?? "Unknown user";
}
export function buildNameUpdate(input: { name: string }) {
const normalized = input.name.trim().replace(/\s+/g, " ");
return {
name: normalized,
fullName: normalized,
displayName: normalized.length > 40 ? `${normalized.slice(0, 39)}...` : normalized,
};
}
Feature flag database change और user-visible behavior को अलग करता है। New read path backfill validation तक off रखें। Error आए तो DB rollback करने के बजाय flag off या app rollback करें। Implementation के लिए Claude Code feature flags guide देखें।
यह pattern कम से कम तीन कामों में उपयोगी है: profile fields rename या split करना, invoice balance या search label जैसे calculated columns add करना, और high-traffic tables पर index या foreign key बाद में जोड़ना।
Backfill छोटे batches में करें
एक बड़ा UPDATE lock time, WAL volume, replica lag और operational risk बढ़ा सकता है। Claude Code से restartable batch script बनवाएँ।
// scripts/backfill-user-names.mjs
import pg from "pg";
const { Client } = pg;
const batchSize = Number(process.env.BATCH_SIZE ?? 1000);
const sleepMs = Number(process.env.SLEEP_MS ?? 200);
const client = new Client({ connectionString: process.env.DATABASE_URL });
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
await client.connect();
try {
let total = 0;
while (true) {
const result = await client.query(
`
WITH target AS (
SELECT id, name
FROM users
WHERE full_name IS NULL
AND name IS NOT NULL
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED
)
UPDATE users AS u
SET
full_name = target.name,
display_name = CASE
WHEN length(target.name) > 40 THEN substring(target.name from 1 for 39) || '...'
ELSE target.name
END
FROM target
WHERE u.id = target.id
RETURNING u.id
`,
[batchSize],
);
total += result.rowCount;
console.log(`updated=${result.rowCount} total=${total}`);
if (result.rowCount === 0) break;
await sleep(sleepMs);
}
} finally {
await client.end();
}
Production से पहले idempotency, partial failure, parallel execution और stop control review करें। अच्छा backfill batch size, pause, logs, abort condition और rerunnable query रखता है।
CI और Staging Checks
CI में temporary PostgreSQL पर पूरी migration history apply होनी चाहिए। GitHub Actions workflow .github/workflows में YAML file के रूप में रखा जाता है।
name: migration-check
on:
pull_request:
paths:
- "prisma/**"
- "scripts/backfill-*.mjs"
- ".github/workflows/migration-check.yml"
jobs:
prisma-migrations:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app
ports:
- "5432:5432"
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/app?schema=public
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- run: npm ci
- run: npx prisma validate
- run: npx prisma migrate deploy
- run: npx prisma migrate status
- name: Detect schema drift after migrations
run: |
npx prisma migrate diff \
--exit-code \
--from-config-datasource \
--to-schema=prisma/schema.prisma
यह example Prisma ORM v7 style config datasource arguments इस्तेमाल करता है। पुराने examples से --from-url या --shadow-database-url copy करने से पहले current CLI reference देखें।
Staging को CI से ज्यादा realistic रखें: similar row count, indexes, timeouts और वही migration runner। Claude Code से lock wait, replication lag, latency, app logs और abort thresholds की checklist बनवाएँ।
Contract और Rollback Limits
नई app stable और backfill verified होने के बाद ही contract करें। NOT NULL से पहले validation constraint लगाएँ।
-- 20260602120000_contract_users_names.sql
-- Run only after the new application version has been stable in production.
ALTER TABLE users
ADD CONSTRAINT users_full_name_present
CHECK (full_name IS NOT NULL) NOT VALID;
ALTER TABLE users
VALIDATE CONSTRAINT users_full_name_present;
ALTER TABLE users
ALTER COLUMN full_name SET NOT NULL;
ALTER TABLE users
DROP CONSTRAINT users_full_name_present;
-- Drop old columns in a later deploy, not in the same deploy that changes reads.
-- ALTER TABLE users DROP COLUMN name;
सबसे बड़ा भ्रम है कि down migration सब restore कर देगी। Dropped columns, overwritten values और lossy type conversions reverse SQL से वापस नहीं आते। अक्सर rollback app version या feature flag होता है। Database side पर backup, point-in-time recovery या forward fix चाहिए।
prisma migrate resolve --rolled-back successful migration undo नहीं करता। यह failed migration history state resolve करता है। Claude Code से हर plan में app rollback, DB forward fix और data restore required अलग-अलग लिखवाएँ।
Team Workflow
Common failures ये हैं: rename को drop and add समझना, schema change और huge data rewrite को एक migration में रखना, shadow database को production rehearsal मान लेना, और backup check को verbal assumption पर छोड़ देना।
DB rules CLAUDE.md में लिखें: hot table column drop same PR में नहीं, large backfill schema migration में नहीं, Prisma migration --create-only से SQL review के लिए बने, और review में official docs links हों। Structure के लिए CLAUDE.md best practices पढ़ें।
Revenue-critical SaaS में खराब migration billing, signup और support रोक सकती है। ClaudeCodeLab के products reusable prompts और checklists देते हैं, और Claude Code training real repository में यह workflow लगाने में मदद करता है।
Practical use में सबसे बड़ा सुधार clever SQL से नहीं आया। सुधार तब आया जब एक PR में कम काम रखा गया: expand-only PR, separate backfill job, और बाद का contract PR। SQL से पहले abort conditions और recovery steps लिखवाने की आदत production risk कम करती है।
Summary
Claude Code production DB migration को अपने-आप सुरक्षित नहीं बनाता। यह तब मजबूत होता है जब team उसे safe model देती है: expand/contract, staged app deploy, small backfills, CI checks, staging rehearsal, feature flags और clear rollback limits।
अगली migration में पहले risk review माँगें। Plan ठीक लगे तो ही Claude Code से SQL, Prisma migration, GitHub Actions workflow और backfill script लिखवाएँ।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.