# Drizzle

Use Drizzle ORM with KeelDB through node-postgres or postgres.js, with queries on the pooled host and drizzle-kit migrations on the direct host.

Drizzle ORM talks to KeelDB through a regular PostgreSQL driver. Use the pooled host for your app and the direct host for `drizzle-kit`, which runs migrations and introspection in sessions of its own.

Copy both connection strings from the database's **Overview** page:

```bash
# .env
DATABASE_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1-pooler.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10"
DIRECT_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10"
```

## Install

With node-postgres:

```bash
npm install drizzle-orm pg
npm install --save-dev drizzle-kit @types/pg dotenv
```

## Schema and client

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

export const notes = pgTable("notes", {
  id: bigint({ mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
  title: text().notNull(),
  createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
});
```

```ts
// src/db/index.ts
import { drizzle } from "drizzle-orm/node-postgres";
import * as schema from "./schema";

export const db = drizzle(process.env.DATABASE_URL!, { schema });
```

```ts
import { desc } from "drizzle-orm";
import { db } from "@/db";
import { notes } from "@/db/schema";

await db.insert(notes).values({ title: "First note" });
const latest = await db.select().from(notes).orderBy(desc(notes.id)).limit(20);
```

In a Next.js app, create the client in a module imported only by server code, and read [Next.js](/docs/nextjs) for when queries run.

### With postgres.js

```bash
npm install drizzle-orm postgres
```

```ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

const client = postgres(process.env.DATABASE_URL!, { max: 5 });
export const db = drizzle(client);
```

KeelDB's pooler supports the protocol-level prepared statements both drivers use. If you see `prepared statement ... does not exist` through the pooled host, pass `prepare: false` to `postgres()`.

## Migrations with drizzle-kit

```ts
// drizzle.config.ts: drizzle-kit uses the direct host
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

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

```bash
# Write SQL migration files from schema changes (no database needed)
npx drizzle-kit generate

# Apply pending migrations to KeelDB
npx drizzle-kit migrate
```

`drizzle-kit migrate` records applied migrations in a table in a schema named `drizzle`. Your owner role can create that schema, so nothing needs setting up first. Read each generated SQL file before you apply it; it is plain SQL you can edit.

To apply migrations from code instead, for example in a release step:

```ts
// scripts/migrate.ts
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";

const db = drizzle(process.env.DIRECT_URL!);
await migrate(db, { migrationsFolder: "./drizzle" });
await db.$client.end();
```

`drizzle-kit push` applies schema changes without migration files. It is handy on a [branch](/docs/branching) while you prototype; use generated migrations for production.

## Test a migration on real data

Create a branch of your production database, run `drizzle-kit migrate` with the branch's direct string as `DIRECT_URL`, and check the result before you touch production. On Free and Launch the branch is a copy-on-write copy, ready in seconds. [Preview environments per pull request](/docs/branching#preview-environments-per-pull-request) automates this in GitHub Actions.

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `drizzle-kit migrate` fails or hangs | It is using the pooled host. Set `dbCredentials.url` to the direct host. |
| `prepared statement ... does not exist` with postgres.js | Pass `prepare: false` to `postgres()` for the pooled host. |
| Timeouts on the first query after idle time | A sleeping Free or Launch database is waking. Raise `connect_timeout` to `30`; see [Waking a sleeping database](/docs/connect#waking-a-sleeping-database). |
