---
name: client-db
description: "Use when routes or components read/write application-owned records with TanStack DB: collection descriptors, shared live query options, useLiveQuery/useLiveSuspenseQuery, loader preloading and SSR hydration, optimistic CRUD, joins, on-demand sync and paging, or data that is empty, fetched too broadly, stale or rolled back."
metadata:
  type: convention
  library: wcz-layout
---

Query builder, operators, hooks and the transaction API: load `@tanstack/db#db-core` with its
`live-queries` and `mutations-optimistic` sub-skills, and `@tanstack/react-db#react-db`.

## Rules

- `src/router.tsx` creates one `DbClient({ queryClient })` per request,
  puts both on the router context and returns `routerWithDbClient(router, dbClient)`.
- A collection is a `collectionOptions` descriptor, never `createCollection` or a
  module-scope `QueryClient`: both leak between SSR requests. `use<Entity>Collection`, next to
  it, is how components get the collection to write to. `queryFn` calls the entity's select
  server function with its Query `signal`, `schema` is its row schema. Include dynamic
  collection scope in both `id` and `queryKey`; one client reuses the first descriptor per id.
- Each live query is defined once in `src/db/queries/<entity>.ts` and shared by loader and
  component as the same config form, not just its `.query` callback. Business filters,
  ordering, joins and aggregates belong there.
- Loaders preload and return the promise:
  `loader: ({ context }) => context.dbClient.preloadLiveQuery(featuresQueryOptions)`, or
  `Promise.all([...])` of every live query the page reads (a form's picker options too). SSR
  then ships those queries' rows and the first render has data. Never `void` it (empty SSR),
  never `collection.preload()` (a no-op on-demand), never `dbClient.collection()` in a loader
  (it ships the collection's rows a second time).
- `setupRouterSsrQueryIntegration` also ships every query in the `QueryClient`: an eager
  collection's whole table goes out even when the page preloads one row; on-demand collections
  ship only the subsets they loaded. The browser still refetches after hydration.
- Lists read `useLiveQuery(options)` (`data`, `isLoading`). Detail and edit pages read
  `useLiveSuspenseQuery(byIdOptions(id))` under the route's `pendingComponent`. `.findOne()`
  still yields `T | undefined`: render `<RouterNotFound />` for a missing row, which also
  covers one deleted while the page is open.
- Every write is a `createOptimisticAction`: `onMutate` mirrors the change on the collection;
  `mutationFn` awaits the server function, then `utils.refetch({ throwOnError: true })` on
  every collection it changed. The caller awaits `when("settled")` in `try`; `catch` alerts
  `error.message` (the optimistic change has already rolled back).
- Serialize writes that can overlap on one collection (scanner input, repeated Enter): each
  `utils.refetch` cancels the one in flight, and with three or more overlapping writes all but
  the last two actions roll back with `CancelledError` although the server saved. Queue them
  with `usePacedMutations` + `queueStrategy` or a promise chain.
- One query per parent, never `useLiveQuery` per row: `DbClient` queries don't pool, so 50 rows
  make 50 queries and requests. Load children with `inArray(child.parentId, ids)` and split
  them in the component.
- `groupBy` selects grouped columns, expressions over them (`coalesce(a, b)`) and aggregates.
  A grouped row has no `id`; select one when `LayoutTable` shows it (table).

## Sync mode

- **eager** (default): the collection loads whole. Small reference data/top-level tables;
  ~10k rows is a sizing heuristic, not a safe payload or memory limit.
- **on-demand**: each live query loads only its subset, with `where`, `orderBy` and `limit`
  eligible for server push-down, not a guarantee for every query plan. Bigger tables and child
  rows read per parent. agnostic-query carries
  the subset to Drizzle (`agnostic-query#adapters`; server function in server-functions). The
  collection adds:

  ```ts
  // fromTanDb from agnostic-query/tanstack-db, BasicIndex from @tanstack/react-db
  syncMode: "on-demand",
  queryFn: ({ meta, signal }) =>
    selectFeatures({ data: fromTanDb(meta?.loadSubsetOptions), signal }),
  autoIndex: "eager",
  defaultIndexType: BasicIndex,
  defaultStringCollation: { stringSort: "lexical" },
  ```

  Without the index, an ordered `limit` query warns and can load the whole table; with the
  default locale string sort, ordering by any text field (uuid ids included) does. Lexical
  order matches Postgres for uuid, number and date columns; a text sort column needs
  `COLLATE "C"` on the server.

- Joining two on-demand collections: `leftJoin` from the side the `where` narrows. `innerJoin`
  loads the smaller side first and, on a tie (both still empty), the joined collection whole.
- Collections don't page on the server: page N's first request reads rows 0 to N × size (no
  offset reaches `queryFn`), and nothing counts the server's rows for the pager. Tables over
  more rows than the browser should hold page with TanStack Query (table).

## Examples

```ts
// src/db/collections/feature.ts
import { queryCollectionOptions } from "@tanstack/query-db-collection";
import { collectionOptions, useDbClient } from "@tanstack/react-db";
import type { QueryClient } from "@tanstack/react-query";
import { FeatureSchema } from "~/lib/schemas/feature";
import { selectFeatures } from "~/server/actions/feature";

const FEATURES_ID = "features";

export const featureCollection = collectionOptions(FEATURES_ID, (client) =>
  queryCollectionOptions({
    id: FEATURES_ID,
    queryKey: [FEATURES_ID],
    queryFn: ({ signal }) => selectFeatures({ signal }),
    getKey: ({ id }) => id,
    schema: FeatureSchema,
    queryClient: client.requireDependency<QueryClient>("queryClient"),
  }),
);

export const useFeatureCollection = () => useDbClient().collection(featureCollection);
```

```ts
// src/db/queries/feature.ts
import type { InitialQueryBuilder } from "@tanstack/react-db";
import { eq } from "@tanstack/react-db";
import { featureCollection } from "../collections/feature";

// uuidv7 sorts client creation time, not database insertion order.
export const featuresQueryOptions = {
  query: (q: InitialQueryBuilder) =>
    q.from({ feature: featureCollection }).orderBy(({ feature }) => feature.id, "desc"),
};

export const featureByIdQueryOptions = (id: string) => ({
  query: (q: InitialQueryBuilder) =>
    q
      .from({ feature: featureCollection })
      .where(({ feature }) => eq(feature.id, id))
      .findOne(),
});
```

```tsx
// a write in a component. update: features.update(id, (draft) => Object.assign(draft, value));
// delete: ids.forEach((id) => features.delete(id)) with deleteFeatures({ data: ids })
const features = useFeatureCollection();

const handleOnSubmit = createOptimisticAction<Feature>({
  onMutate: (value) => {
    features.insert(value);
  },
  mutationFn: async (value) => {
    await insertFeature({ data: value });
    await features.utils.refetch({ throwOnError: true });
  },
});

try {
  await handleOnSubmit(value).when("settled");
  await navigate({ to: "/features" });
} catch (error) {
  if (error instanceof Error) await alert(error.message);
}
```
