Skip to main content

Utilities

Standalone helper functions exported from @repo/db.

getOr404

Awaits a promise and throws a SvelteKit 404 error if the result is null or undefined.

import { getOr404 } from '@repo/db'

const user = await getOr404(db.query.users.findFirst({ where: eq(users.id, id) }))

Signature:

function getOr404<T>(data: Promise<T | null | undefined>): Promise<T>

Throws error(404, { message: 'Not found' }) from @sveltejs/kit.

subtractTables

Extracts only PgTable instances from a schema object, filtering out relations and other exports.

import { subtractTables } from '@repo/db'
import * as schema from './schema'

const tables = subtractTables(schema)
// { users: PgTable, orders: PgTable, ... }

Signature:

function subtractTables(schema: Record<string, unknown>): Record<string, PgTable>

convertTablesToZod

Generates Zod schema source code (as a string) from Drizzle table definitions. Produces insert, select, and update schemas for each table.

import { convertTablesToZod, subtractTables } from '@repo/db'
import * as schema from './schema'

const tables = subtractTables(schema)
const zodSource = convertTablesToZod(tables)
// Returns a string like:
// import { z } from 'zod/v4'
// export const usersInsertSchema = z.object({ ... })
// export const usersSelectSchema = z.object({ ... })
// export const usersUpdateSchema = z.object({ ... })

Typically used in code generation scripts rather than at runtime.

Signature:

function convertTablesToZod(tables: Record<string, Table>): string

whereToObject

Converts a Drizzle SQL where clause into a plain key-value object. Supports equality and comparison operators (=, !=, >, <, >=, <=).

import { whereToObject } from '@repo/db'
import { eq, and } from 'drizzle-orm'

const where = and(eq(users.id, '123'), eq(users.orgId, 'org-1'))
const obj = whereToObject(where)
// { id: '123', orgId: 'org-1' }

Useful for extracting filter values from a composed where clause, e.g. for audit logging or cache key generation.

Signature:

function whereToObject(where?: SQL): Record<string, any>

Returns an empty object if where is undefined.