Read sets and $many
Run several reads as one round trip, a single GET to a stable function or one SQL transaction.
An app shell that shows an unread badge, a customer count and the latest
note makes three requests on every navigation. Even in parallel, each costs
a connection and a trip through PostgREST. db.$many runs them together:
ad-hoc specs as one parallel wave, and registered read sets as a single
request.
Ad-hoc reads
Pass an array of query specs. The result is a tuple, typed per entry:
const [customers, notes] = await db
.$many([
betterSupabase.spec.customers.list({ select: ["id", "name"], limit: 10 }),
betterSupabase.spec.notes.count(),
])
.orThrow();Over PostgREST the specs run in parallel, as one wave.
Over better-supabase/postgres they run on one
connection in one transaction, through Executor.batch. Plugins apply to
each spec as usual. The first error fails the whole call.
Registered read sets
A read set names its reads once, with typed placeholders for parameters and for the caller's id:
import { defineReadSet } from "better-supabase";
import { betterSupabase } from "./supabase/index.ts";
export const workspaceSummary = defineReadSet(
betterSupabase,
"workspace_summary",
{},
(s, _p, auth) => ({
customers: s.customers.count(),
mine: s.customers.count({ where: { createdBy: auth.uid } }),
latestNote: s.notes.list({
select: ["body", "createdAt"],
orderBy: { createdAt: "desc" },
limit: 1,
}),
}),
);List the module in the config and add the read-sets SQL module:
export default defineConfig({
gen: { readSets: ["src/lib/read-sets.ts"] },
blocks: ["read-sets"],
});better-supabase gen compiles each set into one function in the
read-sets module, then you create a migration with
supabase db schema declarative sync (supabase db diff on the legacy migra
engine):
create or replace function public.rs_workspace_summary(p jsonb)
returns jsonb
language sql stable security invoker set search_path = ''
as $rs$
select jsonb_build_object(
'customers', ...,
'mine', ... where t0."created_by" = (select auth.uid()) ...,
'latestNote', ...
)
$rs$;
grant execute on function public.rs_workspace_summary(jsonb) to authenticated;Then run it:
const summary = await db.$many(workspaceSummary, {}).orThrow();
// { customers: number; mine: number; latestNote: { body: string; createdAt: string }[] }| Executor | What runs |
|---|---|
| PostgREST | One GET to rpc/rs_<name>. The function is stable, so a read replica can serve it |
better-supabase/postgres | The same reads with the values bound, in one transaction. The function isn't needed |
| Anything else | The reads in parallel |
Rows come back exactly as db.$run(spec) would return them: same casing,
codecs and aggregates.
Parameters
p holds placeholders, not values. Use them where a value goes in where,
including in lists and string filters such as contains. The function
reads each one from its p jsonb argument and casts it to the declared type,
so nothing is built as dynamic SQL.
| Type | TypeScript value |
|---|---|
uuid, text, date, timestamp, timestamptz | string |
int2, int4, int8, float4, float8, numeric | number |
bool | boolean |
<type>[] | readonly array of the above |
schema.type, for example public.note_kind | string |
Name enums and domains with their schema: the function runs with an empty
search_path. An enum column expects its literal union, so cast the
placeholder (p.kind as 'call').
Every parameter is required. A missing one fails with invalid_request
before anything reaches the database. A spec taken from a read set still
holds placeholders, so db.$run(readSet.specs.x) fails too; run the set.
The caller's id
The third builder argument, auth, stands for the signed-in user.
auth.uid goes wherever a uuid value does, so the set needs no userId
parameter and a caller can't pass someone else's id. Inside a string filter
such as contains it is compared as text. It is a single value, so it can't
go in an in list; compare with it directly instead.
Over PostgREST the function calls (select auth.uid()), which reads the
sub claim of the request's JWT. Over better-supabase/postgres, and on
executors that run the reads in parallel, $many binds the sub claim of
the connection's claims instead, and fails with invalid_request when
there is none. Connect with the user's verified claims
(connect(client, { claims }); the server's db does this for you). For an
anon caller auth.uid() is null, so a comparison with it matches nothing.
Security
The function is security invoker, so RLS decides what each caller reads,
as for any other query. Execute is granted to authenticated only; pass
roles: ['anon', 'authenticated'] to open it up.
Read sets run without query plugins, on both executors: the function is
compiled once, and plugins such as memberships or softDelete add filters at
request time. Scope read sets with RLS, or with explicit parameters and
where filters. defineReadSet logs a warning when the definition has
query plugins and the set reads a table with a tenant or soft-delete flag.
Limits
- Each entry is one select:
list,get,count,aggregateor an offsetpage. - A set has between 1 and 50 entries.
- Names are snake*case, at most 60 characters. The function is
public.rs*<name>. genimports the module with Node, so relative imports need their.tsextension (allowImportingTsExtensionsintsconfig.json), and the module can't importserver-only.
Functions, block reads and records
A read set can also call stable SQL functions, so a page loads a board and
its counts in one request. s.$fn.<name>(args) calls any stable or
immutable function the schema metadata lists. Each installed block that
ships composed reads exposes them as s.blocks.<instance>.<read>(args), from
the reads constant in blocks.reads.ts, and s.record(type, id, { sections }) calls record_summary for one record:
import { reads } from "./supabase/blocks.reads.ts";
export const pipelineOverview = defineReadSet(
betterSupabase,
"pipeline_overview",
{ params: { pipelineId: "uuid" }, blocks: reads },
(s, p) => ({
customers: s.customers.count(),
board: s.blocks.deals.board({ pipelineId: p.pipelineId }),
}),
);A function call carries no table list, because the database cannot tell which
tables a function reads. Pass them as the second argument and bsb.tags and
bsb.cached({ readSet }) tag the cache entry with them, so a mutation of one
of those tables revalidates the payload:
s.$fn.board_payload(
{ pipelineId: p.pipelineId },
{ tables: ["deals", "stages"] },
);bsb.tags(spec) accepts the same call outside a read set, alone or in a list
next to table reads.
blocks.reads.ts imports no block, and defineReadSet takes any app, with or
without blocks. Build the set over the app without blocks (app) and the route
that runs it bundles only the block set of its own server (ADR 0645).
blocks.generated.ts re-exports reads and its types for existing imports.
The function runs inside the set's function as the caller, so RLS applies as
it does for the block's own client. A function can't sit in a nested
object argument, and a volatile one is refused. gen also writes the
result type of each block read (DealsBoardResult) and the block's client
has a method for it, so deals.board({ pipelineId }) works without a read
set.
The blocks that sit on most pages ship reads for a page's side data, so a detail page reads them in the same call as its own rows:
| Read | Function | Returns |
|---|---|---|
s.blocks.comments.list({ tenant, subjectType, subjectId }) | list_comments | a record's comments and replies |
s.blocks.comments.counts({ tenant, subjectType, subjectIds }) | comment_counts | the comment count per record |
s.blocks.notifications.inbox({ status }) | notification_page | the user's notifications and the total |
s.blocks.notifications.counts({}) | notification_counts | the unread and actionable counts |
s.blocks.savedViews.list({ tenant, list }) | list_views | the saved views of one list |
s.blocks.tags.list({ tenant }) | list_tags | the tenant's tags |
s.blocks.tags.forSubjects({ tenant, subjectType, subjectIds }) | subjects_tags | the tags per record, for up to 200 records |
s.blocks.attachments.list({ tenant, subjectType, subjectId }) | list_attachments | the files on a record |
Each read keeps the checks of its function: tags.forSubjects runs the
subject_tags check for every record, so one record the caller can't read
fails the read.
Batched record reads
The block also writes read_batch(calls jsonb), which runs up to 50 function
calls in one request and returns one result per call, in order:
select api.read_batch('[
{ "fn": "customer_tags", "args": { "customer_id": "…" } },
{ "fn": "customer_notes", "args": { "customer_id": "…" } }
]');
-- [{ "data": … }, { "error": { "code", "message", "details", "hint" } }]bsb.record(type).get and timeline use it on their own: the first read of
each binding goes into one read_batch call, and each binding gets the same
result or error a direct call would return. You don't call it yourself.
It calls a function only when a direct Data API call could too. It is
security invoker, so the caller's grants and RLS apply to every call. It
looks functions up in the API schema when the config sets api, and in the
block schema otherwise, so it reaches nothing the Data API hides. It runs only
stable or immutable functions that return jsonb, not a set, and whose
argument names cover the keys passed, and never itself. Any other call comes back
{ "skipped": true } and the client sends it on its own. An error in one call
doesn't fail the others. More than 50 calls fail with READ_BATCH_TOO_LARGE,
and anything but an array with READ_BATCH_INVALID.
Caching
In Next.js, tag a "use cache" scope with every table a set (or an array
of specs) reads:
export async function getWorkspaceSummary() {
"use cache: private";
const { db, session } = await bsb.cached();
bsb.tags(workspaceSummary);
if (session.kind !== "user") return null;
return db.$many(workspaceSummary, {}).orThrow();
}Any mutation of those tables revalidates the entry. A block read lists its
tables in reads.<instance>.<read>.tables, and bsb.tags tags the scope
with them. Block writes go through functions rather than repositories, so
name the tables a block action changes with invalidates:
export const archiveDeal = bsb.blockAction(
({ blocks }) => blocks.deals,
"archive",
{ input: archiveSchema, invalidates: reads.deals.board.tables },
);See Cache Components.
Doctor
BS304 reports a read-sets file that no longer
matches the sets in readSets. Run better-supabase gen (or
better-supabase upgrade), then supabase db schema declarative sync.
Check a result that crossed a boundary
readSet.parse(value) checks that a value has the shape db.$many(readSet, params) returns. Use it where a read set result passes through a cache, a Server Component prop or JSON. It returns a Result, naming each key with the wrong shape. It checks structure (counts are numbers, lists are arrays, a gated entry may be null), not each column. For a check of each column, use resultSchema. The block row parsers viewOf (saved views) and subscriptionOf (notifications) parse single rows from a page payload. A record binding stays unchecked until its function has a schema from registerRpcReturn.
Last updated on