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.tsimport { 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 } }),);}
export const readTodosWithIncludes = Effect.gen(function* () {const jazz = yield* Jazz;return yield* jazz.all(app.todos.where({ done: false }).include({ project: true, parent: { project: true } }),);});
/// Each todo with its project, and its parent with the parent's project.pub type TodoWithProjects = (Todo, Option<Project>, Option<(Todo, Option<Project>)>);pub async fn read_todos_with_includes(jazz: &Jazz) -> jazz_app::Result<Vec<TodoWithProjects>> {let query = todos::query().filter(todos::done().eq(false)).include(todos::project()).include(todos::parent().with(todos::query().include(todos::project())));jazz.all(query).await}
public func readOpenTodosWithProjects(_ jazz: Jazz.Client) async throws -> [JazzApp.Todo] {let todos = JazzApp.todos.self// Included rows land in the relation properties (`todo.project`,// `todo.parent?.project`), which are nil when not included.return try await jazz.all(todos.query().where(todos.done.eq(false)).include(todos.project, todos.parent.include(todos.project)))}
// Read an included row with `todo[Todos.project]`, or `todo.row(Todos.parent)`// to go on to its own includes.suspend fun readOpenTodosWithProjects(jazz: Jazz): List<JazzRow<Todo>> =jazz.all(Todos.where(Todos.done eq false).include(Todos.project, Todos.parent.include(Todos.project)),)
func ReadOpenTodosWithProjects(ctx context.Context, db *jazz.DB) ([]jazzapp.Todo, error) {// Fills each todo's Project, and its Parent with the parent's Project.return jazzapp.Todos.Query().Where(jazzapp.Todos.Done.Eq(false)).Include(jazzapp.Todos.Project, jazzapp.Todos.Parent.Include(jazzapp.Todos.Project)).All(ctx, db)}
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 }) }));}
export const readProjectsWithTodos = Effect.gen(function* () {const jazz = yield* Jazz;return yield* jazz.all(app.projects.include({ todos: app.todos.where({ done: false }) }));});
pub async fn read_projects_with_todos(jazz: &Jazz) -> jazz_app::Result<Vec<(Project, Vec<Todo>)>> {let open_todos = todos::query().filter(todos::done().eq(false));let query = projects::query().include(projects::todos().with(open_todos));jazz.all(query).await}
public func readProjectsWithOpenTodos(_ jazz: Jazz.Client) async throws -> [JazzApp.Project] {try await jazz.all(JazzApp.projects.query().include(JazzApp.projects.todos.where(JazzApp.todos.done.eq(false))))}
// `projects.todos` is the reverse of `todos.project`: read it with `project[Projects.todos]`.suspend fun readProjectsWithOpenTodos(jazz: Jazz): List<JazzRow<Project>> =jazz.all(Projects.include(Projects.todos.where(Todos.done eq false)))
func ReadProjectsWithOpenTodos(ctx context.Context, db *jazz.DB) ([]jazzapp.Project, error) {return jazzapp.Projects.Query().Include(jazzapp.Projects.Todos.With(jazzapp.Todos.Query().Where(jazzapp.Todos.Done.Eq(false)))).All(ctx, db)}
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") }),);}
export const readTodoTitlesWithSelectedProject = Effect.gen(function* () {const jazz = yield* Jazz;return yield* jazz.all(app.todos.select("title").where({ done: false }).include({ project: app.projects.select("name") }),);});
pub async fn read_todo_titles_with_selected_project(jazz: &Jazz,) -> jazz_app::Result<Vec<(Partial<Todo, String>, Option<Partial<Project, String>>)>> {// `select` reads only some columns: each row is a `Partial`, with its id.let query = todos::query().select(todos::title()).filter(todos::done().eq(false)).include(todos::project().with(projects::query().select(projects::name())));jazz.all(query).await}
/// The columns `select` reads (and `id`), with the included project's.public struct TodoTitle: Decodable, Sendable, Equatable {public struct ProjectName: Decodable, Sendable, Equatable {public var name: String}public var id: Jazz.IDpublic var title: Stringpublic var project: ProjectName?}public func readOpenTodoTitles(_ jazz: Jazz.Client) async throws -> [TodoTitle] {let todos = JazzApp.todos.selfreturn try await jazz.all(todos.query().where(todos.done.eq(false)).include(todos.project).select(todos.title),as: TodoTitle.self)}
// Only the columns you read; `id` comes along always.suspend fun readOpenTodoTitlesWithProjectNames(jazz: Jazz): List<JazzRow<Todo>> =jazz.all(Todos.where(Todos.done eq false).select(Todos.title).include(Todos.project.select(Projects.name)),)
// Your structs, whose json tags name the selected columns (and relation).type ProjectName struct {ID string `json:"id"`Name string `json:"name"`}type TodoTitle struct {ID string `json:"id"`Title string `json:"title"`Project *ProjectName `json:"project"`}func ReadOpenTodoTitles(ctx context.Context, db *jazz.DB) ([]TodoTitle, error) {return jazz.Select[TodoTitle](jazzapp.Todos.Query().Where(jazzapp.Todos.Done.Eq(false)).Include(jazzapp.Todos.Project.Select(jazzapp.Projects.Name)),jazzapp.Todos.Title,).All(ctx, db)}
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 first3 * tobytes. - 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());}
export const readOrdersWithRequiredCustomer = Effect.gen(function* () {const jazz = yield* Jazz;return yield* jazz.all(requiredReferences.orders.include({ customer: true }).requireIncludes());});
pub async fn read_orders_with_required_customer(jazz: &Jazz,) -> jazz_app::Result<Vec<(required_references::Order, required_references::Customer)>> {// `require` keeps only the orders whose customer is there, and includes// a `Customer` rather than an `Option<Customer>`.let query = required_references::orders::query().include(required_references::orders::customer().require());jazz.all(query).await}
// Only comments whose author this user can read: `required()` drops the others,// so `comment[Comments.author]` is there for every row it returns.val comments = jazz.all(Comments.where(Comments.taskId eq taskId).include(Comments.author.required()))
func ReadOrdersWithTheirCustomer(ctx context.Context, db *jazz.DB) ([]orders.Order, error) {// Only orders whose customer resolves (one you can read).return orders.Orders.Query().Include(orders.Orders.Customer).RequireIncludes().All(ctx, db)}
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:
| Option | Description |
|---|---|
start | A where filter selecting the root rows to begin traversal from |
step | A callback that receives { current } (a token for the row being visited) and returns a query with one .hopTo() call specifying which relation to follow |
maxDepth | Maximum 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,});}
pub fn build_todo_lineage_query() -> Query<Todo> {todos::query().filter(todos::done().eq(false)).gather(todos::parent(), 10)}
public func todoLineageQuery() -> Gathered<JazzApp.Todo> {let todos = JazzApp.todos.self// Each open todo, and its parent, its parent's parent and so on.return todos.query().where(todos.done.eq(false)).gather(todos.parent, maxDepth: 10)}
// From each open todo, its parent, the parent's parent and so on, up to 10 deep.fun buildTodoLineageQuery(): Query<Todo> =Todos.where(Todos.done eq false).gather(Todos.parent, maxDepth = 10)
func TodoLineageQuery() *jazz.Query[jazzapp.Todo] {// From each open todo, its chain of parents, up to 10 deep.return jazz.Gather(jazzapp.Todos.Query().Where(jazzapp.Todos.Done.Eq(false)), jazzapp.Todos.Parent, 10)}
This starts from all incomplete todos, then follows each todo's parentId → parent relation up to 10 levels deep, returning the full lineage.