Skip to content

15 min read

Drizzle vs Prisma and the N+1 query problem

In one sentence: An ORM translates between your tables and your code: you ask for the data in TypeScript, it writes the SQL and TypeScript knows every column. In exchange, the SQL is no longer in sight, and an innocent loop can make one query per product: the N+1 problem. Turn on the log and count them.

What you will learn

  • Explain what an ORM and a query builder are, what they give you and what they hide from you.
  • Describe the tables in TypeScript with Drizzle, and know how Prisma differs.
  • Spot the N+1 problem by counting the queries in the log, and fix it with a single query.
  • Generate a migration with drizzle-kit and apply it with your own runner.

Before you start, read: 08-transactions.md

Ana wants the product list to say which categories each product is in: the Mug, in Home and Gifts. The categories live in another table, joined to the products by product_categories, as you saw in lesson 4, “Modeling”.

The first thing anyone thinks of: ask for the products and, for each one, its categories. It works. With four products that’s five QueryA command written in SQL for a database. Mostly the ones that ask for data (SELECT), whose answer is another table, although the ones that add, change or delete rows are called that too.Go to definition; with a thousand, a thousand and one. The list takes longer and longer, and no query is slow.

And another problem, a smaller one: since lesson 5, your SQL lives in strings. If you write price_cent, without the final “s”, TypeScript doesn’t see it. You find out when someone calls that route.

An ORM fixes the second problem, but it makes it easier to fall into the first one, and it hides it.

The analogy

You travel to Japan without speaking Japanese. At the restaurant, an interpreter talks to the waiter for you. Comfortable.

Now you ask what allergens each dish on the menu has. A careless interpreter goes to the kitchen for the first one, comes back, goes for the second… Twenty dishes, twenty trips. An attentive one asks for the whole list at once. You don’t hear the difference: you only notice it takes a while.

Where the analogy breaks down

  • An ORM always translates the same request the same way: if it does it badly, it always does it badly. And you can ask it to repeat out loud what it says: its log.
  • If the interpreter doesn’t know how to say something, you’re left without saying it. With an ORM, you can speak to PostgreSQL in SQL when you need to.

The code is the one in this lesson’s folder, 23-orm, with drizzle-orm 0.45.3. The outputs are from Node 26 and PostgreSQL 18.6.

From text with SQL to functions shaped like SQL

Section titled “From text with SQL to functions shaped like SQL”

Until now, each data function gave pg a string with SQL. There are three ways of talking to the database:

Tool What you write Who writes the SQL
The Driver (database)The package that lets a program talk to a database. It opens the connection, sends the queries using that database’s protocol and turns the answers into data in the program’s language. In Node.js, the most used one for PostgreSQL is pg.Go to definition, pg (lesson 5) The SQL, in a string You
A query builder Functions shaped like SQL: select, from, where It does, almost word for word
An ORM Which data you want, and with which relations It does, and it decides how

A Query builderA package that lets you write an SQL query with functions in the program’s language, one for each part (select, from, where), instead of as text. The editor checks the names of the tables and columns, and the values travel separately, as parameters.Go to definition writes the query with TypeScript functions. An ORMORM stands for Object-Relational Mapping.A package that translates between a database’s tables and a program’s objects. You ask for the data in the program’s language, it writes the SQL and gives you back each row as an object. Drizzle and Prisma are ORMs for TypeScript.Go to definition also translates between the tables and your program’s ObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition, and knows how the tables relate to each other. Drizzle, the one the course uses, does both.

Drizzle needs to know what your tables are like. You tell it in a new file, src/schema.ts:

src/schema.ts
export const products = pgTable(
'products',
{
id: integer().primaryKey().generatedAlwaysAsIdentity(),
name: text().notNull(),
priceCents: integer('price_cents').notNull(),
stock: integer().notNull().default(0),
},
(table) => [
check('products_price_cents_check', sql`${table.priceCents} > 0`),
check('stock_not_negative', sql`${table.stock} >= 0`),
],
);

