Data
Read and write the app's tables from pages and components. Every read and write is a request to the app's data API as the signed-in user, so your row-level security policies (db/access/*.sql) decide what each person sees and changes. Rows are typed from db/schema.
Reads are cached per URL and shared by every component that asks for the same thing. On a public page they run on the server as a signed-out visitor, and the browser hydrates from the same rows.
Writes through useTable refresh the table's reads when they finish. Calling a server action (import it from server/ and call it) refreshes every read.
Reads
useQueryfunction
Rows of a table: where (equality), filter ([{ field, op, value }]), sort ("title", "-created_at" or { field, dir }), limit, offset or cursor, and embed (related rows in the same read: "experience(title,city)"). enabled: false waits. Rows are typed from db/schema.
useQuery<T extends TableName>(table: T, opts: QueryOptions & { enabled?: boolean } = {}): QueryResult<RowOf<T>>Parameters
| Name | Type | Description |
|---|---|---|
tablerequired | T | A table (or security_invoker view) in db/schema. |
optsoptional | QueryOptions & { enabled?: boolean } | The read. filter ops: eq, neq, lt, lte, gt, gte, in, not_in, contains, not_contains, starts_with, ends_with, is_null, is_not_null, between and the date ranges. |
- Returns
{ rows, total, hasMore, nextCursor, loading, error, refresh }.- Errors
- Never throws: a refused read is
error({ status, code, message }), for example 403TABLE_FORBIDDENfor a table marked@api off.
- Never throws: a refused read is
- Permissions
- Reads as the signed-in user (a signed-out visitor on a public page). Row-level security decides which rows come back; a role with no policy for the table gets none.
import { useQuery } from "@appbricx/ui";
const { rows, loading, hasMore, nextCursor } = useQuery("booking", {
where: { status: "requested" },
sort: "-created_at",
limit: 20,
embed: "experience(title)",
});Source: internal/kernel/appsdk/ui/app.tsx:412
useRowfunction
One row: by id (useRow("booking", id)), or, with no id, the row the route's meta.row binds from the URL. null as the id waits.
useRow<T extends TableName>(table: T, id?: string | null, opts: { embed?: string } = {}): RowResult<RowOf<T>>Parameters
| Name | Type | Description |
|---|---|---|
tablerequired | T | The table. |
idoptional | string | null | The row's id; leave it out for the route's bound row. |
optsoptional | { embed?: string } | embed, as in useQuery. |
- Returns
{ row, loading, error, notFound, refresh }.notFoundis true once read when there is no such row or the user may not read it.- Errors
- Never throws: see
errorandnotFound.
- Never throws: see
- Permissions
- Reads as the signed-in user (a signed-out visitor on a public page). Row-level security decides which rows come back; a role with no policy for the table gets none. A row the user can't read is
notFound, the same as a missing one.
const { row, notFound } = useRow("booking", bookingId, { embed: "experience(title)" });Source: internal/kernel/appsdk/ui/app.tsx:453
useListfunction
useQuery with a limit of 200: for pickers and small lookups (cities, categories).
useList<T extends TableName>(table: T, opts: Omit<QueryOptions, "limit"> = {}): QueryResult<RowOf<T>>Parameters
| Name | Type | Description |
|---|---|---|
tablerequired | T | |
optsoptional | Omit<QueryOptions, "limit"> |
- Returns
QueryResult<RowOf<T>>- Errors
- Never throws: see
error.
- Never throws: see
- Permissions
- Reads as the signed-in user (a signed-out visitor on a public page). Row-level security decides which rows come back; a role with no policy for the table gets none.
const cities = useList("city", { sort: "name" });
<select>{cities.rows.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}</select>Source: internal/kernel/appsdk/ui/app.tsx:436
Writes
useTablefunction
Writes to a table as the signed-in user: create(values) and update(id, patch) resolve with the written row, remove(id) deletes (soft-deletes on a ctx.soft_delete table). Every read of the table refreshes after each. Every row carries _version: update(id, patch, { ifVersion: row }) and remove(id, { ifVersion: row }) only write while the row is still the one you read (an edit form: useEditRow(table, row) does this and hands you the conflict). Without ifVersion the last write wins, as before.
useTable<T extends TableName>(table: T): { create: (row: Loose) => Promise<Loose>; update: (id: string, patch: Loose, opts?: WriteOptions | undefined) => Promise<Loose>; remove: (id: string, opts?: WriteOptions | undefined) => Promise<undefined>; }Parameters
| Name | Type | Description |
|---|---|---|
tablerequired | T | The table. |
- Returns
{ create, update, remove }, typed from the table's insert and update shapes.- Errors
- Rejects with an Error carrying
codeandstatus: 403TABLE_FORBIDDENorRLS_VIOLATIONwhen a policy refuses, 422RULE_REFUSEDwith your trigger'sraise exceptionmessage, 409CONFLICTon a unique column, 422E_LIFECYCLE_DIRECT_WRITEwhen a lifecycle column is written directly. - With
ifVersion: 409VERSION_CONFLICTwhen someone changed the row since (isVersionConflict(e);e.currentis the row as you may read it now, null when it was deleted or is no longer yours to read). Nothing was written.
- Rejects with an Error carrying
- Permissions
- Your policies'
with checkdecide what may be written; your triggers run. Columns with defaults such asuser_id default ctx.uid()are filled by the database, so leave them out.
const bookings = useTable("booking");
try {
await bookings.create({ experience_id: id, hr_id: me, team_size: 12, email });
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
// An edit of a row someone else may change meanwhile:
try {
await bookings.update(row.id, { notes }, { ifVersion: row });
} catch (e) {
if (isVersionConflict(e)) showTheirs(e.current); // nothing was written
else throw e;
}Source: internal/kernel/appsdk/ui/app.tsx:505
Named queries and actions
useNamedQueryfunction
Runs a db/queries/<name>.sql query in the browser with typed params and typed rows (Postgres describes the query at check time). Re-runs when the params change.
useNamedQuery<Q extends QueryName>(name: Q, params: QueryParamsOf<Q>, opts: { enabled?: boolean } = {}): QueryResult<QueryRowOf<Q>>Parameters
| Name | Type | Description |
|---|---|---|
namerequired | Q | The file's stem. |
paramsrequired | QueryParamsOf<Q> | Values for the query's -- @param lines. |
optsoptional | { enabled?: boolean } | enabled: false waits. |
- Returns
{ rows, loading, error, refresh }(totalis the row count; no paging).- Errors
- Never throws: 400
PARAMS_INVALIDfor a missing or mistyped param, 403 when the caller's role isn't in the query's-- @roles, inerror.
- Never throws: 400
- Permissions
- Runs as the caller, so row-level security applies to the tables it reads.
-- @roleslimits who may call it.
// db/queries/experience-bookings.sql
// -- @param experience uuid
// -- @roles host, ops
// select count(*)::int as bookings, coalesce(sum(team_size), 0)::int as people
// from booking where experience_id = :experience;
const { rows } = useNamedQuery("experience-bookings", { experience: id });
const people = rows[0]?.people ?? 0;Source: internal/kernel/appsdk/ui/app.tsx:554
callfunction
Calls a server action by name. You rarely need it: import the action from server/ and call it, which is the same call with types. Each call sends an idempotency key (yours with idempotencyKey), so a retry with the same key answers the first result without running twice. Every read refreshes afterwards.
call<O = unknown>(name: string, input: unknown, opts: { idempotencyKey?: string } = {}): Promise<O>Parameters
| Name | Type | Description |
|---|---|---|
namerequired | string | The action's export name. |
inputrequired | unknown | Its input. |
optsoptional | { idempotencyKey?: string } | idempotencyKey: up to 128 characters. |
- Returns
- The handler's return value.
- Errors
- Rejects with the action's thrown message (422
FUNCTION_FAILED),INVALID_INPUTnaming the field, or 403 when the caller's role isn't in the action'sroles. - Throws when called during a server render: actions run in the browser.
- Rejects with the action's thrown message (422
- Permissions
- Runs as the caller after its input is checked;
rolesdecides who may call it.
import { confirmBooking } from "../server/bookings";
const r = await confirmBooking({ booking: id }); // POST /__appbricx/actions/confirmBooking
setMessage(r.ref + " " + r.status);Source: internal/kernel/appsdk/ui/app.tsx:591
Types
interface QueryOptions {
/** Exact matches: { status: "published" }. */
where?: Record<string, unknown>;
/** Clauses, ANDed: [{ field, op, value }]. */
filter?: { field: string; op: string; value?: unknown }[];
/** "title" or "-created_at" (descending), or { field, dir }. */
sort?: string | { field: string; dir?: "asc" | "desc" };
limit?: number;
offset?: number;
cursor?: string;
/** Related rows in the same read: "experience(title,city),booking". */
embed?: string;
}Source: internal/kernel/appsdk/ui/store.ts:212
interface QueryResult<R> {
rows: R[];
/** Rows matching, past any limit (when the API counts them). */
total: number;
hasMore: boolean;
nextCursor: string | null;
loading: boolean;
error: ApiError | undefined;
refresh: () => void;
}Source: internal/kernel/appsdk/ui/app.tsx:392
interface RowResult<R> {
row: R | null;
loading: boolean;
error: ApiError | undefined;
/** Read, and no such row (or the user may not read it). */
notFound: boolean;
refresh: () => void;
}Source: internal/kernel/appsdk/ui/app.tsx:440
interface ApiError {
status: number;
code: string;
message: string;
/** The error's details, when it has some (VERSION_CONFLICT: {current, version}). */
details?: Record<string, unknown>;
}Source: internal/kernel/appsdk/ui/store.ts:7