Drizzle ORM with Postgres: schema to first migration

Set up Drizzle ORM with PostgreSQL in TypeScript: a Docker database, a typed schema, reviewable SQL migrations, a second migration done safely, and migrate on deploy.

Drizzle is the ORM I reach for when I want the database to stay visible. The schema is TypeScript, the migrations are plain SQL files you can read in a pull request, and the query builder looks enough like SQL that you never wonder what it is doing. This post walks through a clean setup with PostgreSQL: a local database in Docker, a schema, a first migration, a second one, and the step that runs migrations when the app deploys.

If you have read my post on [Prisma migrations you can actually review](/journal/prisma-migrations-you-can-actually-review-in-a-pull-request), the goal here is the same. Every schema change becomes a file, the file gets reviewed, and production only ever runs files that were reviewed.

What you need

  • Node 20 or newer.
  • Docker, for a throwaway local Postgres.
  • A TypeScript project. An Express API is fine; nothing below cares which framework sits on top.

One note on versions before anything else. As of this writing, the official PostgreSQL getting-started guide installs the 1.0 release candidate with the `@rc` tag. The schema, config and migration commands in this post match that guide. Whatever you install, pin it in `package.json` and read the changelog before you bump it. An ORM is not the dependency you want floating.

A local Postgres that starts clean

I keep the local database in a compose file so anyone can bring it up with one command and throw it away with another. I covered the reasoning in [a local run that starts clean and leaves clean](/journal/a-local-run-that-starts-clean-and-leaves-clean).

# compose.yaml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    ports:
      - "5433:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:
docker compose up -d db

I map it to 5433 on purpose. If a Postgres is already running on the machine, the default port is taken, and a quiet connection to the wrong database is a bad way to spend an afternoon.

Then the connection string goes in `.env`, which stays out of git:

DATABASE_URL=postgres://app:app@localhost:5433/app

Install

npm i drizzle-orm@rc pg dotenv
npm i -D drizzle-kit@rc tsx @types/pg

`drizzle-orm` is the runtime. `drizzle-kit` is the CLI that diffs your schema and writes migrations, so it is a dev dependency. `pg` is the node-postgres driver. Drizzle also supports postgres.js; pick one and stay with it.

The config

Drizzle Kit reads one config file from the project root:

// drizzle.config.ts
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

`out` is where migration files land. That folder gets committed. `schema` points at the file, or folder, that holds your table definitions.

The schema

Here is a small schema with two tables and a foreign key. It is enough to show the parts you use every day: identity columns, defaults, a unique constraint and a reference.

