

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: Storage
incomplete
2: Drizzle ORM
incomplete
3: Drizzle Queries
incomplete
4: Automatic Migrations
incomplete
5: Database Review
incomplete
6: Create User
incomplete
7: Create Chirp
incomplete
8: Collections and Singletons
incomplete
9: Get All Chirps
incomplete
10: Get Chirp
incomplete
Back
ctrl+,
Next
ctrl+.
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.
We need to configure a db object that will be used to run queries.
DB_URL="YOUR_CONNECTION_STRING_HERE"
Add it to your .gitignore file. It's incredibly insecure to commit secret keys to a Git repo.
I created an envOrThrow(key: string) helper function to assert that the environment variables are present on startup. It's better to crash early if something is missing.
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema.js";
import { config } from "../config.js";
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 "../index.js";
import { NewUser, users } from "../schema.js";
export async function createUser(user: NewUser) {
const [result] = await db
.insert(users)
.values(user)
.onConflictDoNothing()
.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.
Run and submit the CLI tests from the root of your project.