Word by word:

  • pgTable('products', {…}) describes PostgreSQL’s products table. What it returns, products, is what you’ll use in the queries.
  • integer() and text() are the types; .notNull(), .primaryKey() and .default(0), the rules of the CREATE TABLE from lesson 4. .generatedAlwaysAsIdentity(), the GENERATED ALWAYS AS IDENTITY that numbers the id.
  • priceCents: integer('price_cents') gives two names: price_cents in PostgreSQL and priceCents in TypeScript. Drizzle translates, and the AS "priceCents" from lesson 5 disappears. If they have the same name, like name, one is enough.
  • check(…) are the CHECK constraints, with their names. sql`…` is a piece of SQL written by hand: it will come back at the end.

This file doesn’t create anything. The tables still come from your MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition; schema.ts describes to Drizzle what already exists. If they don’t match, Drizzle writes queries for other tables.

Drizzle is set up on top of the Connection poolA few connections to the database that a server keeps open and reuses. Each query takes a free one and gives it back when it’s done. Opening a connection costs much more than using it, and the database only accepts a limited number at a time.Go to definition you already have, in src/db.ts:

src/db.ts
// Drizzle, on top of the same pool: it doesn't open connections of its own, it uses pg's. schema
// gives it the tables and their relations (schema.ts). Transactions are done by db.transaction(),
// which does the same as lesson 8's inTransaction: a client from the pool, BEGIN, and COMMIT or
// ROLLBACK.
export const db = drizzle({ client: pool, schema });

drizzle({ client: pool, schema }) uses the connections of pg’s pool, and schema gives it the tables.

What you gain: TypeScript knows every column

Section titled “What you gain: TypeScript knows every column”

A query with Drizzle, in src/data.ts:

src/data.ts
export async function findOrder(id: number): Promise<Order | undefined> {
const [row] = await db.select().from(orders).where(eq(orders.id, id));
return row && toOrder(row);
}
  • It reads like the SQL: select from orders where the id is equal (eq) to the one that arrives.
  • eq(orders.id, id) becomes "orders"."id" = $1: the value still travels separately, as a parameter.
  • row already has its type. TypeScript knows that row.createdAt is a date, without you promising it with <OrderRow>, as in lesson 5.

Check it by breaking something. In listProducts, change products.priceCents to products.price_cents and check the types:

A column that doesn't exist

Ventana de terminal
npm run check

What you will see:

> shop-api@1.0.0 check
> tsc --noEmit
src/data.ts(82,64): error TS2551: Property 'price_cents' does not exist on type 'PgTableWithColumns<{ name: "products"; schema: undefined; columns: { id: PgColumn<{ name: "id"; tableName: "products"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; ... 7 more ...; generated: undefined; }, {}, {}>; name: PgColumn<...>; priceCents: PgColumn<.....'. Did you mean 'priceCents'?

The error arrives before anything runs, with the line and the column (yours may be different). The long part in the middle is how Drizzle describes the table: read the beginning and the end, “price_cents does not exist… Did you mean priceCents?” With the SQL in a string, only PostgreSQL would have said it, when it received the query. Undo the change.

What you don’t see: the SQL that really runs

Section titled “What you don’t see: the SQL that really runs”

Drizzle writes the SQL for you, and you don’t see it unless you ask for it with a log. examples/n-plus-one.ts sets up its own Drizzle, with a log that writes each query and counts them:

examples/n-plus-one.ts
// A Drizzle for this example, on top of the same pool, with a log of its own: it writes each query
// and counts it.
let queries = 0;
const db = drizzle({
client: pool,
schema,
logger: {
logQuery(query) {
queries++;
console.log(` SQL: ${query}`);
},
},
});

logQuery is a function Drizzle calls with each query before sending it; queries++ adds one. To see all the queries of your API, logger: true when creating db is enough: Drizzle writes them in the terminal, with their parameters.

The same example asks for the products with their categories in two ways. The first, the most direct:

examples/n-plus-one.ts
// WRONG: one query for the products and, after that, another for each product for its
// categories. With 4 products that's 5 queries; with 1000, 1001. Each one is a round trip to the
// database, and the loop waits for each one to come back before launching the next.
async function withNPlusOne() {
const list = await db.select().from(products).orderBy(asc(products.id));
const result = [];
for (const product of list) {
const its = await db
.select({ name: categories.name })
.from(productCategories)
.innerJoin(categories, eq(categories.id, productCategories.categoryId))
.where(eq(productCategories.productId, product.id))
.orderBy(asc(categories.id));
result.push({ name: product.name, categories: its.map((row) => row.name) });
}
return result;
}
  • The first query brings all the products.
  • for (const product of list) goes through the list and, for each one, makes another query for its categories. innerJoin is the INNER JOIN from lesson 2.
  • The await inside the loop waits for each answer before asking for the next one.

