Drizzle Migration Schema Diff
Evolve a Drizzle PostgreSQL schema with generated SQL migrations, reviewing column additions as nullable first, then backfilling safely.
Code
import { pgTable, text, integer, timestamp, index } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
// 初始 schema(drizzle/0000_init.sql 由 drizzle-kit generate 产出)
const invoices = pgTable('invoices', {
id: integer('id').primaryKey(),
customer: text('customer').notNull(),
createdAt: timestamp('created_at').defaultNow(),
});
// 增量迁移:新增可空列 → 回填 → 收紧约束
const ADD_COLUMN = sql`
ALTER TABLE invoices
ADD COLUMN due_date timestamp;
`;
const BACKFILL = sql`
UPDATE invoices
SET due_date = created_at + interval '30 days'
WHERE due_date IS NULL;
`;
const TIGHTEN = sql`
ALTER TABLE invoices
ALTER COLUMN due_date SET NOT NULL;
`;
async function applySteps(db, steps: ReturnType<typeof sql>[]) {
for (const step of steps) {
await db.execute(step);
}
await db.execute(sql`
CREATE INDEX IF NOT EXISTS invoices_due_date_idx
ON invoices (due_date);
`);
}
console.log('three-step migration prepared: add, backfill, tighten');How the snippet works
The code’s whole job belongs to the function applySteps.
for (const step of steps) is the loop that carries the per-item work. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. From drizzle-orm/pg-core it pulls pgTable, text, integer, timestamp, index — the imports name exactly which library surface the snippet touches.
Points of care
- Plan for an install step:
drizzle-orm/pg-coreanddrizzle-ormare a real dependency, resolved by the package manager.
Applying it
The main signature reads async function applySteps(db, steps: ReturnType<typeof sql>[])
Statements that matter
await db.execute(step);
await db.execute(sql`
CREATE INDEX IF NOT EXISTS invoices_due_date_idx
ON invoices (due_date);
`);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.
FAQ
- Does this require external packages?
- Yes — `drizzle-orm/pg-core` and `drizzle-orm`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.