

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Postgres
incomplete
2: Drizzle ORM
incomplete
3: Drizzle Queries
incomplete
4: Reset
incomplete
5: List Users
incomplete
This lesson's interactive features are locked, please to keep using them
We've set up Drizzle and created our schema. Now we need to write some queries to interact with the database.
Until now, all our code has been blissfully synchronous. We're about to start interacting with a database which is best handled asynchronously. We could keep our function signatures the same, but callback hell is real and it's much nicer to use async/await.
Let's do a bit of refactoring.
CommandHandler type signature to return a Promise<void> instead of void.async keyword before all the commands and runCommandasync in front of main in index.tsawait the run command.main add process.exit(0) to ensure the program exits.With that done... let's get started.
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";
import { readConfig } from "../../config";
const config = readConfig();
const conn = postgres(config.dbUrl);
export const db = drizzle(conn, { schema });
We'll use this db object to run queries against the database.
import { db } from "..";
import { users } from "../schema";
export async function createUser(name: string) {
const [result] = await db.insert(users).values({ name: name }).returning();
return result;
}
Array destructuring is used to get the first item from the returned array. This is because drizzle returns an array of results, even if there is only one result.
The syntax is almost identical to SQL.
INSERT INTO <table> (<columns>) VALUES (<values>) RETURNING *;
Keep the Drizzle docs handy, you'll probably need to refer to them again later.
npm run start register lane
It should:
Test the register command by running it with a name:
npm run start register lane
Use psql to verify that the user was created:
psql postgressudo -u postgres psql\c gator
SELECT * FROM users;
Take a good look at the tests and run them before submitting. You may have to TRUNCATE your users between each submission, because the tests assume a clean database. We'll set up a way to do this via the CLI in the next lesson.
Submit the CLI tests after a final TRUNCATE.