The second asks Drizzle for the products with their categories. For that, schema.ts tells it how the tables are joined:

src/schema.ts
// Relations don't change anything in the database: they tell Drizzle how the tables are joined,
// so it can ask for "the products with their categories" at once (with, in data.ts).
export const productsRelations = relations(products, ({ many }) => ({
categories: many(productCategories),
}));
export const productCategoriesRelations = relations(productCategories, ({ one }) => ({
product: one(products, {
fields: [productCategories.productId],
references: [products.id],
}),
category: one(categories, {
fields: [productCategories.categoryId],
references: [categories.id],
}),
}));

relations doesn’t change anything in the database: it tells Drizzle that a product has many (many) rows in product_categories, and each row, one (one) category, joined by those columns.

With that, the query:

examples/n-plus-one.ts
// RIGHT: a single query. with asks Drizzle for the products with their categories, and Drizzle
// writes SQL that brings it all at once, whether there are 4 products or 1000.
async function withOneQuery() {
const list = await db.query.products.findMany({
orderBy: asc(products.id),
with: {
categories: { with: { category: true }, orderBy: asc(productCategories.categoryId) },
},
});
return list.map((product) => ({
name: product.name,
categories: product.categories.map((row) => row.category.name),
}));
}

db.query.products.findMany is Drizzle’s ORM way: instead of writing the JOIN, you say what you want. with asks, for each product, for its rows in product_categories and, for each of them, its category.

The two ways, with the log on

Ventana de terminal
node --env-file=.env examples/n-plus-one.ts

What you will see:

== With N+1
SQL: select "id", "name", "price_cents", "stock" from "products" order by "products"."id" asc
SQL: select "categories"."name" from "product_categories" inner join "categories" on "categories"."id" = "product_categories"."category_id" where "product_categories"."product_id" = $1 order by "categories"."id" asc
SQL: select "categories"."name" from "product_categories" inner join "categories" on "categories"."id" = "product_categories"."category_id" where "product_categories"."product_id" = $1 order by "categories"."id" asc
SQL: select "categories"."name" from "product_categories" inner join "categories" on "categories"."id" = "product_categories"."category_id" where "product_categories"."product_id" = $1 order by "categories"."id" asc
SQL: select "categories"."name" from "product_categories" inner join "categories" on "categories"."id" = "product_categories"."category_id" where "product_categories"."product_id" = $1 order by "categories"."id" asc
Result: [{"name":"T-shirt","categories":["Clothing"]},{"name":"Mug","categories":["Home","Gifts"]},{"name":"Hoodie","categories":["Clothing"]},{"name":"Cap","categories":["Clothing","Gifts"]}]
Database queries: 5
== With one query
SQL: select "products"."id", "products"."name", "products"."price_cents", "products"."stock", "products_categories"."data" as "categories" from "products" "products" left join lateral (select coalesce(json_agg(json_build_array("products_categories"."product_id", "products_categories"."category_id", "products_categories_category"."data") order by "products_categories"."category_id" asc), '[]'::json) as "data" from (select * from "product_categories" "products_categories" where "products_categories"."product_id" = "products"."id" order by "products_categories"."category_id" asc) "products_categories" left join lateral (select json_build_array("products_categories_category"."id", "products_categories_category"."name") as "data" from (select * from "categories" "products_categories_category" where "products_categories_category"."id" = "products_categories"."category_id" limit $1) "products_categories_category") "products_categories_category" on true) "products_categories" on true order by "products"."id" asc
Result: [{"name":"T-shirt","categories":["Clothing"]},{"name":"Mug","categories":["Home","Gifts"]},{"name":"Hoodie","categories":["Clothing"]},{"name":"Cap","categories":["Clothing","Gifts"]}]
Database queries: 1

Count the SQL: lines. In the first way, one with the products and four identical ones, one per product, with its id in $1: five. In the second, one. The same result, with five queries or with one. If you get ECONNREFUSED, PostgreSQL isn’t running.

