Skip to content

How to understand a Drizzle ORM codebase

Drizzle defines tables in TypeScript and offers two query styles: a SQL-like builder (`db.select().from(users)`) and a relational API (`db.query.users.findMany`). Because the schema is code, it can be split across many files, so finding it is the first step.

How to tell it's Drizzle ORM

  • drizzle-orm and drizzle-kit in package.json
  • drizzle.config.ts and schema files using pgTable, mysqlTable or sqliteTable
  • A drizzle/ folder of generated SQL migrations

Where things usually live

drizzle.config.ts
Where the schema lives, the migrations folder, the dialect.
src/db/schema.ts (or schema/)
Table definitions and relations(...).
src/db/index.ts
Creates db with the driver and passes the schema.
drizzle/
Migration SQL and snapshots.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. drizzle.config.ts, which points at the schema
  2. The schema files
  3. The db instance

How a request moves through the code

  1. 1Code imports db and table objects.
  2. 2It builds a query with the SQL-like or relational API.
  3. 3Drizzle generates SQL for the dialect and runs it through the driver.
  4. 4Results come back typed from the schema.

Questions to ask about the repository

  • List the tables and relations.
  • Which queries use the relational API, and which use joins?
  • Where are transactions used?

What trips people up

  • relations() only affects the relational query API; it doesn't create foreign keys.
  • If the schema isn't passed to drizzle(...), db.query is empty.