Skip to content
clientdb

Search the docs

Find a page or section

Reference

Schema in TypeScript

Define models, fields and relations once; the schema types every read, write and permission rule, on the server and in the browser.

The schema is one value that the server and every client import. It says which models exist, their fields, how they relate, and when their rows reach a device. Everything else is typed from it: reads, writes, permission rules, and the Swift client's model classes.

Without Prisma, you write it in TypeScript, as on this page. With Prisma, fromPrisma builds the same value from schema.prisma.

The example is the todo app from the quick start (users, projects, members, todos and comments), with a few additions so every option appears once.

A schema file

src/sync/schema.ts
import { createSchema, model, t, type InferSchema } from "@clientdb/schema";

const user = model(
  {
    name: t.string(),
    email: t.string().unique(),
    avatarUrl: t.string().nullable(),
  },
  { load: "eager" },
);

const project = model(
  {
    name: t.string(),
    budget: t.decimal().nullable(), // exact: "1200.50"
    /** Lets people join the project; only admins receive it (see its field rule). */
    inviteCode: t.string().unique().restricted(),
  },
  { load: "eager", archivable: true },
);

const member = model(
  {
    project: t.belongsTo("project", { inverse: "members", onDelete: "cascade" }),
    user: t.belongsTo("user", { inverse: "memberships" }),
    role: t.enum(["member", "admin"]).default("member"),
  },
  { load: "eager", indexes: [["projectId", "role"]] },
);

const todo = model(
  {
    id: t.uuid({ prefix: "todo" }).id(), // todo_01932c…
    number: t.number().generated(), // #42, filled in by Postgres
    project: t.belongsTo("project", { inverse: "todos", onDelete: "cascade" }),
    author: t.belongsTo("user", { inverse: "todos" }),
    assignee: t.belongsTo("user", { inverse: "assignedTodos" }).nullable(),
    title: t.string(),
    done: t.boolean().default(false),
    isPrivate: t.boolean().default(false),
    createdAt: t.timestamp().defaultNow(),
    updatedAt: t.timestamp().updatedAt(),
  },
  { load: "eager" },
);

// lazy, the default: a todo's comments load the first time `todo.comments` is read
const comment = model({
  todo: t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" }),
  author: t.belongsTo("user", { inverse: "comments" }),
  body: t.string(),
  createdAt: t.timestamp().defaultNow(),
});

// stays on the server: rules and your backend can read it, clients never see it
const auditEntry = model(
  {
    actor: t.belongsTo("user", { inverse: "auditEntries" }),
    action: t.string(),
    createdAt: t.timestamp().defaultNow(),
  },
  { serverOnly: true },
);

const builtSchema = createSchema({ user, project, member, todo, comment, auditEntry });

/** A named type, so editor hovers show `Schema` instead of the whole structure. */
export interface Schema extends InferSchema<typeof builtSchema> {}
export const schema: Schema = builtSchema;
  • model(fields, options) describes one model. It gets its name from its key in createSchema: member, auditEntry.
  • Relations name their target model as a string, so models can point at each other in any order, and across files.
  • Every model has an id, a UUIDv7 generated on the device that creates the row. Declare it only to change it (here, a todo_ prefix).
  • The InferSchema interface is optional; it only keeps type hovers short. export const schema = createSchema({ … }) works the same.

Mistakes that involve one model are type errors on the offending property, and those that involve two (an unknown target, an inverse name that collides with a field) on the property in createSchema. The same checks run again when the schema is built, for plain JavaScript.

Fields

FieldType on the clientNotes
t.string()string
t.number()number
t.boolean()boolean
t.timestamp()numbera time, as milliseconds since 1970 (not a Date); new Date(todo.createdAt) to format it
t.enum(["member", "admin"])"member" | "admin"
t.json<T>()Tany JSON value; T is only a type, nothing checks it at runtime
t.uuid()stringa UUID-valued column; t.uuid({ prefix: "todo" }) generates todo_<UUIDv7> values
t.decimal()stringexact decimals (Postgres numeric), sent as strings such as "1200.50", never as floats

Every field takes these options:

OptionMeaning
.nullable()the value may be null; nullable fields are optional on create
.default(value)used when a create leaves the field out. .default(() => value) computes it on the device, in TypeScript only (the Swift client needs a plain value)
.defaultNow()on timestamps: the current time on create
.defaultUuid()on uuids: a new UUIDv7 on create, with the field's prefix
.updatedAt()on timestamps: set on create and on every update, at once on the device and again by the server, like Prisma's @updatedAt
.unique()the field identifies one row: a unique index, and a lazy read by it (db.user.where({ email })) loads that row
.indexed()an index for reads that filter by it; foreign keys and unique fields are indexed already
.generated()Postgres fills it in (an identity column on engine-owned tables, a sequence or trigger on yours). Clients read it but never send it: it's left out of the create and update types, and is null on the device until the server confirms the create
.restricted()only viewers allowed by the field's own read rule receive its value; for everyone else it is undefined, so its type on the client is T | undefined
.id()on the field named id: this field is the id. t.uuid({ prefix: "pay" }).id() makes ids such as pay_01932c… on every client, matching ids your backend creates. A prefix is letters and digits, starting with a letter