This is the N+1 problemA program asks the database for a list with one query and then makes one more for each item, instead of fetching everything together. With 1,000 products, that’s 1,001 round trips. It’s fixed with a JOIN or by asking for each relationship in one go.Go to definition: one query for the list and N more, one per item.

  1. Your API → PostgreSQLthe products
  2. PostgreSQL → Your API4 products
  3. Your API → PostgreSQLthe categories of 1
  4. PostgreSQL → Your APIClothing
  5. Your API → PostgreSQLthe categories of 2
  6. PostgreSQL → Your APIHome, Gifts
  7. Your API · PostgreSQL… and again for 3 and for 4

Each query is a round trip, with its LatencyHow long data takes to get from one place to another. It depends mostly on distance and on the routers along the way, and a faster plan (more bandwidth) barely improves it: that changes how much data fits per second, not how long each trip takes.Go to definition. If each trip takes 1 ms, a thousand products are a second spent just waiting.

And you fall into it without meaning to. In the ORMs that load relations when you touch them, like those of Ruby on Rails or Django, you don’t even see the loop: reading product.categories looks like reading a piece of data, and it makes a query. Drizzle and Prisma don’t load anything you don’t ask for.

You already know the query that brings everything at once: a Join (combining tables)The part of an SQL query that puts together the rows of two tables that match on a condition, such as each order with its product. If a row matches several in the other table, it comes out once for each one.Go to definition, the three-table one from lesson 2. In psql -d shop:

shop=> SELECT p.id, p.name, c.name AS category
FROM products AS p
LEFT JOIN product_categories AS pc ON pc.product_id = p.id
LEFT JOIN categories AS c ON c.id = pc.category_id
ORDER BY p.id, c.id;
id | name | category
----+---------+----------
1 | T-shirt | Clothing
2 | Mug | Home
2 | Mug | Gifts
3 | Hoodie | Clothing
4 | Cap | Clothing
4 | Cap | Gifts
(6 rows)

With LEFT JOIN, a product without categories comes out too. Six rows for four products: the Mug and the Cap come out twice, and your code would have to put them together.

The SQL Drizzle writes with with is the long one in the log. You don’t have to write it, but you do have to recognize it:

  • left join lateral (…): for each product, a SubqueryA query written in parentheses inside another one. The database works it out and the outer query uses its result, for example to compare each row with an average or to read from it as if it were a table.Go to definition with its rows from product_categories. Lateral means it can use the outer row, "products"."id".
  • json_agg(…) puts those rows together in a JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition array, in a single column.

Result: one row per product, with its categories inside, in a single trip.

Prisma is the other ORM widely used with TypeScript. This is how products would be described with it, in a schema.prisma file, in its own language (don’t install it: it’s for comparison):

model Product {
id Int @id @default(autoincrement())
name String
priceCents Int @map("price_cents")
stock Int @default(0)
@@map("products")
}

And a query, the products at €20 or less: prisma.product.findMany({ where: { priceCents: { lte: 2000 } } }).

Drizzle Prisma 7
The schema In TypeScript (src/schema.ts) In its own language (schema.prisma)
The queries Shaped like SQL: select().from().where() With objects: findMany({ where: … })
The types TypeScript takes them from the schema right away prisma generate writes a client into a folder of your project
The migrations drizzle-kit generates the SQL Prisma Migrate generates it and applies it (prisma migrate dev)
The relations with include

Since version 7, Prisma no longer starts its old engine written in Rust: it connects to PostgreSQL with an adapter, @prisma/adapter-pg, which uses pg underneath. With include it doesn’t do an N+1 either: it asks for each relation in one go.

The course uses Drizzle because its queries look like the SQL you’ve just learned, and what it writes is predictable. Prisma is a good choice if your team prefers not to think in SQL. Drizzle 1.0 is at the release candidate stage and changes, among other things, how relations are declared (defineRelations).

drizzle-kit writes the migration; your runner applies it

Section titled “drizzle-kit writes the migration; your runner applies it”

The new filter, GET /v2/products?category=gifts, searches product_categories by category_id. The Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition starts with product_id, and doesn’t help: it’s the order of the columns from lesson 7. An Index (database)A separate, sorted list with the values of one or more columns of a table and where each row is. With it, the database finds a few rows without reading the whole table. In exchange, it takes up disk space and every write has to update it.Go to definition is needed:

