Skip to content
clientdb

Search the docs

Find a page or section

Guides

Reading data

Synchronous, typed, reactive reads: lookups, filters, relations, lazy loads, server queries and eviction.

Every read is synchronous: it returns what's on the device right away, never a promise. Collections are reactive and, while observed, maintained incrementally from each change. The examples use the todo app from the quick start: users, projects, members, todos (eager) and comments (lazy).

Getting the database

The client is the database: models hang directly off it (db.todo), and the client's own members start with $ (db.$ready(), db.$undo()), so they never collide with a model name.

src/sync/db.ts
"use client";
import { createDatabaseClient, indexedDb, type EntitiesOf } from "@clientdb/client";
import { schema, type Schema } from "./schema";

export const db = createDatabaseClient({ schema, storage: indexedDb() });

export type DB = EntitiesOf<Schema>;
export type Todo = DB["Todo"];

Lookups and whole models

TypeScript
import { db } from "@/sync/db";

db.todo.get(todoId); // Todo | undefined, archived rows included
db.todo.all; // readonly Todo[]
db.todo.count;
db.todo.first; // Todo | null
db.todo.isEmpty;

Filtering, ordering, limits

TypeScript
import { db } from "@/sync/db";

const recent = db.todo
  .where({ projectId, done: false, createdAt: { gte: Date.now() - 7 * 24 * 3600_000 } })
  .orderBy("createdAt", "desc")
  .orderBy("title") // later orderBy calls are tie-breakers
  .limit(20)
  .all; // live, maintained incrementally while observed

const releaseTodos = db.todo.where({ title: { contains: "release", mode: "insensitive" } }).all;
  • A value means equality; an array means "any of".
  • gt, gte, lt and lte compare numbers, timestamps and text. Timestamps are numbers: milliseconds since 1970.
  • contains, startsWith and endsWith match text; mode: "insensitive" ignores case.
  • orderBy takes a field name or a function, and a direction ("asc" by default). Without orderBy, the order is unspecified.
  • A predicate is allowed too, but it re-runs on every change instead of being maintained incrementally:
TypeScript
import { db } from "@/sync/db";

const shortTitles = db.todo.where((todo) => {
  return todo.title.length < 10;
});

Queries are interned by their filters while observed and released when nothing observes them, so writing the same query in two components costs one.

Collections

Every collection (db.todo, a where(…), a relation like project.todos) has the same shape:

MemberMeaning
all, first, last, count, isEmptythe current result
get(id)a member by id, or undefined
where, orderBy, limita refined collection
includeArchived()include archived rows (hidden by default)
status"complete", "loading" or "partial" (see lazy models)
isLoadingtrue while missing rows are being fetched
preload()start fetching missing rows early, as an optimisation; returns a promise

Relations

Relations are typed from the schema and indexed on the foreign key:

TypeScript
import type { Todo } from "@/sync/db";

export function describe(todo: Todo) {
  const projectName = todo.project.name; // to-one
  const authorName = todo.author.name; // to-one, through `authorId`
  const openInProject = todo.project.todos.where({ done: false }).count; // the inverse collection
  return `${projectName} · ${authorName} · ${openInProject} open`;
}

Lazy models load when read

A model is lazy unless it says load: "eager". Its rows arrive the first time a read needs them, and stay. You don't fetch them yourself: reading a collection (.all, .count, .first and so on) or a row loads whatever it's missing, by what the read names:

ReadLoads
todo.commentsthe comments of this todo (a foreign key)
db.user.where({ email })the user with that email (a .unique() field)
db.comment.get(id)that comment
db.comment.all, or a where on other fieldsevery comment the user may read

Reads in the same tick are batched into one request, and each set of rows is fetched only once. While rows are on their way, the collection returns what it has (often nothing), isLoading is true and status is "loading". When they arrive, everything that read the collection updates:

src/app/Comments.tsx
import { live } from "@clientdb/react";
import { Spinner } from "@/components/spinner";
import type { Todo } from "@/sync/db";

export const Comments = live(({ todo }: { todo: Todo }) => {
  const comments = todo.comments.orderBy("createdAt").all; // the first read loads this todo's comments

  if (todo.comments.isLoading) {
    return <Spinner />;
  }
  return comments.map((comment) => {
    return <p key={comment.id}>{comment.body}</p>;
  });
});

Every way in is separate. If comments belong to a todo (todoId) and an author (authorId), todo.comments and user.comments each load on their own: reading one user's comments loads all of them, even when some are already on the device because their todos were opened. Until then user.comments.status is "partial": some rows are here, not all.

The server loads these rows with WHERE "todoId" = $1 (or "authorId"). Tables clientdb creates index every foreign key; on your own tables (Prisma), add an index for each foreign key of a lazy model, such as @@index([authorId]).

preload(): fetching early

preload() starts the same fetch before anything reads the collection. It is only an optimisation, for example to fetch a todo's comments when the pointer hovers over its link, so they're there by the time it opens. It returns a promise that resolves when the rows have arrived.

src/app/TodoLink.tsx
import { live } from "@clientdb/react";
import type { Todo } from "@/sync/db";

