Includes & Relations

Learn how to load related rows with include(), pick columns with select() and run recursive queries.

Includes

Use include(...) to load related rows as nested objects in a single query result. Pass true to resolve a relation, or a nested object to follow multi-hop references.

Including a relation adds the resolved object alongside the foreign-key column — it does not replace it. For example, include({ project: true }) gives you both projectId (the FK string) and project (the resolved row).

schema.ts
import { schema as s } from "jazz-tools";
​
export const schema = s.defineSchema({
todos: s.table(
{
title: s.string(),
done: s.boolean(),
priority: s.int().optional(),
description: s.string().optional(),
owner_id: s.uuid().optional(),
parentId: s.uuid().optional(),
projectId: s.uuid().optional(),
},
{
parent: s.rel("todos", "parentId"),
project: s.rel("projects", "projectId"),
children: s.reverse("todos", "parent"),
},
),
projects: s.table(
{
name: s.string(),
},
{ todos: s.reverse("todos", "project") },
),
});
export async function readTodosWithIncludes(db: Db) {
return db.all(
app.todos.where({ done: false }).include({ project: true, parent: { project: true } }),
);
}

Reverse relations

Declare reverse relations explicitly on the target table. For example, if todos declares the relation project: s.rel("projects", "projectId"), projects can declare todos: s.reverse("todos", "project") and load it with include({ todos: true }). The reverse relation returns matching source rows as an array. Its name is your choice; Jazz does not generate an inverse or infer names from UUID columns.

export async function readProjectsWithTodos(db: Db) {
return db.all(app.projects.include({ todos: app.todos.where({ done: false }) }));
}

You can chain .where(), .select(), .orderBy() and other query methods on the included reverse relation.

Select

Use select(...) to narrow a row to id plus the columns you pick. You can combine it with include(...), and select within included rows too.

export async function readTodoTitlesWithSelectedProject(db: Db) {
return db.all(
app.todos
.select("title")
.where({ done: false })
.include({ project: app.projects.select("name") }),
);
}

Partial large values

For a bytes, text, or JSON column, the object form of select(...) returns just the requested primitive slice or JSON subtree. The range end is exclusive. Text coordinates use JavaScript UTF-16 code units by default, so they match String.prototype.slice; use fromUtf8 and toUtf8 when interoperating with a byte-oriented protocol. Jazz rejects a range that would split a UTF-8 code point or UTF-16 surrogate pair rather than rounding it.

In Rust, text ranges are UTF-8 byte offsets, str indices: query.part(column, ValuePart::text(from..to)) reads &text[from..to]. ValuePart::TextUtf16 is there for interop with hosts that count UTF-16.

A range past the end of the value is clamped to it, like String.prototype.slice: one that starts past the end returns an empty string or empty bytes, and one that runs past it returns what the value still covers. So a subscription to a window of a text keeps going when the text shrinks below it, and shows the window again as the text grows back.

const [document] = await db.all(
app.documents.where({ id: documentId }).select({
bytes: { from: 1_000_000, to: 2_000_000 },
text: { from: 4, to: 124 },
utf8Text: { fromUtf8: 4, toUtf8: 67 },
metadata: { at: "/chapters/0/title" },
}),
);
​
// document.bytes is Uint8Array; text and utf8Text are strings; metadata is
// the decoded JSON value at that RFC 6901 pointer.

The object form is schema-aware: byte ranges are for bytes, text ranges are for string, and { at } is for json. Selecting a field by name continues to return the complete primitive.

Names and partial selections mix in one select, in any order, for example select("title", { content: { from: 0, to: 1_048_576 } }). A column is selected either whole or in part, not both: naming a column and also giving it a range, or giving it two ranges, throws.

