Write Drizzle queries
Choose native Drizzle query operators and preserve database semantics.
Prefer native operators
Before writing a custom SQL predicate or helper, check the Drizzle filter operators and query builders supported by the version pinned in packages/db/package.json. Use eq, exists, inArray, arrayContains, and arrayOverlaps when they express the operation. Reviewers should flag handwritten equivalents and suggest the specific native API.
For example, building permissions @> ARRAY[...] by hand duplicates arrayContains. Use the operator directly:
import { arrayContains } from "drizzle-orm";
// Guard the empty list before constructing this predicate.
arrayContains(accessGrant.permissions, [...permissions]);
arrayContains requires all requested values; arrayOverlaps requires at least one. The pinned version throws if either receives an empty JavaScript array. Decide the empty case explicitly: the application’s findMatching returns no grants for an empty request before calling the database lookup. Do not silently omit a filter when its input is empty.
Use eq for equality, including comparisons against expressions. Keep sql for the function call; Drizzle’s equality operator supplies the comparison.
eq(sql`lower(trim(${user.email}))`, organizationInvitation.invited_email);
Preserve database semantics
Use parameterized sql expressions for PostgreSQL operations Drizzle does not provide directly, such as string_to_array, CASE, database time, and casts in insert-select projections. Prefer the builder for the surrounding statement. Verify null and empty-list behavior, types, and generated queries against the pinned driver.
Keep permission decisions in application operations and HTTP error mappings in routes. Database functions read the requested scopes, perform mutations, and return domain errors; they do not check the caller’s roles or eligibility. The application determines invitation list scopes from current memberships and verified email before calling the database lookup.
Preserve atomic data transitions: invitation acceptance and relationship creation use one common table expression, so a relationship conflict rolls back acceptance. Conditional writes still require a pending, unexpired invitation. Do not split these writes merely to simplify the query.