Only numbers can be .generated() on engine-owned tables. On Prisma's tables, any column with @default(autoincrement()) or @default(dbgenerated(…)) is generated.

Relations: t.belongsTo

A relation is declared once, on the model that holds the key:

TypeScript
// in `todo`:
author: t.belongsTo("user", { inverse: "todos" }),

That one line adds three things:

  • the key column authorId (a string), which you pass on create: db.todo.create({ authorId: viewerId, … });
  • the relation todo.author, the user row;
  • the collection user.todos, every todo whose authorId is that user. The name comes from inverse.
OptionMeaning
inverserequired: the name of the collection on the target (user.todos)
.nullable()the relation is optional: the key column may be null
foreignKeythe key column's name, when it isn't the relation name plus Id: t.belongsTo("user", { inverse: "todos", foreignKey: "createdBy" })
onDeletewhat deleting the target does to this row: "setNull" (the default for nullable relations), "restrict" (the default for required ones: the delete is refused while rows point at it) or "cascade"; see below
eager: truethe rows come along whenever their target arrives on a device; see below

Cascading relations

onDelete: "cascade" says the row lives and dies with its target. A comment without its todo means nothing, so comment.todo cascades:

  • Deleting the todo deletes its comments, on the device at once and on the server; undo brings the whole subtree back.
  • A comment counts as archived while its todo is: archiving the todo's project hides the project's todos and their comments too.

A model may cascade from several relations. A row then goes when any of its targets is deleted, and counts as archived while any of them is archived.

Cascading says nothing about who may read the row. Give the comment a read rule like any other model; $.canRead(comment.todo) makes it readable whenever its todo is (see Permissions).

Eager relations

eager: true means: whenever a target row arrives on a device, the rows that point at it through this relation come with it, however the target arrived. If comments should travel with their todo instead of loading on first read, mark the relation:

TypeScript
// in `comment`:
todo: t.belongsTo("todo", { inverse: "comments", onDelete: "cascade", eager: true }),

The cascade has fixed limits, so loading one row can't pull in a whole database:

  • It only goes down, from a target to the rows marked eager: true that point at it, and on from those.
  • The rows those point at (a comment's author) come along as single rows, and nothing cascades from them.
  • It stops at a model it already passed through, and at 5,000 rows per load (createEngine({ cascadeRowLimit })). What a cut cascade didn't deliver loads when it's read.

Load modes

load decides when a model's rows reach a device:

loadRows arrive
"lazy" (the default)when something reads them: a relation (todo.comments), a unique field (where({ email })), an id (get(id)), or the whole model (db.comment.all)
"eager"when the client starts: every row of the model the user may read

A lazy read returns what's on the device at once, and its status says whether more is on the way (see Reading data).

Use eager for models that stay small per user, such as their projects and teammates. A lazy model loads by id, by a unique field or by a foreign key; a read by any other field loads the whole model. On your own tables, give every foreign key an index, since Postgres doesn't add one: engine-owned tables have them already.

If one user may read 100,000 rows of an eager model, all of them load at startup, so the engine warns when a first load sends more than 20,000 rows (createEngine({ bootstrapRowWarning })).

Other model options

OptionMeaning
archivable: trueadds archivedAt and archivedBy, and project.archive() / project.unarchive(): an archived row is hidden on every device, with the rows that cascade from it, and kept in the database. See Archive and delete
serverOnly: truethe model stays on the server. Rules can read it (a membership table that decides who sees what), your backend can write it, and clients get no API for it or its relations. It needs no rules
indexes: [["projectId", "role"]]extra indexes on engine-owned tables, for reads that filter on several fields

The viewer model

Signed-in users are rows of one model: user, when the schema has one. Name another with createSchema(models, { viewer: "account" }). It types db.$viewer on the client and $.viewer in rules; your session callback returns the id of the viewer's row.

Types

src/sync/types.ts
import type { EntitiesOf } from "@clientdb/client";
import type { ClientRow, Insert, Row, Update } from "@clientdb/schema";
import type { Schema } from "./schema";

/** Entities by PascalCase model name, with their fields, relations and write methods: `DB["Todo"]`. */
export type DB = EntitiesOf<Schema>;

export type TodoRow = Row<Schema, "todo">; // every field, as stored
export type ProjectOnClient = ClientRow<Schema, "project">; // restricted fields as `T | undefined`
export type NewTodo = Insert<Schema, "todo">; // fields with defaults, nullable and generated ones optional or absent
export type TodoChanges = Update<Schema, "todo">; // any subset of the writable fields

Exporting the schema for other clients

The Swift client, and any other implementation of the protocol, reads the schema as JSON (clientdb.schema.json):

scripts/export-schema.ts
import { writeFileSync } from "node:fs";
import { exportSchema } from "@clientdb/schema";
import { schema } from "../src/sync/schema";

writeFileSync("clientdb.schema.json", JSON.stringify(exportSchema(schema), null, 2));

Run it whenever the schema changes, and commit the file with the app that reads it. See Swift.