// src/db/schema.ts
import {
  integer,
  pgTable,
  text,
  timestamp,
  varchar,
} from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  email: varchar({ length: 255 }).notNull().unique(),
  displayName: varchar("display_name", { length: 120 }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

export const posts = pgTable("posts", {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  authorId: integer("author_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  title: varchar({ length: 200 }).notNull(),
  body: text().notNull(),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

A few choices worth calling out:

  • **Identity columns over serial.** `generatedAlwaysAsIdentity()` is the modern Postgres way to do auto-increment ids. The PostgreSQL docs on identity columns explain why it behaves better than `serial` around permissions and copies.
  • **Explicit snake_case names.** The TypeScript property is `displayName`, the column is `display_name`. Whoever opens psql later will thank you.
  • **Timestamps with time zone.** Always. Storing local time without a zone is a bug that waits for daylight saving time.

Push versus generate

Drizzle Kit gives you two ways to get that schema into a database, and the difference matters.

`drizzle-kit push` compares your schema to the live database and applies the difference directly. No files. It is fast and great while you are sketching tables on a laptop.

`drizzle-kit generate` compares your schema to the last migration snapshot and writes a SQL file. `drizzle-kit migrate` then applies any files the database has not seen yet.

My rule is simple. Push is for a local database I am about to throw away. Anything that touches a shared or production database goes through generate and migrate, because that is the only path that leaves a reviewable file behind. The migrations fundamentals page lays out all the options if your team works database-first instead.

The first migration

npx drizzle-kit generate --name=init

That writes a SQL migration under `drizzle/` along with a snapshot Drizzle uses for the next diff. Open the SQL. It should look like what you would have written by hand:

CREATE TABLE "users" (
  "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (...),
  "email" varchar(255) NOT NULL,
  "display_name" varchar(120) NOT NULL,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
  CONSTRAINT "users_email_unique" UNIQUE("email")
);

I trimmed the identity options above; the generated file spells them out. The point is that nothing is hidden. If the SQL surprises you, fix the schema and generate again before you commit, not after.

Apply it:

npx drizzle-kit migrate

Drizzle records which migrations have run in its own table, so running `migrate` again does nothing. That is exactly what you want from a deploy step.

Querying

The client takes the connection string directly:

// src/db/index.ts
import "dotenv/config";
import { drizzle } from "drizzle-orm/node-postgres";

export const db = drizzle(process.env.DATABASE_URL!);

And queries read like SQL with types attached:

// src/demo.ts
import { desc, eq } from "drizzle-orm";
import { db } from "./db";
import { posts, users } from "./db/schema";

async function main() {
  const [author] = await db
    .insert(users)
    .values({ email: "dev@example.com", displayName: "Dev" })
    .returning({ id: users.id });

  await db.insert(posts).values({
    authorId: author.id,
    title: "Hello",
    body: "First post.",
  });

  const recent = await db
    .select({
      title: posts.title,
      author: users.displayName,
      createdAt: posts.createdAt,
    })
    .from(posts)
    .innerJoin(users, eq(posts.authorId, users.id))
    .orderBy(desc(posts.createdAt))
    .limit(10);

  console.log(recent);
}

main().then(() => process.exit(0));
npx tsx src/demo.ts

The type of `recent` comes from the select object, not from a generated client. Rename a column in the schema and every query that uses it breaks at compile time, which is the whole reason to use a typed ORM.

If you want the insert and select types elsewhere, say for an API layer, Drizzle infers them from the table:

export type NewPost = typeof posts.$inferInsert;
export type Post = typeof posts.$inferSelect;

The second migration is the real test

Anyone can generate an init migration. The second one shows whether the workflow holds up. Say posts need a slug:

slug: varchar({ length: 200 }).notNull().unique(),
npx drizzle-kit generate --name=add_post_slug

Read the SQL before you go further. It will add a `NOT NULL` column to a table that may already have rows, and Postgres will refuse that on any table with data in it. This is the moment a reviewable file earns its keep. You have three honest options:

1. Add the column as nullable, backfill it, then make it `NOT NULL` in a later migration. 2. Give it a default that makes sense, if one exists. 3. Edit the generated SQL by hand to add and fill the column in one step, as long as the end state matches the schema.

I usually take the first one. Two small migrations are easier to review and easier to undo than one clever one. Generated SQL is a first draft, and you are allowed to change it before it ships.

Running migrations on deploy

On a server I do not run `drizzle-kit` at all. It is a dev dependency, and the production install should not need it. Drizzle ships a runtime migrator that applies the same files from inside Node:

// src/db/migrate.ts
import "dotenv/config";
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";

const db = drizzle(process.env.DATABASE_URL!);

await migrate(db, { migrationsFolder: "./drizzle" });
console.log("Migrations applied");
process.exit(0);

The deploy script runs that once, before the new release starts taking traffic. On my DigitalOcean VPS it sits right after the build and right before the symlink swap I described in [release folders and a symlink](/journal/release-folders-and-a-symlink-so-a-deploy-can-roll-back). If the migration fails, the swap never happens and the old release keeps serving.

Two things to keep in mind there:

  • **Take a backup first.** A rollback of code is a symlink. A rollback of data is a restore. `pg_dump` before the migrate step is cheap insurance.
  • **Write migrations that the old code can survive.** For a few seconds, or longer if something goes wrong, the old release runs against the new schema. Adding columns and tables is safe. Dropping or renaming them should wait until the code that used them is gone.

Where Drizzle fits

Drizzle is a thin layer. It does not hide SQL, it does not run a query engine beside your app, and it expects you to know what an index is. If your team wants the ORM to make database decisions for it, that is a reason to look elsewhere. If you want typed queries, readable migrations and a schema that lives next to the code, it is a very good fit.

The workflow is the part to keep regardless of the tool: generate a file, read the file, commit the file, and let production run only what was reviewed.

Some links in this post are referral links.

Back to Journal