src/schema.ts
export const productCategories = pgTable(
'product_categories',
{
productId: integer('product_id')
.notNull()
.references(() => products.id, { onDelete: 'cascade' }),
categoryId: integer('category_id')
.notNull()
.references(() => categories.id, { onDelete: 'cascade' }),
},
(table) => [
primaryKey({ columns: [table.productId, table.categoryId] }),
// The primary key (product_id, category_id) already works for searching by product, because
// it starts with that column. To search by category (the ?category= filter) another index that
// starts with category_id is needed. Migration 004, generated by drizzle-kit, adds it.
index('product_categories_by_category').on(table.categoryId),
],
);

index('product_categories_by_category').on(table.categoryId) describes the index. But schema.ts doesn’t create anything: the migration is missing. That’s where drizzle-kit comes in, Drizzle’s tool for the schema. Its configuration, drizzle.config.ts:

drizzle.config.ts
// The configuration of drizzle-kit, Drizzle's tool for the schema. Here it only generates
// migrations: npm run db:generate -- --name=what-changes
// drizzle-kit compares src/schema.ts with the last snapshot of the schema it saved (drizzle/meta/)
// and writes into drizzle/ the SQL for what has changed. It doesn't apply it: that file is copied to
// db/migrations/ with the next number, and our runner applies it (npm run db:migrate), like the
// others. drizzle/0000_base.sql is the starting snapshot: the tables from migrations 001 to 003,
// which already existed. It's never applied.
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/schema.ts',
out: './drizzle',
});

schema is your tables file and out, the folder it writes to. Each time it generates, it saves a snapshot of the schema in drizzle/meta/; the next time, it compares schema.ts with that snapshot and writes only what has changed.

For the index, it wrote this, which becomes your migration 004:

db/migrations/004-categories-index.sql
CREATE INDEX "product_categories_by_category" ON "product_categories" USING btree ("category_id");

Why not apply it with drizzle-kit migrate, its own command? For two reasons:

  • Your database already has its history in the migrations table, from 001 to 003. drizzle-kit records its own in another one, __drizzle_migrations, and two lists of the same history end up saying different things.
  • drizzle-kit sees your tables, not your data. It doesn’t know that the products that were already there needed a starting stock: you still decide the steps from lesson 6.

So drizzle-kit writes the draft, you read it, and your runner applies it, like the others.

The stock UPDATE from lesson 8, with Drizzle:

