Database

Database client

Use database client to interact with the database.

The database client is an export of the Drizzle client. It is automatically typed by Drizzle based on the schema and is exposed as the db object from the database package (@turbostarter/db) in the monorepo.

This guide covers how to initialize the client and also basic operations, such as querying, creating, updating, and deleting records. To learn more about the Drizzle client, check out the official documentation.

Initializing the client

Pass the validated DATABASE_URL to the client to initialize it.

packages/db/src/client.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
 
import { env } from "../env";
 
const client = postgres(env.DATABASE_URL);
export const db = drizzle(client);

Now it's exported from the @turbostarter/db package and can be used across the codebase (server-side).

Querying data

To query data, you can use the db object and its methods:

query.ts
import { eq } from "@turbostarter/db";
import { db } from "@turbostarter/db/client";
import { customers } from "@turbostarter/db/schema";
 
export const getCustomerByUserId = async (userId: string) => {
  const [data] = await db
    .select()
    .from(customers)
    .where(eq(customers.userId, userId));
 
  return data ?? null;
};

Mutating data

You can use the exported utilities to mutate data. Insert, update or delete records in fast and fully type-safe way:

mutation.ts
import { eq } from "@turbostarter/db";
import { db } from "@turbostarter/db/client";
import { customers } from "@turbostarter/db/schema";
 
export const upsertCustomer = (data: InsertCustomer) => {
  return db.insert(customers).values(data).onConflictDoUpdate({
    target: customers.userId,
    set: data,
  });
};

Last updated on

On this page

Ship your startup everywhere. In minutes.Get TurboStarter