Partial object selections currently apply to the root query only. An included relation may select complete fields by name, but rejects object-form partial selections until Jazz can carry terminal-specific demand through relation evaluation (#2090).

Jazz reads only the part you select. A range or pointer select loads, and syncs from the server, just the chunks that part covers, so reading the last page of a 100 MB value costs about as much as reading a small one. Edits elsewhere in the value don't make a range select fetch anything new. A few selections read more than their part:

  • A text range counts UTF-16 code units, which don't map to byte offsets without reading the text, so { from, to } reads up to the first 3 * to bytes.
  • A JSON pointer reads the document up to where the pointer points, and the work grows with the square of that distance. Only an index into a top-level array is read in part; a pointer into a nested array reads the document to its end.
  • A field that a computed field or a field transform depends on is read whole, and your selection is cut from the whole value.

Live changes as splices

A subscription can also tell you how a string or bytes column changed, not just its new value. Name the columns in the splices option, and each update's second argument maps a changed row's id to that row's splices:

const unsubscribe = db.subscribe(
app.documents.where({ id: documentId }),
{
onUpdate: (rows, { splices }) => {
const edits = splices.get(documentId)?.text;
if (edits) {
for (const { at, delete: length, insert } of edits) {
editor.replace(at, at + length, insert);
}
} else if (rows[0]) {
editor.setValue(rows[0].text);
}
},
},
{ splices: ["text"] },
);

The splices turn the value the previous update showed into the new one. They apply in order, so each splice's offsets are in the value the earlier ones produced. A string column's splices count UTF-16 code units (like String.prototype.slice) and insert a string. A bytes column's splices count bytes and insert a Uint8Array. In Rust, a ValueSplice's at and delete count UTF-8 bytes on a string column too, so text.replace_range(at..at + delete, insert) applies it; at_utf16 and delete_utf16 carry the same edit for hosts that count UTF-16. They work the same for your own writes and for changes that arrive from other clients. Jazz computes them by comparing the value's chunk trees, so a small edit to a large value only reads the chunks that changed.

On a range select, the splices are relative to the selected window and turn the window's old contents into its new contents. An insert before the window shifts its contents, and the splices describe that shift too.

A column that didn't change has an empty list. When a row has no entry for a column, read its new value from rows: Jazz couldn't compute splices locally, for example because the old version isn't stored on this device anymore. Splices are only supported for string and bytes columns without a column transform. Other columns, including json, are rejected with a "not supported yet" error when you subscribe, and so is a range-selected column that a computed field or field transform depends on, since that column is read whole. A computed field's dependencies can first show up on a later update; if one of them is such a column, the subscription ends then with the same error through onError. One-shot reads ignore the option.

Missing references

Jazz is distributed and supports offline edits, so a referenced row won't always be available locally — it might not have synced yet, or another peer might have deleted it.

When you don't load a reference, the FK column contains its raw value (the UUID string) and the row always appears in results.

When you load a forward reference with TypeScript include, the source row still appears if the target can't be resolved — for example, because it has not synced yet, was deleted, or is hidden by permissions. The included field is null. A nullable, unset reference also produces null.

Requiring includes

Use .requireIncludes() when every included, non-nullable forward reference must resolve. It drops a source row if one of those required targets is unavailable.

export async function readOrdersWithRequiredCustomer(db: Db) {
return db.all(requiredReferences.orders.include({ customer: true }).requireIncludes());
}

requireIncludes() only filters non-nullable forward references (FK → row). Nullable forward references and reverse relations (such as authoredPosts) are unaffected. When used inside a nested include, it applies at that nesting level only.

Magic columns

Jazz exposes computed columns for edit metadata ($createdBy, $createdAt, $updatedBy, $updatedAt). See Magic columns for details and examples.

Recursive queries with gather and hopTo

If your data has self-referencing relations (e.g. a todo with a parent that points to another todo), use gather(...) to walk the graph recursively and collect all reachable rows in a single query.

gather takes three options:

OptionDescription
startA where filter selecting the root rows to begin traversal from
stepA callback that receives { current } (a token for the row being visited) and returns a query with one .hopTo() call specifying which relation to follow
maxDepthMaximum recursive hops (default: 10). The start rows are depth 0, so 0 returns only those rows

Inside the step callback, call hopTo(relation) to tell Jazz which reference to follow at each level.

Depth is counted from the start relation: maxDepth: 0 returns only the start rows, while maxDepth: 1 may also return rows reached by one step hop. A zero bound never performs an implicit first hop.

export function buildTodoLineageQuery() {
return app.todos.gather({
start: { done: false },
step: ({ current }) => app.todos.where({ id: current }).hopTo("parent"),
maxDepth: 10,
});
}

This starts from all incomplete todos, then follows each todo's parentId → parent relation up to 10 levels deep, returning the full lineage.