src/data.ts
return db.transaction(async (tx): Promise<OrderResult> => {
// Lesson 8's conditional UPDATE, with the query builder: it reads almost the same as the SQL
// (SET stock = stock - $2 WHERE id = $1 AND stock >= $2). For the subtraction, a piece of SQL
// (sql`…`): with Drizzle, what matters here, that the check and the change go in the same
// query, stays in sight.
const taken = await tx
.update(products)
.set({ stock: sql`${products.stock} - ${quantity}` })
.where(and(eq(products.id, productId), gte(products.stock, quantity)))
.returning({ stock: products.stock });
  • db.transaction(async (tx) => …) is your inTransaction from lesson 8, a TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition: everything that goes through tx goes through the same client from the pool, between BEGIN and COMMIT or ROLLBACK.
  • gte is >=: the check stock >= quantity, in the same WHERE.
  • Drizzle has no function for “the stock minus the quantity”: it goes in SQL, sql`${products.stock} - ${quantity}`.

What goes in ${…} inside sql`…` travels as a parameter, not pasted into the text: it doesn’t open the door to SQL injectionSQL stands for Structured Query Language.An attack that sends a value crafted so that, pasted inside the text of a query, it changes what the query does, such as returning every row or deleting a table. It’s prevented by sending the values separately, as parameters, and never pasting them into the SQL.Go to definition. And the important thing from lesson 8, checking and taking in the same command, stays in sight.

SQL also wins at what the ORM can’t say, like the cursor comparison, (created_at, id) < (…), in src/pagination.ts, and in the reports with GROUP BY and subqueries from lesson 3. The ORM, for everyday things; SQL, where SQL is what matters.

The goal: count the queries yourself, and have your API give the categories with a single one.

You start from your project from lesson 8, “Transactions”, in ~/backend-course/phase-3/shop-api. Install Drizzle and drizzle-kit:

1. Install Drizzle

Ventana de terminal
npm install drizzle-orm@0.45.3
npm install --save-dev drizzle-kit@0.31.11

What you will see:

added 1 package, and audited 54 packages in 6s
6 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
npm warn deprecated @esbuild-kit/core-utils@3.3.2: Merged into tsx: https://tsx.hirok.io
npm warn deprecated @esbuild-kit/esm-loader@2.6.5: Merged into tsx: https://tsx.hirok.io
added 15 packages, and audited 69 packages in 9s
8 packages are looking for funding
run `npm fund` for details
4 moderate severity vulnerabilities
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.

drizzle-kit goes in --save-dev: the server doesn’t use it. Your number of packages may vary. The deprecated warnings and the 4 vulnerabilities come from an old esbuild inside drizzle-kit, and they affect a development server that drizzle-kit doesn’t start. Don’t run npm audit fix --force: it would replace drizzle-kit with the old 0.18.1.

Then, write the changes, or copy them from this lesson’s folder (below):

  1. Create src/schema.ts, still without the index line, and drizzle.config.ts. In package.json, add "db:generate": "drizzle-kit generate".
  2. In src/db.ts, create db and delete inTransaction, which is now db.transaction().
  3. Move src/data.ts, src/pagination.ts and src/middleware/idempotency.ts to Drizzle; whatever you haven’t seen here, copy it from the step.
  4. In src/problems.ts, PostgreSQL’s error arrives inside Drizzle’s, in cause. In src/schemas.ts, categories and the category filter.

The example and the tests come in the folder:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/23-orm.tar.gz
tar -xzf 23-orm.tar.gz
cd shop-api
cp ../23-orm/examples/n-plus-one.ts examples/
cp ../23-orm/test/*.ts test/

Run node --env-file=.env examples/n-plus-one.ts, as above, and count the SQL: lines of each way yourself. Then, add a fifth product in psql -d shop:

INSERT INTO products (name, price_cents) VALUES ('Pin', 200);
Challenge: with five products, run the example again. How many queries does each way make?Show answer
== With N+1
Database queries: 6
== With one query
Database queries: 1

The first grows with each product; the second doesn’t. Delete it afterwards with DELETE FROM products WHERE name = 'Pin';.

Start your API with npm run dev and, in another terminal:

2. The products, with their categories

Ventana de terminal
curl -s -w '\n' localhost:3000/v2/products
curl -s -w '\n' 'localhost:3000/v2/products?category=gifts'
curl -s -w '\n' localhost:3000/v1/products/2

What you will see:

[{"id":1,"name":"T-shirt","priceCents":2000,"stock":40,"categories":["Clothing"]},{"id":2,"name":"Mug","priceCents":850,"stock":60,"categories":["Home","Gifts"]},{"id":3,"name":"Hoodie","priceCents":3500,"stock":25,"categories":["Clothing"]},{"id":4,"name":"Cap","priceCents":1500,"stock":15,"categories":["Clothing","Gifts"]}]
[{"id":2,"name":"Mug","priceCents":850,"stock":60,"categories":["Home","Gifts"]},{"id":4,"name":"Cap","priceCents":1500,"stock":15,"categories":["Clothing","Gifts"]}]
{"id":2,"name":"Mug","price":8.5}

/v2 brings categories, a new field: it doesn’t break anyone (lesson 4 of Phase 4). ?category=gifts leaves the Mug and the Cap, regardless of capital letters, and /v1 doesn’t change. Your stock may be different.

First, the starting snapshot: what you already have, without the index.

3. The starting snapshot

Ventana de terminal
npm run db:generate -- --name=base

What you will see:

> shop-api@1.0.0 db:generate
> drizzle-kit generate --name=base
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'
6 tables
categories 2 columns 0 indexes 0 fks
idempotency_keys 6 columns 0 indexes 0 fks
orders 5 columns 1 indexes 1 fks
processed_events 2 columns 0 indexes 0 fks
product_categories 2 columns 0 indexes 2 fks
products 4 columns 0 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0000_base.sql 🚀

With no previous snapshot, drizzle-kit writes all the tables in drizzle/0000_base.sql. That file is never applied: your tables already exist, and it’s only there for comparing. fks are the Foreign keyA column that stores the primary key of a row in another table, such as the product number of each order. The database won’t let you save a value that doesn’t exist in the other table and, unless told otherwise, won’t let you delete a row that others point to either.Go to definition.

Now add the index line to schema.ts and generate again:

4. Only what has changed

Ventana de terminal
npm run db:generate -- --name=categories-index

What you will see:

> shop-api@1.0.0 db:generate
> drizzle-kit generate --name=categories-index
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'
6 tables
categories 2 columns 0 indexes 0 fks
idempotency_keys 6 columns 0 indexes 0 fks
orders 5 columns 1 indexes 1 fks
processed_events 2 columns 0 indexes 0 fks
product_categories 2 columns 1 indexes 2 fks
products 4 columns 0 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0001_categories-index.sql 🚀

Now product_categories has 1 indexes, and drizzle/0001_categories-index.sql is the CREATE INDEX from above. If you get No schema changes, you didn’t save schema.ts.

5. Your runner applies it

Ventana de terminal
cp drizzle/0001_categories-index.sql db/migrations/004-categories-index.sql
npm run db:migrate

What you will see:

> shop-api@1.0.0 db:migrate
> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 004-categories-index.sql

Only 004 was missing. With psql -d shop -c '\d product_categories', you’ll see the index under Indexes.

6. This lesson's tests

Ventana de terminal
npm test -- test/orm.test.ts

What you will see:

> shop-api@1.0.0 test
> node --env-file=test/.env --test --test-concurrency=1 test/orm.test.ts
✔ v2 shows the categories of each product, in the list and one by one (131.388255ms)
✔ a new product starts without categories and without stock (8.87415ms)
✔ ?category= filters, whatever the capital letters, and combines with the other filters (18.56151ms)
✔ an odd value in ?category= is only a value: it does not change the query (4.162421ms)
✔ v1 does not change: no categories and no category filter (18.336991ms)
✔ the contract documents the categories and the filter (15.134668ms)
✔ examples/n-plus-one.ts: N+1 queries versus a single one, with the same result (755.396624ms)
✔ migration 004, which drizzle-kit generated, creates the index by category (4.463315ms)
✔ drizzle-kit sees no pending changes: src/schema.ts and its migrations are up to date (1084.9514ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3092.403209

The last test runs drizzle-kit generate and expects No schema changes: if you change schema.ts without generating the migration, it fails. Your times will be different.

  • A website that takes longer the longer the list is, even though each item is small: very often it’s an N+1.
  • In the Network tab of DevTools, a page that makes a request to the API for each product in the list: the same problem, between the browser and the server.
  • An await with a query inside a for. That’s the N+1. Ask for the relation with with, or with a JOIN.
  • Changing schema.ts without a migration. Drizzle asks for a column your database doesn’t have, and PostgreSQL answers column … does not exist in the middle of a request.
  • Applying what drizzle-kit generates without reading it. When you rename a column, it asks whether it’s a rename or a new column; if you answer wrong, it deletes the old one with its data.
  • Believing everything in the ORM is safe from injection. sql`…` uses parameters, but sql.raw() pastes the text as is: never with something the client sends.
  • A query builder writes the SQL with functions; an ORM also knows the relations. Drizzle does both.
  • You gain: TypeScript knows every column. You lose: the SQL that runs is out of sight. Turn on the log.
  • The N+1 problem is one query for each item in a list. It’s fixed with a JOIN or by asking for the relation in one go (with in Drizzle, include in Prisma).
  • drizzle-kit generates the migration by comparing schema.ts with its last snapshot; you read it, and your runner applies it.
  • What the ORM can’t say goes in sql`…`, and its values are still parameters.
A shop’s product page was quick with 50 products, and now, with 2,000, it takes 3 seconds. In the log, each query takes about 1 ms. What’s the most likely cause?

With Drizzle, you write products.price_cents instead of products.priceCents. When do you find out?

You add discount: integer() to products in schema.ts and start the API, without doing anything else. What happens when you ask for the product list?

In the stock UPDATE, the quantity the client sends goes inside sql`${products.stock} - ${quantity}`. Can someone slip SQL in through there?

Your team uses Prisma. You add a field to schema.prisma, and your editor doesn’t find it in the client. What’s missing?

drizzle-kit has just generated the index migration. Why does the shop apply it with its runner and not with drizzle-kit migrate?

phase-5 · lesson 9/10