We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Drizzle Queries

We've set up Drizzle and created our schema. Now we need to write some queries to interact with the database.

Assignment

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.