Drizzle Migration Schema Diff

Evolve a Drizzle PostgreSQL schema with generated SQL migrations, reviewing column additions as nullable first, then backfilling safely.

TypescriptNodeData Integrity

Code

typescriptsnippet
38 lines
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-core and drizzle-orm are 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

FAQ

Does this require external packages?
Yes — `drizzle-orm/pg-core` and `drizzle-orm`. Add them to your project before running the snippet.