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.

@appbricx/ui6 membersSDK referenceData API over HTTP

On this page
  1. Reads
  2. useQuery
  3. useRow
  4. useList
  5. Writes
  6. useTable
  7. Named queries and actions
  8. useNamedQuery
  9. call
  10. Types

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

NameTypeDescription
tablerequiredTA table (or security_invoker view) in db/schema.
optsoptionalQueryOptions & { 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 403 TABLE_FORBIDDEN for a table marked @api off.
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.
Example
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

NameTypeDescription
tablerequiredTThe table.
idoptionalstring | nullThe 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 }. notFound is true once read when there is no such row or the user may not read it.
Errors
  • Never throws: see error and notFound.
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.
Example
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

NameTypeDescription
tablerequiredT
optsoptionalOmit<QueryOptions, "limit">
Returns
QueryResult<RowOf<T>>
Errors
  • Never throws: see error.
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.
Example
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

NameTypeDescription
tablerequiredTThe table.
Returns
{ create, update, remove }, typed from the table's insert and update shapes.
Errors
  • Rejects with an Error carrying code and status: 403 TABLE_FORBIDDEN or RLS_VIOLATION when a policy refuses, 422 RULE_REFUSED with your trigger's raise exception message, 409 CONFLICT on a unique column, 422 E_LIFECYCLE_DIRECT_WRITE when a lifecycle column is written directly.
  • With ifVersion: 409 VERSION_CONFLICT when someone changed the row since (isVersionConflict(e); e.current is the row as you may read it now, null when it was deleted or is no longer yours to read). Nothing was written.
Permissions
Your policies' with check decide what may be written; your triggers run. Columns with defaults such as user_id default ctx.uid() are filled by the database, so leave them out.
Example
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

NameTypeDescription
namerequiredQThe file's stem.
paramsrequiredQueryParamsOf<Q>Values for the query's -- @param lines.
optsoptional{ enabled?: boolean }enabled: false waits.
Returns
{ rows, loading, error, refresh } (total is the row count; no paging).
Errors
  • Never throws: 400 PARAMS_INVALID for a missing or mistyped param, 403 when the caller's role isn't in the query's -- @roles, in error.
Permissions
Runs as the caller, so row-level security applies to the tables it reads. -- @roles limits who may call it.
Example
// 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

NameTypeDescription
namerequiredstringThe action's export name.
inputrequiredunknownIts 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_INPUT naming the field, or 403 when the caller's role isn't in the action's roles.
  • Throws when called during a server render: actions run in the browser.
Permissions
Runs as the caller after its input is checked; roles decides who may call it.
Example
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