Querying
Create clients and run RLS-scoped, admin, and service-role queries
Clients
@zeno-lib/db exports five client factories. Each takes an optional Drizzle
config ({ relations?, logger?, casing? }) plus an optional connectionString
and requirePooler. The two that run as a user's token, createAuthClient and
createSupabaseClient, also take sessionRevocation (see
Revoked sessions). Without connectionString, it reads
SUPABASE_DATABASE_URL from the environment. For local and deployed
connection strings, see
Environment.
| Factory | Runs as | Use for |
|---|---|---|
createAuthClient(supabase, config?) | the signed-in user (anon/authenticated) | per-request, RLS-enforced reads and writes |
createAnonClient(config?) | anon | unauthenticated, RLS-enforced reads |
createServiceClient(config?) | service_role (bypasses RLS) | trusted server work that needs service_role |
createSupabaseClient(accessToken, config?) | the token's role (anon/authenticated) | RLS work when you already hold the verified, decoded claims |
createAdminClient(config?) | the postgres connection role (bypasses RLS) | seeds, webhooks, cron, background jobs |
The RLS clients (createAuthClient, createSupabaseClient, createAnonClient)
clamp a user token's role to anon or authenticated. A forged or unexpected
role claim falls back to anon, and service_role is reachable only through the
explicit createServiceClient, never from a JWT.
For deployed Supabase projects, prefer the
Supabase connection pooler
for serverless or autoscaling environments. The package sets prepare: false on
the underlying postgres-js pools so Supabase's transaction-mode pooler works.
The package caches pools per (kind, connectionString), and close() is
reference-counted, so a handle releases only its share of the shared pool.
Query with RLS
Create the request-scoped Supabase client first, then bind it to
createAuthClient(...). You query the returned client directly, and each query
runs as the signed-in Supabase user, so auth.uid() resolves to that user
and RLS policies apply:
import { createAuthClient } from "@zeno-lib/db"
import { createClient } from "@zeno-lib/supabase/server"
import * as schema from "{project}-db"
const supabase = await createClient()
const db = createAuthClient(supabase)
const myPosts = await db.select().from(schema.posts)Awaiting a query calls supabase.auth.getClaims(), opens a transaction,
installs the verified JWT claims into transaction-local Postgres settings (so
auth.uid() and auth.jwt() work inside RLS policies), and runs the query as
the claims' role. Each awaited statement is its own transaction unless it runs
inside db.transaction (below), and the client re-resolves claims for every
transaction, so a single client sees a sign-out at once, and a ban or a
deletion with sessionRevocation.
createAuthClient(...) does not take a schema. The client resolves types from
the tables you reference in the query itself. Pass a relations object only when
you want the relational query API (see below).
Relational queries
The relational query API works the
same way once you pass a relations object (from Drizzle's defineRelations) to
the factory. Build the relations object once at module scope, not per request:
import { createAuthClient } from "@zeno-lib/db"
import { createClient } from "@zeno-lib/supabase/server"
import { defineRelations } from "drizzle-orm"
import * as schema from "{project}-db"
const relations = defineRelations(schema)
const supabase = await createClient()
const db = createAuthClient(supabase, { relations })
const myPosts = await db.query.posts.findMany()Multiple statements in one transaction
When you need several statements to share one atomic RLS transaction (for
example a read followed by a dependent write), use db.transaction(...) and run
each statement on its tx argument, which runs under the same claims and role:
const created = await db.transaction(async (tx) => {
const [post] = await tx
.insert(schema.posts)
.values({ title: "Hello" })
.returning()
await tx.insert(schema.auditLog).values({ postId: post.id })
return post
})Parallel reads work the same way. Pass tx to each query function, and they
share one begin, one claims setup and one commit instead of opening a
transaction each:
const [post, comments] = await db.transaction((tx) =>
Promise.all([selectPost(tx, id), selectComments(tx, id)])
)Reads that cannot take tx
Some reads sit behind code that has no way to receive tx, such as a query
factory that calls a server action or a defineQuery, which builds its own
client with getRequestDb() (see below). For those, a statement on db itself, awaited
while the callback runs, joins the transaction too:
const db = await getRequestDb()
await db.transaction(() =>
// The server actions behind these queries reach the transaction through
// getRequestDb(), not through tx.
Promise.all([
queryClient.prefetchQuery(postQueryOptions(id)),
queryClient.prefetchQuery(commentsQueryOptions(id)),
])
)This goes through the async context, so it covers only the same client, and
only while the callback runs: another client keeps its own transactions, and a
statement started after the callback ends opens its own. Pass tx whenever you
can, because then the code shows which statements share the transaction.
Either way, the statements run one after another on one connection. A
db.transaction inside another one is a savepoint of it, so never run two of
those in parallel. Postgres aborts a transaction at its first failed statement,
so the statements after it fail too, and db.transaction rejects with that
first error even when the callback caught it, as prefetchQuery does.
Use db.transaction only when a single statement is not enough; one direct
statement is the common case.
Request-scoped client for Next.js
@zeno-lib/db/next wraps createSupabaseClient for the App Router. Create one
module per app (not a "use server" file) that binds it to your Supabase server
client and relations:
import { createRequestDb } from "@zeno-lib/db/next"
import { createClient } from "@zeno-lib/supabase/next-server"
import { relations } from "./relations"
export const {
defineAction,
defineFormAction,
defineQuery,
getRequestContext,
getRequestDb,
} = createRequestDb({ relations, supabase: () => createClient() })
export { SessionRevokedError, UnauthenticatedError } from "@zeno-lib/db/next"getRequestContext() verifies the cookie session with auth.getClaims() once
per server render, because React's cache wraps it. It returns
{ claims, db, via }, where db runs as the caller with the whole verified
claims object installed, and via is null (see
Marking who acts for the user). It never falls back to anon. Without a verified
sub, it throws UnauthenticatedError. getRequestDb() returns just the db.
defineAction(schema, handler) turns each server action into one line. The
returned async function parses its argument with schema.parse, then calls
handler(db, input, context):
"use server"
import { defineAction } from "{project}-db/server-db"
import { z } from "zod"
import { deletePost, insertPost } from "./queries"
export const deletePostAction = defineAction(z.number().int(), deletePost)
// Stamp authorship from the verified claims, never from an argument.
export const createPostAction = defineAction(
z.object({ title: z.string().min(1) }),
(db, input, { claims }) => insertPost(db, { ...input, userId: claims.sub })
)An action never resolves to undefined. When the handler does (a findFirst
that matches no row, for example), the action resolves to null. TanStack
Query rejects a query whose function resolves to undefined, so a query
function can return a read action's result as it is, typed T | null.
When being signed out is a valid answer (in a permission check, say), catch the named error instead. A revoked session throws it at the first query, so the catch covers the query too:
const posts = await getRequestDb()
.then((db) => db.select().from(schema.posts))
.catch((error: unknown) => {
if (error instanceof UnauthenticatedError) return null
throw error
})Revoked sessions
With asymmetric signing keys, getClaims() verifies a token without asking
Auth, so a token issued before a ban or a deletion keeps working until it
expires (jwt_expiry, one hour by default). Pass sessionRevocation to check
each transaction against the database:
import { authUserRevocation } from "@zeno-lib/db/auth"
createRequestDb({
relations,
sessionRevocation: authUserRevocation,
supabase: () => createClient(),
})authUserRevocation refuses what Supabase Auth refuses: a banned user, with the
code user_banned, and a deleted one, with user_not_found. A refused
transaction throws SessionRevokedError before any of its statements run. It
is an UnauthenticatedError with the same name, so code that catches
signed-out callers catches it too, and it carries the code as code. The check
runs with each transaction, so a handler that sends an email or uploads a file
should query first. To sign the user out, call
supabase.auth.signOut({ scope: "local" }) before you redirect to the sign-in
page, or a page that sends signed-in users away loops.
getRequestContext() still resolves for a revoked session. To let it run a
query anyway, use a client without the option, such as
createSupabaseClient(claims), which still applies RLS.
A check of your own returns a scalar SQL expression that yields a text code, or
NULL while the session still counts. It runs once the claims are set, so
auth.uid() works, but before the role switch, as the login role, which
bypasses RLS: keep it a read-only lookup, and pass values as bound parameters.
Combine checks with coalesce:
import { authUserRevocation } from "@zeno-lib/db/auth"
import { sql } from "drizzle-orm"
import { profiles } from "./schema"
// `account_closed` once the user's profile is closed, else NULL.
const accountClosed = sql<string | null>`(
select 'account_closed'
from ${profiles}
where ${profiles.id} = auth.uid() and ${profiles.closedAt} is not null
)`
createRequestDb({
relations,
// The first code wins: Supabase Auth's, then the app's own.
sessionRevocation: (context) =>
sql<string | null>`coalesce(${authUserRevocation(context)}, ${accountClosed})`,
supabase: () => createClient(),
})The check guards the Drizzle clients only: the same token still reaches
PostgREST, Storage and Realtime until it expires. Each transaction plans it
afresh, so it locks the tables it reads and their indexes until commit, about
a dozen relations for auth.users. Postgres 17 and older keep only 16 locks
per transaction on their fast path, so the check leaves about 4 for the rest of
the transaction. Locks past 16 go through a shared lock table, which can slow
transactions down under heavy load. Postgres 18 sizes the fast path from
max_locks_per_transaction: 64 locks by default.
Returning validation errors to a form
In production, Next.js replaces a thrown server-action error's message with a
generic one, so the ZodError that defineAction throws on bad input reaches
the browser without its issues. For an action a form submits, use
defineFormAction, which createRequestDb returns next to defineAction. It
takes the same arguments and runs in the same order (validate, then resolve
the session, then call the handler), but it resolves to an ActionResult
instead of throwing on invalid input:
type ActionResult<T> =
| { ok: true; data: T }
| {
ok: false
error: {
fieldErrors: Record<string, string[]> // "address.city", "owners[0].share"
formErrors: string[] // issues with no path
}
}Field keys are the names TanStack Form registers fields under: object keys
joined with ., array indices in brackets. Schema issues come back this way,
and so does a FieldValidationError thrown from the handler, for a check only
the database can make:
"use server"
import { isConstraintViolation } from "@zeno-lib/db/errors"
import { FieldValidationError } from "@zeno-lib/db/next"
import { defineFormAction } from "{project}-db/server-db"
import { z } from "zod"
import { insertTeam } from "./queries"
export const createTeamAction = defineFormAction(
z.object({ name: z.string().min(2), slug: z.string().min(3) }),
async (db, input, { claims }) => {
try {
return await insertTeam(db, { ...input, userId: claims.sub })
} catch (error) {
if (isConstraintViolation(error, ["teams_slug_key"])) {
throw new FieldValidationError({ slug: "That slug is taken" })
}
throw error
}
}
)Everything else still throws: UnauthenticatedError, a database error, a bug.
A FieldValidationError thrown inside db.transaction(...) rolls the
transaction back before defineFormAction converts it. On the client,
submitAction from @zeno-lib/forms writes the result onto the form; see
Server actions.
defineAction still throws. Use it for an action whose errors no form renders
(a delete button, a toggle).
Reads through a query route
The browser runs server actions one at a time: Next.js queues each call until the one before it settles. That suits a write, but a screen whose cards each read through an action waits for every read in turn, and each one pays the round trip to the server and on to the database. Serve reads from a route instead, where each call is its own request and they run in parallel.
defineQuery, which createRequestDb returns next to defineAction, takes
the same arguments and behaves the same way: parse, verify the session, call
the handler, resolve undefined to null. The difference is where it lives:
export it from a module without "use server", and gather those exports
into the map a query route serves:
import "server-only"
import { defineQuery } from "{project}-db/server-db"
import { z } from "zod"
import { selectPosts } from "./db-queries"
export const selectPostsQuery = defineQuery(
z.object({ authorId: z.string() }),
selectPosts
)import { createQueryRoute } from "@zeno-lib/query/query-route"
import * as queries from "@/app/posts/queries"
export const { POST } = createQueryRoute(queries)The browser side, createQueryCaller, and the server prefetch are on the
Queries
page. Every entry in the map is a public endpoint, exactly like a server action:
defineQuery checks the session and RLS authorizes the rows, and the schema
bounds what a caller can ask for. import "server-only" makes a client import
of the module fail the build instead of bundling your database client.
Reads and actions an agent can call
defineQuery, defineAction and defineFormAction also take one object, which
adds the name and description a tool list shows a model. The export is the
same function, with the definition on its definition key, so one definition
serves the UI and an agent:
export const selectPostsQuery = defineQuery({
name: "list_posts",
description: "List the caller's posts, newest first. At most 20.",
schema: z.object({ authorId: z.string() }),
run: selectPosts,
})"use server"
export const renamePostAction = defineAction({
name: "rename_post",
description: "Rename one of the caller's posts.",
schema: z.object({ id: z.number().int(), title: z.string().min(1) }),
describeChange: async (db, { id, title }) => {
const post = await db.query.posts.findFirst({ where: { id } })
return {
entity: `Post ${id}`,
changes: [{ field: "title", from: post?.title ?? null, to: title }],
}
},
run: renamePost,
})- The name is a tool name: 1 to 64 letters, digits,
_or-. Any other name throws when the module loads. definition.readOnlyistruefor a query andfalsefor both write builders. A write always needs the user's approval, so there is no switch to turn it off. A query's object form runs in a read-only transaction, export andinvokealike, so arunthat writes fails with Postgres's error instead of slipping past the approval a host skips for it.describeChange(db, input, context)is optional on writes, but an agent tool list requires it: a write given one has it in its definition's type. It reads, under the caller's RLS, what the write would change, so an approval step can show the record and each field old → new instead of a tool name. Call it throughdefinition.describe(input, context), which parses the input asinvokewould, handsdescribeChangea read-onlydb, and resolves tonullfor a write without one. A form action'sdescribethrows aFieldValidationErrorfor input its schema refuses. Wrap several reads indb.transactionfor one snapshot.definition.invoke(input, context)runs the definition for a context you pass in: parse, thenrun, thenundefined→null(anActionResultfor a form action). Use it where the request has no cookie session, such as a bearer token below. The export itself still resolves the cookie session.paged: true(orpaged: { defaultLimit, maxLimit, maxOffset }, 20, 50 and 10,000 by default) makes a query a paged read. It addslimitandoffsettoschema, which must be an object schema without them, checks and defaults both beforerun(nulltakes the default, as a model often sends it), and adds them to the JSON Schema a tool list shows. The JSON Schema is built only when a tool list asks for it, so a schema it can't express (aDate) still works on a screen.runreceives them with the rest of the input and must resolve to aPage, such asfindPage's, and the description gains a sentence onitems,total,hasMoreand how to ask for the next page.definition.pagedholds the bounds.- The positional forms keep working, and carry no definition.
The definition sits on its own key because a function's name is read-only. It
survives "use server" for the server code that imports the export.
AI & agents turns a list of these into AI SDK tools and an MCP endpoint.
Callers with a bearer token
A client that is not the browser, such as an MCP client, sends an OAuth access
token in Authorization: Bearer instead of cookies. Pass bearer to
createRequestDb and use getBearerContext(request) in that route:
import { createClient as createTokenClient } from "@supabase/supabase-js"
export const { getBearerContext, withVia /* , … */ } = createRequestDb({
relations,
supabase: () => createClient(),
bearer: {
// A client that holds no session: it only verifies the token it is given.
supabase: () =>
createTokenClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{ auth: { autoRefreshToken: false, persistSession: false } }
),
// Your registered OAuth clients: client_id → the label writes carry.
client: async (clientId) => (await registeredClients()).get(clientId),
confirmSession: true,
},
})getBearerContext verifies the token with auth.getClaims(token) and returns
{ claims, db, via, clientId, token }. It throws UnauthenticatedError for a
missing or invalid token, a token with no sub or a role other than
authenticated, a token issued to no OAuth client (a browser session's own
token), and a client bearer.client gives no label for (null, undefined or
''). Auth being unreachable or rate-limiting (429) rethrows as it is, so it
is not mistaken for a bad token. It never falls back to anon, and it is not
memoised: call it once per request.
- Check
client_id, notaud. Supabase Auth's OAuth server accepts aresourceparameter but keepsaudatauthenticated. - A client's token works only here.
getRequestContextrefuses a session whose token carriesclient_id. The token carries the user's full rights, and with its refresh token it makes a valid cookie session, so without this check whoever holds it could run every server action as the user. confirmSessionalso asks Auth for the session (auth.getUser(token)) on every call. Revoking a grant ends its refresh token at once, but its last access token still passesgetClaimsuntil it expires. Without the option, allow for up to the token's lifetime (one hour by default). On a project still signing with the legacy HS256 secret,getClaimsalready asks Auth, so the option costs a second round trip.
Marking who acts for the user
Every RLS transaction sets app.via in the same statement as the claims. It
names who acts for the user: the label bearer.client returned for a bearer
caller, or the one you pass to withVia for a cookie caller:
const context = withVia(await getRequestContext(), "AI assistant")
// Every transaction of context.db now carries app.via = 'AI assistant'.A trigger reads it to attribute a write. It is '' when nothing set it, so read
it with nullif:
nullif(current_setting('app.via', true), '')Set it only through the client. A set_config('app.via', …, true) sent as its
own statement is its own transaction, and the value is gone before the next
statement runs. app.via is a label, not proof: a role that can run SQL can set
it, so for a bearer caller also record the signed client_id
(auth.jwt() ->> 'client_id').
Labelling where a write comes from
When several apps or jobs share one database, give each its own source. Every
transaction of the client then sets app.source in the same statement as the
role, so an audit trigger can tell a write from the web app apart from one from
a worker:
export const { getBearerContext, getRequestDb /* , … */ } = createRequestDb({
relations,
source: "web",
supabase: () => createClient(),
bearer: {
// A bearer caller's own label. Without it, it takes `source`.
source: "api",
supabase: () => createTokenClient(/* … */),
client: async (clientId) => (await registeredClients()).get(clientId),
},
})createServiceClient, createAnonClient, createSupabaseClient and
createAuthClient take source in their config too. createAdminClient opens
no transaction of its own, so it sets nothing. Read it with nullif, since it is
'' when nothing set it:
nullif(current_setting('app.source', true), '')Like app.via, it is a label: set it only through the client, and treat it as
proof of nothing a role that can run SQL could not also write.
Other RLS clients
When you already hold the verified, decoded claims (for example from a prior
supabase.auth.getClaims() call), skip the getClaims() call each transaction
makes with
createSupabaseClient(accessToken, config?). Its config (and
createAuthClient's) also takes via, the
app.via label, source, the
app.source label, and readOnly, which runs
every transaction read-only. It accepts a decoded
SupabaseToken (the role and sub claims), not a raw JWT string, and does not
re-verify it:
import { createSupabaseClient } from "@zeno-lib/db"
import * as schema from "{project}-db"
const db = createSupabaseClient({ role: "authenticated", sub: userId })
const myPosts = await db.select().from(schema.posts)For unauthenticated, RLS-enforced reads, use createAnonClient(), which runs
every query as anon:
import { createAnonClient } from "@zeno-lib/db"
const db = createAnonClient()Prefer createAuthClient when you have a Supabase client. It resolves and
verifies claims through auth.getClaims() before every transaction, so it
sees a sign-out at once, and a ban or a deletion with sessionRevocation.
Use admin and service queries carefully
For trusted server work that should bypass user RLS, use createAdminClient(...).
It needs no Supabase client (it connects via SUPABASE_DATABASE_URL), and you
query it directly:
import { createAdminClient } from "@zeno-lib/db"
import * as schema from "./schema"
const db = createAdminClient()
await db.select().from(schema.posts)createAdminClient(...) does not switch roles. It runs as the role the client
connects as (the postgres role by default), which is not subject to RLS. That
connection role, not service_role, is what makes admin queries bypass policies.
createServiceClient(...) instead runs every statement as service_role, which
bypasses RLS through Supabase's BYPASSRLS grant. It is the only path to
service_role; use it when trusted work needs that role rather than the
postgres connection role:
import { createServiceClient } from "@zeno-lib/db"
import * as schema from "./schema"
const db = createServiceClient()
await db.select().from(schema.posts)Use either for seed scripts, webhooks, cron jobs, admin tools, and background jobs. Never use them for user-scoped reads or writes.
Query helpers
@zeno-lib/db/query covers the PostgREST conveniences Drizzle has no
equivalent for.
one(rows) is the equivalent of .single(). It returns the row and throws
unless there is exactly one. maybeOne(rows) is the equivalent of
.maybeSingle(). It returns the row, or undefined when there is none, and
throws when there are several.
import { maybeOne, one } from "@zeno-lib/db/query"
const post = one(await db.insert(posts).values(input).returning())
const draft = maybeOne(await db.select().from(posts).where(eq(posts.id, id)))excludedSet(table, values, { target? }) builds the set that makes
onConflictDoUpdate behave like .upsert(). It writes every column the caller
supplied back from excluded, under its database name.
import { definedValues, excludedSet } from "@zeno-lib/db/query"
const values = definedValues(input)
await db
.insert(contacts)
.values(values)
.onConflictDoUpdate({ target: contacts.id, set: excludedSet(contacts, values) })It skips a key holding undefined, because Drizzle leaves it out of the insert
and excluded.<col> would be the column default, overwriting the stored value.
It never writes back the conflict target ("id" unless target names other
column keys). When the caller supplied nothing else, the set falls back to
id = excluded.id, because Drizzle refuses an empty set while building the
statement. A table without that column (a junction keyed by its foreign keys)
gets an empty set; use onConflictDoNothing there.
Paging a list
findPage(builder, { limit, offset }, { where, orderBy, rows }) reads one page
of a relational query and says how many rows match in all. It resolves to a
Page: { items, total, hasMore }.
import { findPage, mapPage } from "@zeno-lib/db/query"
const page = await findPage(
db.query.posts,
{ limit: 20, offset: 40 },
{
where: { status: "draft" },
orderBy: { updatedAt: "desc", id: "desc" },
rows: (ids) =>
db.query.posts.findMany({
columns: { id: true, title: true },
where: { id: { in: ids } },
with: { author: { columns: { name: true } } },
}),
}
)
const titles = mapPage(page, ({ author, title }) => `${title} (${author.name})`)- It takes two statements. Once a query reads relations (
with), Drizzle moveslimitandoffsetinto a subquery, wherecount(*) over ()would count only the page. The first statement reads the page's ids and the total;rowsreads those rows with any columns and relations. rowscan read in any order: the items come back inorderByorder, so the order is written once. EndorderByon a unique column, or rows that tie can show on two pages, or on none.- The table needs an
idcolumn;rowsreceives the ids typed as that column. totalcounts every match on any page. A page past the last row has no row to carry the count, so it takes a third statement.mapPage(page, toItem)maps the items and keepstotalandhasMore.
Syncing a parent's rows
A form that edits a parent with its child rows, such as an order and its lines,
sends back the whole list. syncRows(db, table, { parent, rows }) makes that
list the parent's rows: it removes the stored rows that left the list, updates
the ones still in it and inserts the new ones. It resolves to the saved rows in
input order, so the form can take up the new ids.
import { one, syncRows } from "@zeno-lib/db/query"
export const updateOrder = (db: Db, { id, lines, ...values }: OrderInput) =>
db.transaction(async (tx) => {
const order = one(
await tx.update(orders).set(values).where(eq(orders.id, id)).returning()
)
const saved = await syncRows(tx, orderLines, {
parent: { orderId: id },
rows: lines,
})
return { ...order, lines: saved }
})parent holds the columns that make a row the parent's. The sync reads, updates
and removes only the rows that match all of them, and writes them onto every
row, so a row leaves them out and can't land under another parent. A null
value matches null, but at least one value must not be null: a parent that
isn't saved yet would otherwise reach every orphaned row in the table.
By default, rows are told apart by their id; pass id to name another column.
A row without an id is new. A row whose id the parent doesn't hold, because it
belongs to another parent or was deleted since the form loaded it, is inserted
as a new row, so a sync never writes another parent's row. When the id column
has no default (primaryId("assigned")), the caller assigns ids: a new row
keeps its id, and one another row already holds fails on the primary key.
The form and the sync agree on what a row is through
ownedRows,
which syncRows takes in place of the table. Its parent must then name
exactly the descriptor's parent columns:
await syncRows(tx, orderLinesOfOrder, { parent: { orderId: id }, rows: lines })A junction table, or any table whose rows are told apart by what they point at,
takes key, the natural key columns within the parent. Each row carries them,
since a missing one would be stored as the column default and never match
again, and a null key part matches a stored null:
await syncRows(tx, postsTags, {
key: ["tagId"],
parent: { postId },
rows: tagIds.map((tagId) => ({ tagId })),
})- The rows that left the list are removed first, then the kept rows are
updated, then the new rows are inserted. A row the user removes and adds back
doesn't hit a unique index, and neither does a new row that takes a value a
kept row gives up. A kept row that points at a new row through a foreign key
needs that key to be
deferrable initially deferred, since the new row doesn't exist yet when the kept row is updated. - An update sets only the columns a row carries and changes, and a property
holding
undefinedkeeps its stored value. A kept row with nothing changed is returned as it is, unwritten, so itsupdated_atstays put. - An empty list removes every row of the parent.
- Two rows with the same key reject before anything is written. Next redacts that error in production, so reject duplicates in the form's schema too, where the user sees them on the field.
- It runs in
db.transaction, which is a savepoint inside atx. A failure undoes every write the sync made, and nothing else.
The rows that left the list are deleted. To soft-delete or unlink them instead,
or to delete only the ones nothing else references, pass remove. It gets the
transaction and the removed rows, and runs before any update or insert:
await syncRows(tx, orderLines, {
parent: { archivedAt: null, orderId },
remove: (tx, removed) =>
tx
.update(orderLines)
.set({ archivedAt: new Date() })
.where(inArray(orderLines.id, removed.map(({ id }) => id))),
rows: lines,
})With archivedAt: null in parent, archived rows stay out of the sync, and new
rows are written unarchived. An archived row still holds its key, so make the
unique index partial, or a removed key can't come back:
uniqueIndex()
.on(table.orderId, table.product)
.where(sql`${table.archivedAt} is null`)The sync reads the parent's rows before it writes, so two syncs of one parent
at the same time can both insert the same new row. A unique index on the parent
and key columns makes the second one fail instead. Add .nullsNotDistinct()
when a key part is nullable, because Postgres otherwise treats two NULLs as
different and lets both rows in. Updating the parent row first in the same
transaction, as updateOrder does, makes the second sync wait for the first to
commit.
A parent can hold thousands of rows, such as the grants on a shared folder. The
removals and the inserts go many rows to a statement, split to stay under
Postgres's limit of 65,535 bind parameters, so saving thousands of new grants
or revoking thousands takes a few statements. Each kept row that changed is
still one update. To change thousands of kept rows at once, use insert with
onConflictDoUpdate.
A trigger can rewrite the rows the sync keeps. Say a team's members hold shares
that must sum to 1, and a delete trigger hands a leaving member's share to the
members left. The sync compares the listed rows with the parent's rows as they
stand after the removal, so a member whose listed share is the one she started
with is written back too, and the save ends with the listed shares. That costs
one more read of the parent's rows, and only when the sync removed something.
remove gets the same treatment: a change it makes to the rows left counts. A
kept row that the removal deleted, through a cascade or a trigger, rejects the
sync rather than coming back as a new row.
A trigger that an update or an insert fires runs after that comparison, so what it writes to the other rows stays, and the rows the sync returns don't show it: each is what its own statement returned. Read the parent's rows again after the sync when such a trigger exists.
Between its statements, the sync leaves the rows in states the save doesn't end in, such as shares that sum to 0.8 once a member is removed. Check a rule across rows in a deferred constraint trigger, which runs at commit:
create constraint trigger team_members_shares_sum
after insert or update or delete on team_members
deferrable initially deferred
for each row execute function check_team_members_shares();Errors
Drizzle wraps every driver error in a DrizzleQueryError whose own code is
undefined, so error.code === "23505" is always false. @zeno-lib/db/errors
extracts the postgres.js error:
import { isConstraintViolation, SqlState, toPostgresError } from "@zeno-lib/db/errors"
try {
await db.insert(contacts).values(row)
} catch (error) {
if (isConstraintViolation(error, ["contacts_email_key"], { code: SqlState.uniqueViolation })) {
return { error: "That email is already a contact" }
}
throw error
}toPostgresError(error) returns the PostgresError (with code,
constraint_name, detail, …) or undefined. It only returns errors the
server sent: one postgres.js raises itself, such as a closed connection or a
query cancelled before it was sent (57014), gives undefined. A
PostgresError you build in a test needs a SQLSTATE code and a
severity_local, like the real one. isConstraintViolation(error, constraints?, { code? }) returns it only for an integrity-constraint violation
(any class 23 code unless code narrows it) and, when you pass
constraints, only for one of those. SqlState names the codes an application
usually branches on.
Testing against the database
Suites that share one local database, and run in parallel with each other and
with your end-to-end tests, must not commit what they write: a committed row
changes what every other suite counts. @zeno-lib/db/testing has three helpers
for those tests. They throw instead of calling expect, so any test runner can
use them.
import { SqlState } from "@zeno-lib/db/errors"
import { expectPostgresError, expectRlsDenied, rollBackAfter } from "@zeno-lib/db/testing"
it("rejects a second contact with the same email", () =>
rollBackAfter(db, async (tx) => {
await tx.insert(contacts).values(ada)
const error = await expectPostgresError(
tx.insert(contacts).values(ada),
SqlState.uniqueViolation
)
expect(error.constraint_name).toBe("contacts_email_key")
}))rollBackAfter(db, run)runsrunin a transaction that always rolls back, and resolves to whatrunreturned. Nothing it writes is visible outside the transaction, and nothing needs cleaning up, whatever the rows cascade into. Only statements sent throughtxare in it: a write through another client, such as a module-leveladmin, commits.rungets the same transaction typedb.transactionhands you, relations included, and an error it throws is rethrown. On atx, it runs in a savepoint.expectPostgresError(query, code)resolves to thePostgresErrorwhen the query fails with that SQLSTATE, so you can check itsconstraint_nameor message. It rejects when the query succeeds, which a baretry/catchmisses, and when it fails with another code. Pass the query, or a function that starts it.expectRlsDenied(query)is the same check forinsufficient_privilege(42501): a write a row-level security policy or a missing grant refused. Aselectthat RLS filters doesn't fail, it returns fewer rows, so assert on those instead.
A failed statement aborts the transaction it ran in, and every later statement
in it fails too. Make the failing query the last statement in rollBackAfter,
or run it in a savepoint with tx.transaction(...).
Pitfalls
- Do not import
@zeno-lib/dbruntime clients from Client Components or browser code. - Do not use
createAdminClient(...)orcreateServiceClient(...)for user-scoped reads and writes; they bypass RLS. UsecreateAuthClient(...),createSupabaseClient(...), orcreateAnonClient(...)for RLS-enforced work. - Do not pass a raw access token string to
createSupabaseClient(...); it expects a verified, decodedSupabaseTokenand does not re-verify it. PrefercreateAuthClient(...), which verifies claims itself. - Do not feed a user-supplied token to
createServiceClient(...). It clamps nothing and grantsservice_role; it is a trusted backend decision. - Do not put
"use server"in the module that callscreateRequestDb, and do not exportgetRequestDbfrom a"use server"file: every export there is a public endpoint. - Do not use
getRequestContext()in a route a bearer-token client calls. It reads the cookie session, which that client never sends: usegetBearerContext(request). - Do not build a fresh
relationsobject literal per request. Pass a stablerelationsobject, or a cached client built without relations may be reused.