export const TodoLink = live(({ todo }: { todo: Todo }) => {
  return (
    <a
      href={`/todos/${todo.id}`}
      onMouseEnter={() => {
        todo.comments.preload();
      }}
    >
      {todo.title}
    </a>
  );
});

Eager relations come along

eager: true on a relation makes children travel with their parent: whenever a parent row arrives, however it arrived, its children come in the same response. With eager: true on comment.todo, a todo that loads brings its comments, so todo.comments is complete at once.

src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "../generated/clientdb";

export const schema = fromPrisma(prismaModels, {
  omit: { User: ["passwordHash"] },
  models: {
    User: { load: "eager" },
    Project: { load: "eager" },
    Member: { load: "eager" },
    Todo: { load: "eager" },
    Comment: { relations: { todo: { eager: true } } },
  },
});
export type Schema = typeof schema;

The cascade only goes down, from parents to the children marked eager, and on from those. The rows those children point at (a comment's author) come along as single rows. It stops at a model it already passed through, and at 5,000 rows per load; what a cut cascade didn't deliver loads when it's read. Eager children of an eager model arrive at startup, so here every todo's comments would load when the app opens: use it where the children stay few.

Server queries: rows that aren't on the device

where filters the rows on the device. To search rows that aren't there, such as every comment in a large project, ask the server with query:

src/app/CommentSearch.tsx
import { live } from "@clientdb/react";
import { db } from "@/sync/db";

export const CommentSearch = live(({ text }: { text: string }) => {
  const results = db.comment.query({
    where: { body: { contains: text, mode: "insensitive" } },
    orderBy: ["createdAt", "desc"],
    limit: 20,
  });

  return (
    <section>
      {results.status === "loading" && <p>Searching…</p>}
      {results.all.map((comment) => {
        return <p key={comment.id}>{comment.body}</p>;
      })}
      {results.hasMore && (
        <button
          onClick={() => {
            results.loadMore();
          }}
        >
          More
        </button>
      )}
    </section>
  );
});

The server's answer is merged with what's already on the device, in order, cut to the pages loaded. Its rows become ordinary rows on the device, with their eager children.

results.statusMeaning
"loading"the server hasn't answered, and nothing on the device matches yet
"partial"the server hasn't answered (or failed); matching rows already on the device are shown
"complete"the server answered; the result stays live with local changes, and results.refresh() asks again for rows that only started matching on the server

query takes the same where as local reads, an orderBy of one field and a direction (ties are ordered by id), and a limit per page. loadMore() loads the next page and preload() asks without reading the result; both resolve when the rows are on the device.

A model can only be queried when its rules say which fields and operators where may use, and the largest page. Results are still limited to rows the viewer may read:

src/sync/permissions/comment.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";

export const commentRules = defineModelRules(schema, "comment", {
  read: (comment, $) => {
    return $.canRead(comment.todo);
  },
  create: {
    when: (comment, $) => {
      return $.canRead(comment.todo);
    },
    enforce: ($) => ({ authorId: $.viewer.id }),
  },
  query: {
    fields: { body: ["contains"], authorId: ["is"], createdAt: ["gte", "lte"] },
    maxLimit: 50,
  },
});

A query on another field or operator, or a larger limit, is refused with Forbidden.

Keeping memory in check: eviction

A client that loads lazily keeps every row it loaded. For an app that browses far more data than it needs at once, such as an admin panel over every customer, cap it:

src/sync/adminDb.ts
"use client";
import { createDatabaseClient } from "@clientdb/client";
import { schema } from "./schema";

export const adminDb = createDatabaseClient({
  schema,
  url: "/api/admin/sync",
  load: "lazy", // no startup load: every model loads when it's read, eager ones included
  eviction: { maxRows: 50_000 },
});

Past maxRows, the client drops the loads used longest ago, each as a whole: a todo's comments, a server query's pages, one load with its cascade. Collections that held those rows read as "partial" again and load them when read. What stays:

  • whatever is on screen: every row an observed collection, server query or get(id) shows, every row whose fields a component reads (wherever the entity came from), and the loads that brought them, with their eager cascade;
  • eager models (with load: "lazy" on the client, nothing is eager);
  • rows with unsent writes or unsaved drafts.

Archived rows

Archivable models (archivable: true in the schema, or in fromPrisma's models) can archive rows instead of deleting them. Default collections hide archived rows:

TypeScript
import { db } from "@/sync/db";

db.todo.archived.all; // only archived
db.todo.includeArchived().all; // both
todo.isArchived;

See Archive vs delete.

Client state

PropertyMeaning
db.$viewerthe signed-in user's own row, as verified by the server (db.$viewer?.name), or null
db.$sessionwhat the server verified: viewerId, claims, readOnly and hasClaim(claim)
db.$status"bootstrapping", "online", "offline", "outdated" and so on
db.$pendingCounttransactions not yet confirmed
db.$lastSyncIdthe last sync id applied
db.$groupsthe viewer's access groups (under the hood)
db.$clientIdthis client's id (used to deduplicate resent transactions)

Tip

In React, wrap reads in useLive(() => …) (no dependency array) so the component re-renders only when the result changes, or render entities in live() components. With MobX, use observer() and read directly. See React.