Drizzle ORM gives a NestJS API SQL-shaped queries with TypeScript types inferred straight from your schema files, with no generated client to keep in sync.
This guide wires the two together with the pattern we recommend: one injectable database provider, a typed schema, services that return DTOs, transactions that stay correct under concurrent requests, migrations that are reviewed before they run, and the failure modes we hit on a live multi-tenant system.
Key Takeaways
- Expose Drizzle through one
@Global()NestJS module with a factory provider and an injection token, close the postgres.js client inonApplicationShutdown(), and callapp.enableShutdownHooks()so that hook runs onSIGTERM.- Infer row types with
$inferSelectand$inferInsertinstead of writing interfaces by hand.- Check and change a stock count in one conditional
UPDATE … RETURNING, and answer 409 Conflict when no row comes back.- Use
drizzle-kit generateplusdrizzle-kit migratefor anything that reaches production; keepdrizzle-kit pushfor local databases. The migrator runs every pending file in one transaction, soCREATE INDEX CONCURRENTLYhas to be its own step.timestamp()columns default to date mode: a JSON date string written straight into.set()or.values()throws a 500 unless you convert it to aDatefirst.- If you set a tenant on a reserved connection for Row-Level Security,
db.transaction()needs its own route through the pool.
The stack this guide uses
The versions in this guide are the ones the ECOSIRE platform (ecosire.com) runs: a NestJS 11 API on PostgreSQL 17 with drizzle-orm 0.45, drizzle-kit 0.31 and the postgres.js 3.4 driver. The code samples target the drizzle-orm 0.x line. Two notes on 1.0:
- The Drizzle documentation now installs the 1.0 release candidate (
npm i drizzle-orm@rc postgres;1.0.0-rc.5when this guide was updated), while a plainnpm i drizzle-ormstill installs 0.45. Schema declarations and the SQL-shaped builder (select,insert,update,transaction) are written the same way on both lines. - The relational query API is not. On 0.x you declare relations per table with
relations(), pass them todrizzle()insideschema, and givedb.queryawherebuilt from operators such aseq(). Drizzle 1.0 removes that API (Relational Queries v1): you declare every relation once withdefineRelations(), create the database withdrizzle({ client, relations }), and writewhereas a plain object, for exampledb.query.customers.findMany({ where: { email } }). Drizzle's v1-to-v2 migration page still shows the old API asdb._query, which the 1.0 betas kept (1.0.0-beta.22 has it), but Drizzle's v0-to-v1 breaking-changes list says Relational Queries v1 is removed, and the 1.0.0-rc.5 types have no_query. Port those queries instead of planning to keep them. The querying section shows both forms.
Project setup
Install
npm install drizzle-orm postgres
npm install -D drizzle-kit
postgres.js ships its own TypeScript types, so there is no @types/pg to add. That package belongs to the other driver, node-postgres (pg).
drizzle-kit configuration
drizzle.config.ts tells drizzle-kit where the schema lives and where to write migrations. This is the shape we use:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/schema/index.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
The database module
Create the client once and give every service the same instance through dependency injection. A symbol token avoids string collisions, and OnApplicationShutdown closes the pool so tests and rolling restarts do not leave connections behind (on a signal, only once shutdown hooks are enabled; see main.ts below).
// database.module.ts
import { Global, Inject, Injectable, Module, OnApplicationShutdown } from '@nestjs/common';
import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
export const PG_CLIENT = Symbol('PG_CLIENT');
export const DRIZZLE = Symbol('DRIZZLE');
export type Database = PostgresJsDatabase<typeof schema>;
@Injectable()
class PgShutdown implements OnApplicationShutdown {
constructor(@Inject(PG_CLIENT) private readonly client: postgres.Sql) {}
async onApplicationShutdown() {
await this.client.end({ timeout: 5 });
}
}
@Global()
@Module({
providers: [
{
provide: PG_CLIENT,
useFactory: () =>
postgres(process.env.DATABASE_URL!, {
max: 20,
idle_timeout: 30,
connect_timeout: 10,
max_lifetime: 60 * 30,
}),
},
{
provide: DRIZZLE,
inject: [PG_CLIENT],
useFactory: (client: postgres.Sql): Database => drizzle({ client, schema }),
},
PgShutdown,
],
exports: [DRIZZLE],
})
export class DatabaseModule {}
The pool options are the ones our API runs with. max is per process: with two cluster workers, max: 20 can open 40 connections, and that total has to fit inside the server's max_connections alongside everything else that connects. Size the pool against the whole deployment, not one process.
Turn on shutdown hooks in main.ts
onApplicationShutdown() does not run on a signal by default. Nest calls the shutdown hooks when you call app.close() yourself, or when the process receives a signal such as SIGTERM and you called app.enableShutdownHooks() at bootstrap. Nest leaves them off by default because the signal listeners consume resources.
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Without this, SIGTERM never reaches onApplicationShutdown() and the pool is never closed.
app.enableShutdownHooks();
await app.listen(process.env.PORT ?? 3000);
}
void bootstrap();
This matters most on rolling restarts. Each old process is stopped with a termination signal while its replacement starts, and without the call, Nest skips the hook that ends the postgres.js pool. onApplicationShutdown() is the last step of the shutdown sequence and runs after the server's connections have closed, so the pool outlives the requests that use it. One caveat from the NestJS docs: shutdown hooks have limited support on Windows, where SIGTERM never works.
Schema definition
Tables are plain TypeScript. Foreign keys use a callback so the order of declarations does not matter, and indexes sit next to the columns they serve.
// schema/orders.ts
import { index, numeric, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
export const customers = pgTable('customers', {
id: uuid('id').primaryKey().defaultRandom(),
email: text('email').notNull().unique(),
name: text('name').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
export const orders = pgTable(
'orders',
{
id: uuid('id').primaryKey().defaultRandom(),
customerId: uuid('customer_id')
.notNull()
.references(() => customers.id),
status: text('status').notNull().default('draft'),
total: numeric('total', { precision: 12, scale: 2 }).notNull(),
placedAt: timestamp('placed_at'),
},
(t) => [index('orders_customer_idx').on(t.customerId)],
);
export type Order = typeof orders.$inferSelect;
export type NewOrder = typeof orders.$inferInsert;
numeric comes back as a string, which is what you want for money: it never passes through a JavaScript float. Convert it at the edge, in the DTO, if a client needs a number.
Relations (0.x)
// schema/relations.ts
import { relations } from 'drizzle-orm';
import { customers, orders } from './orders';
export const customersRelations = relations(customers, ({ many }) => ({
orders: many(orders),
}));
export const ordersRelations = relations(orders, ({ one }) => ({
customer: one(customers, { fields: [orders.customerId], references: [customers.id] }),
}));
Export the relations from the same schema object you pass to drizzle(), or db.query.* will not see them. On 1.0, this file becomes a single defineRelations() call, shown at the end of the next section.
Querying
Drizzle has two read styles: a SQL-shaped builder and the relational query API.
import { and, desc, eq, gte } from 'drizzle-orm';
// SQL-shaped: you choose the columns, the joins and the order
const recent = await db
.select({ id: orders.id, total: orders.total, email: customers.email })
.from(orders)
.innerJoin(customers, eq(orders.customerId, customers.id))
.where(and(eq(orders.status, 'paid'), gte(orders.placedAt, since)))
.orderBy(desc(orders.placedAt))
.limit(50);
// Relational (0.x): nested objects, one round trip
const customer = await db.query.customers.findFirst({
where: eq(customers.email, email),
with: { orders: true },
});
On drizzle-orm 1.0 the relational query reads differently, because relations are declared once and passed to drizzle() in place of schema:
// drizzle-orm 1.0 (Relational Queries v2)
import { defineRelations } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
export const relations = defineRelations(schema, (r) => ({
customers: {
orders: r.many.orders(),
},
orders: {
customer: r.one.customers({ from: r.orders.customerId, to: r.customers.id }),
},
}));
const client = postgres(process.env.DATABASE_URL!);
const db = drizzle({ client, relations });
// where is a plain object; { email } is shorthand for { email: email }
const customer = await db.query.customers.findFirst({
where: { email },
with: { orders: true },
});
The SQL-shaped query above it is unchanged on 1.0.
Writes return what you ask for:
const [created] = await db
.insert(orders)
.values({ customerId, total: '149.00' })
.returning();
await db
.update(orders)
.set({ status: 'paid', placedAt: new Date() })
.where(eq(orders.id, id));
// Upsert on a unique column
await db
.insert(customers)
.values({ email, name })
.onConflictDoUpdate({ target: customers.email, set: { name } });
Services that return DTOs
Inject the token, build conditions only for the filters the caller sent, and map rows to a response shape. Returning raw rows leaks every column you add to the table later.
// orders.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { and, desc, eq, type SQL } from 'drizzle-orm';
import { DRIZZLE, type Database } from '../database.module';
import { orders } from '../schema';
export interface OrderListQuery {
status?: string;
customerId?: string;
limit?: number;
}
@Injectable()
export class OrdersService {
constructor(@Inject(DRIZZLE) private readonly db: Database) {}
async list(q: OrderListQuery) {
const conditions: SQL[] = [];
if (q.status) conditions.push(eq(orders.status, q.status));
if (q.customerId) conditions.push(eq(orders.customerId, q.customerId));
const rows = await this.db
.select()
.from(orders)
.where(conditions.length ? and(...conditions) : undefined)
.orderBy(desc(orders.placedAt))
.limit(Math.min(q.limit ?? 20, 100));
return rows.map((r) => ({ id: r.id, status: r.status, total: r.total, placedAt: r.placedAt }));
}
}
Cap the page size on the server. A list endpoint without a ceiling is a slow query waiting for a large tenant.
Transactions
db.transaction() hands you a tx object. Every query on it commits together or not at all: if the callback throws, Drizzle rolls the transaction back and the call rejects with that error. A nested tx.transaction() becomes a savepoint, and PostgreSQL options such as isolationLevel go in the second argument.
The classic mistake is to read a value, check it in JavaScript and then write it back. Two orders for the last unit both read on_hand = 1, both pass the check, and under PostgreSQL's default read committed level the stock goes to −1. Raising the level to repeatable read stops the oversell, but the second order then fails with SQLSTATE 40001 ("could not serialize access due to concurrent update"), and unless you retry it, the customer gets a 500. Do the check and the change in one statement instead:
import { ConflictException } from '@nestjs/common';
import { and, eq, gte, sql } from 'drizzle-orm';
// inventory: a table with sku and on_hand columns, declared like orders above
const order = await db.transaction(async (tx) => {
// Check and decrement in one statement. A concurrent order for the same SKU waits for
// this row lock, then PostgreSQL re-checks on_hand >= qty against the committed value.
const [stock] = await tx
.update(inventory)
.set({ onHand: sql`${inventory.onHand} - ${qty}` })
.where(and(eq(inventory.sku, sku), gte(inventory.onHand, qty)))
.returning({ onHand: inventory.onHand });
if (!stock) throw new ConflictException(`Not enough stock for ${sku}`);
const [created] = await tx.insert(orders).values({ customerId, total }).returning();
return created;
});
This runs at the default read committed level and needs no retry. When two orders race, the second UPDATE waits for the first to commit, then evaluates its WHERE clause again against the updated row. If too little stock is left, no row comes back. Throwing ConflictException then rolls the transaction back and gives the caller a 409 Conflict. tx.rollback() aborts too, but it throws Drizzle's TransactionRollbackError, which is not an HttpException, so Nest's built-in exception filter answers it with a 500. If the check cannot be written into the UPDATE, lock the row first with .for('update') on the select, still under read committed, then decide and write.
When you do need repeatable read or serializable
Some rules span rows that a single UPDATE cannot express. Under repeatable read and serializable, PostgreSQL aborts a transaction that would break isolation with SQLSTATE 40001, and expects the application to run the whole transaction again. Drizzle wraps a failed query in a DrizzleQueryError and keeps the driver's error in cause, while a failure at COMMIT comes straight from postgres.js, so check both places for the code:
// 40001 serialization_failure; 40P01 deadlock_detected (PostgreSQL also advises retrying deadlocks)
const RETRYABLE = new Set(['40001', '40P01']);
function sqlState(err: unknown): string | undefined {
const e = err as { code?: unknown; cause?: { code?: unknown } } | null;
const code = e?.code ?? e?.cause?.code;
return typeof code === 'string' ? code : undefined;
}
export async function withRetry<T>(run: () => Promise<T>, attempts = 3): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await run();
} catch (err) {
const code = sqlState(err);
if (attempt >= attempts || !code || !RETRYABLE.has(code)) throw err;
}
}
}
const result = await withRetry(() =>
db.transaction(
async (tx) => {
// reads, decisions and writes: all of it reruns on a retry
},
{ isolationLevel: 'serializable' },
),
);
Retry the whole callback, never one statement inside it, and keep side effects out of it, because it can run more than once.
Keep transactions short and free of network calls. Send the email or the webhook after the commit, not inside the callback, so a slow third party never holds row locks.
Migrations
| command | what it does | where to use it |
|---|---|---|
drizzle-kit push | diffs the schema against the database and applies the change directly | local and throwaway databases |
drizzle-kit generate | writes a versioned SQL file from the schema diff | always, before production |
drizzle-kit migrate | applies every pending SQL file, in one transaction, and records each in the migrations table | CI or the deploy step |
Read every generated file before it ships. A renamed column can come out as a drop and an add, and the drop deletes the data.
One transaction for the whole batch
drizzle-kit migrate (0.31) calls drizzle-orm's own migrator, and in drizzle-orm 0.45 that migrator opens one transaction for all pending files. Every statement of every pending file runs inside it, and nothing commits until the last one succeeds. The 1.0 release candidate's migrator does the same. Two PostgreSQL rules then decide whether a migration can run while the API is live:
- Locks are held until the whole batch commits. Most forms of
ALTER TABLEtake anACCESS EXCLUSIVElock, and PostgreSQL holds a lock until the end of the transaction that took it. AnALTER TABLEin the first pending file therefore blocks every read and write on that table until the last pending file has finished. While it waits for a long-running query to release the table, every new query on that table queues behind it. Start each migration that alters a busy table withSET LOCAL lock_timeout, so a blocked change fails fast instead of stalling the API, and keep slow backfills out of the batch that alters a hot table. CREATE INDEX CONCURRENTLYcannot go in a drizzle-kit migration. PostgreSQL refuses to run it inside a transaction block, and this migrator always opens one.
A migration that changes a busy table starts like this. SET LOCAL lasts until the end of the transaction, which here is the whole batch, and the migrator splits each file into separate statements at the --> statement-breakpoint markers:
SET LOCAL lock_timeout = '5s';
--> statement-breakpoint
ALTER TABLE "orders" ADD COLUMN "channel" text;
Build a concurrent index out of band, as its own deploy step before drizzle-kit migrate, with one statement per psql -c:
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 \
-c 'CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_placed_at_idx ON orders (placed_at);'
psql "$DATABASE_URL" -Atc \
"select indisvalid from pg_index where indexrelid = 'orders_placed_at_idx'::regclass;"
Declare the same index, with the same name, in the schema, so that drizzle-kit generate still creates it on a fresh database. In the generated file, change that statement to CREATE INDEX IF NOT EXISTS, so it does nothing on a database where the step above already built the index. Check indisvalid afterwards. A concurrent build that fails leaves an INVALID index behind, and IF NOT EXISTS would skip it on the next run. Drop it and build again.
Since PostgreSQL 11, adding a column with a constant default no longer rewrites the table. Adding one with a volatile default, or changing a column's type, still can.
Production lessons from our own API
These are failures we hit running NestJS and Drizzle on a live multi-tenant system, and the fix that stuck for each.
1. Do not connect at import time
Our database package creates the postgres.js pool on first use, not when the module is imported. Scripts, test files and build steps import the schema without needing a database, and a missing DATABASE_URL should fail the first query with a clear error, not crash every import. In a NestJS-only codebase, the factory provider recommended above gives you the same thing: nothing connects until the module is instantiated.
2. Date strings in date-mode columns are a 500
A timestamp() column defaults to mode: 'date', and Drizzle calls toISOString() on the value while building the query. JSON can only carry strings, so spreading a request body into .set() throws value.toISOString is not a function, and the caller sees a 500. We now run every update payload through one helper: it reads the table's columns with getTableColumns() and converts strings on date columns to Date. An unparsable value becomes a 400 that names the field.
import { BadRequestException } from '@nestjs/common';
import { getTableColumns, type Table } from 'drizzle-orm';
export function coerceDateColumns<T extends Record<string, unknown>>(table: Table, data: T): T {
const out: Record<string, unknown> = { ...data };
for (const [key, column] of Object.entries(getTableColumns(table))) {
const value = out[key];
if (column.dataType !== 'date' || (typeof value !== 'string' && typeof value !== 'number')) continue;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) throw new BadRequestException(`Invalid date value for "${key}"`);
out[key] = parsed;
}
return out as T;
}
Use mode: 'string' instead on columns where you want strings end to end. The helper is written for 0.x. On drizzle-orm 1.0, getTableColumns() is deprecated in favour of getColumns(), and a date-mode timestamp reports its dataType as 'object date' rather than 'date', so update the check when you move.
3. Row-Level Security changes how transactions reach the database
To let PostgreSQL enforce tenant isolation, we reserve one connection per request with postgres.js client.reserve(), set the tenant on it with set_config('app.current_org', orgId, false), and give the request a Drizzle instance built on that connection. Ordinary queries work unchanged. Transactions did not: the reserved connection has no begin() method, so every db.transaction() reached from an authenticated request failed with this.client.begin is not a function. Unit tests with a mocked database never saw it.
The fix routes transactions through the pool and sets the tenant again inside them, transaction-local (set_config(..., true)), so the setting ends at commit and never reaches the connection's next borrower. Release the reserved connection in a finally, after clearing the setting. The policy side of this setup is in our Drizzle + Postgres Row-Level Security guide.
4. Keep raw SQL parameterized
The sql template tag sends interpolated values as parameters, so the inventory.onHand - qty update in the transaction example is safe. sql.raw() inserts text verbatim. We do not allow it on any path that can carry user input, and our review checklist treats a new sql.raw() as a defect.
Testing
We test services at two levels:
- Unit tests instantiate the service directly with a mocked database. They are fast and cover branching logic. In our mocks, a select chain resolves at
.limit()and an insert or update at.returning(). - Integration tests run against a real PostgreSQL and a real driver. Lesson 3 above is the reason: the failure lived in the driver, so no mock could have caught it. Anything touching transactions, Row-Level Security or migrations belongs in this tier.
For the test runner itself, see Vitest with NestJS.
Frequently Asked Questions
How does Drizzle compare to Prisma in a NestJS project?
Drizzle schemas are TypeScript files and queries read like SQL, with types inferred directly, so there is no client generation step. Prisma uses its own schema language and generates a client from it. Both work well with NestJS. Teams that think in SQL tend to prefer Drizzle; teams that want a higher-level data model tend to prefer Prisma.
Should we use postgres.js or node-postgres with Drizzle?
Both are supported first-class drivers, imported from drizzle-orm/postgres-js and drizzle-orm/node-postgres. We run postgres.js: one pool, simple configuration and its own types. Pick one per service and do not mix them, because each driver brings its own pool.
Is drizzle-kit push safe for production?
No. push applies the diff directly, with no reviewed file and no migration history. Use generate to write SQL you can read, test it against a copy of production data, and apply it with migrate.
How do we stop a migration from locking a busy table?
Set lock_timeout inside the migration so it fails instead of queueing, and remember that drizzle-kit applies every pending file in one transaction, so its locks last until the whole batch commits. Build indexes with CREATE INDEX CONCURRENTLY as a separate step outside drizzle-kit, and split a risky change into steps, for example: add a nullable column, backfill in batches, then add the constraint.
Do we need DTOs if Drizzle already infers types?
Yes. Inferred types describe the table, and DTOs describe the API contract. Mapping rows to a DTO keeps new columns, internal flags and tenant identifiers out of responses.
Next steps
If you are building or hardening a NestJS and Drizzle API, start with the database module and the date-coercion helper above. The first gives every service one pool and closes it cleanly; the second turns a malformed date into a 400 that names the field, where it would otherwise be a 500. For multi-tenant data, read the Row-Level Security guide next.
ECOSIRE builds and integrates business APIs, including connections between custom services and ERPs. Talk to us about your API, or see our Odoo integration services.
Written by
ECOSIRE Research and Development TeamTechnical Writing
The ECOSIRE technical writing team covers Odoo ERP, Shopify eCommerce, AI agents, Power BI analytics, GoHighLevel automation, and enterprise software best practices. Our guides help businesses make informed technology decisions.
ECOSIRE
Grow Your Business with ECOSIRE
Enterprise solutions across ERP, eCommerce, AI, analytics, and automation.
Related Articles
Odoo Hosting Requirements in 2026: Server Sizing by User Count (With Real Configs)
Odoo hosting requirements by user count: vCPU, RAM, storage, and worker settings for 5 to 250+ users, plus PostgreSQL tuning values from real deployments.
Drizzle ORM + Postgres Row-Level Security for Multi-Tenancy 2026
Implement multi-tenant SaaS with Drizzle ORM and Postgres Row-Level Security: schema, policies, session variables, NestJS integration, real production patterns.
Drizzle vs Prisma in 2026: We Run Drizzle on 66 Production Schemas — Honest Comparison
We run Drizzle ORM on 66 production schemas. Honest Drizzle vs Prisma 2026 comparison: schema design, migrations, performance, DX — and when Prisma wins.