Typed queries with an ORM in a feature
Build one Taskboard feature, changing a task's status, with Drizzle: define tables once, get typed queries, and see what the compiler catches and misses.
Typed queries with an ORM in a feature
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An ORM like Drizzle lets you describe tables in TypeScript once and derive row types and query checks from that description.
- Drizzle's query builder stays close to SQL, so you can read a query and know what the database will run.
- The compiler checks column names, value types and required fields, but it cannot check that the query is fast or that your data matches reality.
- Selecting only the columns a screen needs gives you a smaller type and less data over the wire.
- Keep database access in a small feature module so the API handler calls a function with a clear input and output.
Raw SQL and its blind spot
Raw SQL is fine. It is also a string, and a string is invisible to the compiler:
const result = await pool.query("select id, titel from tasks where status = $1", ["finished"]);
Two mistakes in one line: a misspelled column and a status that does not exist. Both are found at runtime, if at all. The result is also untyped, so result.rows[0].id is any, and the compiler can’t help you use it.
An ORM (object-relational mapper) or query builder closes that gap by letting TypeScript know your tables. The backend roadmap compares the options in ORMs, query builders and raw SQL, and the Node roadmap covers Prisma and Drizzle. This lesson is about the full-stack angle: using one in a feature, and being clear about what the types do and don’t promise.
Describe the table once
Taskboard uses Drizzle ORM (0.45.4 when I ran this). You declare a table in TypeScript:
import { pgTable, serial, text, integer, timestamp } from "drizzle-orm/pg-core";
export const tasks = pgTable("tasks", {
id: serial().primaryKey(),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
assigneeId: integer("assignee_id").references(() => users.id, { onDelete: "set null" }),
title: text().notNull(),
status: text({ enum: ["todo", "doing", "done"] }).notNull().default("todo"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
The JavaScript name (projectId) maps to the column name (project_id), which settles the naming seam from the first lesson in one place. The enum option tells TypeScript the legal statuses. It does not create a database constraint on its own, which is why the CHECK from the previous lesson still matters. In a real project you would generate the SQL from this definition with Drizzle Kit; in my scratch project I wrote the SQL by hand and kept the two in step manually.
From that one definition you get types for free:
type TaskRow = typeof tasks.$inferSelect; // a row you read
type NewTask = typeof tasks.$inferInsert; // a row you write
One feature: change a task’s status
Here is the whole data-access side of “mark done”:
type Status = (typeof tasks.$inferSelect)["status"];
export async function setStatus(db: Db, id: number, status: Status) {
const [row] = await db
.update(tasks)
.set({ status })
.where(eq(tasks.id, id))
.returning();
return row; // the task row, or undefined if no such id
}
I ran it on a seeded database. setStatus(db, 1, "done") returned the row with status done and the title Task 001 invoice. .returning() asks Postgres to hand back the updated row, so one round trip both writes and reads.
Two details matter at the seam. First, row can be undefined when the id doesn’t exist, and the type says so. The API handler has to turn that into a 404 and cannot ignore it. Second, the function takes status: Status, not a string. A caller can’t pass "finished", and the handler’s Zod schema from the shared package is what makes sure a request can’t either.
You can see the SQL Drizzle will send, which keeps the builder honest:
db.select({ id: tasks.id }).from(tasks)
.where(and(eq(tasks.projectId, 1), eq(tasks.status, "todo"))).limit(3).toSQL()
select "id" from "tasks" where ("tasks"."project_id" = $1 and "tasks"."status" = $2) limit $3 [ 1, 'todo', 3 ]
Values go in as parameters ($1, $2), not pasted into the string, which is how an ORM protects you from SQL injection by default. The code reads almost like the SQL, and that is a deliberate choice in this library.
What the compiler catches
I wrote three deliberately wrong lines and ran TypeScript 7.0.2 over them:
await db.select().from(tasks).where(eq(tasks.status, "finished")); // not a legal status
cols[0].status; // column was not selected
await db.insert(tasks).values({ projectId: 1 }); // title is required
All three failed to compile. Be warned that the messages are not friendly. The first one reads Argument of type 'PgColumn<...>' is not assignable to parameter of type 'never', a few hundred characters long. The second is clear: Property 'status' does not exist on type '{ id: number; title: string; }'. The third complains about an object literal without naming title clearly. Read the line number first and the message second. The TypeScript roadmap’s reading and debugging type errors lesson helps with this style of error.
The second error shows something useful. When you select { id, title }, the result type is { id: number; title: string }, so the compiler stops you from using status on it. Selecting only what a screen needs gives you a smaller type and a smaller payload, and the next lesson builds on that.
What the compiler cannot catch
Be clear about the limits so you don’t over-trust the types:
- Speed. A perfectly typed query can scan a million rows. Types say nothing about indexes or plans.
- Drift. The TypeScript table definition can disagree with the real database if someone changes one and not the other. The types describe the definition, not the database.
- Meaning.
eq(tasks.id, 5)is a valid query for a task the current user may not touch. Authorization is the API’s job. - Data that was already wrong. If a row from before a constraint existed holds a bad status, the type will say it can’t happen.
Keep it in a feature module
Don’t call the ORM directly inside route handlers. Put data access in a small module, tasks.repo.ts or tasks/queries.ts, that exports functions like setStatus, listForProject, create. Then:
- The handler is about HTTP: parse, call, map to a status code.
- The function has a typed input and a typed output, so it can be tested by calling it with a test database, with no server.
- When you change a query, you change one file.
This is not heavy architecture. It’s one folder.
What the video covers
Neon’s “Learn Drizzle ORM in 13 mins (crash course)” is about fourteen minutes and was published in February 2024. Its description says it covers Drizzle’s components, how to define a schema, and both its SQL-like query API and its relational API, with the code on GitHub. Neon is a Postgres hosting company, so expect Neon-flavoured setup. Drizzle has moved fast, and I could not read a transcript, so some syntax in the video may differ from what is current. Check the examples against the Drizzle documentation. Fireship’s three-minute “Drizzle ORM in 100 Seconds” is linked as a quick overview.
Where this fits
You can read and write rows with types. A real screen rarely wants one table’s rows, though. It wants a board with names, counts and comments, and fetching that badly is how apps get slow. Next: shaping queries for screens.
Check yourself
What does the TypeScript table definition give you that raw SQL strings do not?
Row types and checked queries. A misspelled column, a status that does not exist, or a missing required field becomes a compile error.
Where does the type of a status column come from if the database column is plain text?
From the TypeScript definition, which declares the allowed values. The database's CHECK constraint enforces the same rule at runtime.
Can the compiler tell you a query is slow?
No. It checks shapes and types only. Slowness needs the query plan, an index, and real data volumes.
Why wrap queries in a function like setStatus instead of calling the ORM from the handler?
The handler stays about HTTP, the function has a typed input and output, and you can test and reuse it without a web server.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.