Graph Modeling
In Relate, your domain model is defined in TypeScript using the relate
package. A graph consists of sources, objects, references, and
relationships, registered together with defineGraph.
For aggregate properties over external rows, see Datasets and Calculations.
1. Defining Sources
Sources declare external systems of record. Each source has a stable identifier, the field holding its record key, and a Zod schema for its records:
import { z } from 'zod';
import { defineSource } from 'relate';
export const crmSource = defineSource({
id: 'crm.customers',
idField: 'id',
schema: z.object({
id: z.string(),
name: z.string(),
region: z.string(),
tier: z.string(),
}),
});
export const billingSource = defineSource({
id: 'billing.invoices',
idField: 'invoice_id',
schema: z.object({
invoice_id: z.string(),
customer_id: z.string(),
amount_cents: z.number().min(0),
status: z.string(),
}),
});id: Stable identifier for the source definition.idField: The field inschemaholding the source's record key.schema: An ordinaryz.object. Mapped fields must be plainz.string(),z.number(), orz.boolean(), optionally wrapped in.optional()or.nullable(). String length bounds (.min,.max,.length) and number range bounds (.min,.max,.gt,.lt) are kept. Enums,.int(), formats such asz.email(), refinements, transforms, coercion, and defaults are rejected at compile time. Unmapped source fields are kept privately and never exposed.
2. Defining Objects
Objects represent business entities in the graph. They define an object ID, presentation labels, source membership, and mapped properties.
import { defineObject, from, objectId, source } from 'relate';
import { crmSource } from './sources.js';
export const Customer = defineObject({
id: 'customer',
label: 'Customer',
pluralLabel: 'Customers',
description: 'Enterprise and commercial customer accounts.',
membership: source(crmSource),
properties: {
id: objectId({
id: 'customer.id',
description: 'Opaque Relate customer ID.',
}),
name: from(crmSource.fields.name, {
id: 'customer.name',
description: 'Registered business name.',
}),
region: from(crmSource.fields.region, { id: 'customer.region' }),
tier: from(crmSource.fields.tier, { id: 'customer.tier' }),
},
});An object has a single membership source, and its from properties must read
fields of that source. Combining fields from a second source is a preview and
not yet supported.
Property Types
| Helper | Description | Example |
|---|---|---|
objectId({ id }) | The object ID, generated by Relate. Exactly one per object. | objectId({ id: 'customer.id' }) |
native(schema, { id, access? }) | A scalar value owned by Relate, created inside an action. | native(z.string(), { id: 'review.note' }) |
from(sourceField, { id, access? }) | Maps a property to a field of the membership source, with its type inferred. | from(crm.fields.name, { id: 'customer.name' }) |
reference(TargetObject, { id, from?, access? }) | Typed pointer to another graph object. With from, the target is resolved from a source field; without it, the reference is stored natively by Relate. | reference(Customer, { id: 'invoice.customer', from: billing.fields.customer_id }) |
Native Objects
Relate-owned records use nativeMembership() instead of a source. Define the
review object used by the Actions guide like this:
// model.ts (excerpt; Customer is the application's customer definition)
import { z } from 'zod';
import {
defineObject,
native,
nativeMembership,
objectId,
reference,
} from 'relate';
export const AccountReview = defineObject({
id: 'business.account-review',
membership: nativeMembership(),
properties: {
id: objectId({ id: 'business.account-review.id' }),
customer: reference(Customer, { id: 'business.account-review.customer' }),
author: native(z.string(), { id: 'business.account-review.author' }),
note: native(z.string().min(1).max(4000), {
id: 'business.account-review.note',
}),
},
});Register it in objects and give it explicit read and create rules. For an
access definition with employee and account-manager roles, this policy lets
account managers create reviews attributed to themselves:
// Inside defineGraph({ policies: { ... } })
AccountReview: {
read: { gate: access.role('employee') },
create: {
gate: access.role('account-manager'),
where: { author: { eq: access.actor.id } },
evidenceMaxAgeMs: 30_000,
},
}The Access Control guide
adds customer-portfolio restrictions. A native reference stores a target's
Relate object ID; it has no source-field mapping. Creation validates reference
targets and permissions. host.adopt cannot create native records: an action
must list the object in creates and call its create method. Native updates
and deletes are not implemented.
Machine Names vs Display Labels
- Registry key (
apiName): The key underobjects: { Customer }indefineGraphis the public API name used in SDK calls:objects.Customer. Changing it renames the public API. - Definition
id: The stable definition identity (e.g.'customer'). Stored data is keyed by object and property IDs, so renaming a registry key or property keeps those IDs. A rename still changes the graph's definition revision, which an existing Postgres installation will refuse until it is explicitly migrated (see compilation). labelandpluralLabel: Display names for documentation, UIs, and agents.labeldefaults to the humanized registry key (AccountReview→Account Review);pluralLabeldefaults to the singular label.description: Business meaning exposed to documentation, UIs, and actor-bound discovery. Property helpers accept the same optional metadata.
3. Defining References and Relationships
To connect objects, declare a reference property on the dependent object,
define a relationship over it, and register both in defineGraph:
import { z } from 'zod';
import {
defineAccess,
defineGraph,
defineObject,
defineRelationship,
from,
objectId,
reference,
source,
} from 'relate';
import { billingSource } from './sources.js';
import { Customer } from './customer.js';
export const Invoice = defineObject({
id: 'invoice',
label: 'Invoice',
pluralLabel: 'Invoices',
membership: source(billingSource),
properties: {
id: objectId({ id: 'invoice.id' }),
customer: reference(Customer, {
id: 'invoice.customer',
from: billingSource.fields.customer_id,
}),
amount: from(billingSource.fields.amount_cents, { id: 'invoice.amount' }),
status: from(billingSource.fields.status, { id: 'invoice.status' }),
},
});
export const CustomerInvoices = defineRelationship({
id: 'customer.invoices',
forward: {
name: 'invoices',
description: 'Invoices billed to this customer.',
},
reverse: {
name: 'customer',
description: 'Customer billed by this invoice.',
},
via: Invoice.properties.customer,
});
const access = defineAccess({
roles: ['sales'],
fieldGroups: ['ordinary'],
claims: { region: z.string() },
});
export const graph = defineGraph({
id: 'business',
description: 'Customer accounts and their invoices.',
objects: { Customer, Invoice },
relationships: { CustomerInvoices },
access,
policies: {
Customer: { read: { gate: access.role('sales') } },
Invoice: { read: { gate: access.role('sales') } },
},
});Every registered object needs a read policy; use read: 'deny' to deny it on
purpose. See Access Control.
Once CustomerInvoices is registered under relationships:
- Callers can traverse forward from a
Customerto itsinvoiceswithobjects.Customer.traverse.invoices(id). - Callers can traverse in reverse from an
Invoiceto itscustomerwithobjects.Invoice.traverse.customer(id).
See Reading Data for traversal results.
Many-to-many relationships
Use through to expose direct collections in both directions over an explicit
junction object. For example, a playlist has songs and a song belongs to
playlists. The junction can retain its own position and other metadata.
Given registered Playlist and Song objects, define the junction and
relationship:
import { z } from 'zod';
import {
defineObject,
defineRelationship,
defineSource,
from,
objectId,
reference,
source,
} from 'relate';
const memberships = defineSource({
id: 'music.memberships',
idField: 'id',
schema: z.object({
id: z.string(),
playlist_id: z.string(),
song_id: z.string(),
position: z.number(),
}),
});
const Membership = defineObject({
id: 'membership',
membership: source(memberships),
properties: {
id: objectId({ id: 'membership.id' }),
playlist: reference(Playlist, {
id: 'membership.playlist',
from: memberships.fields.playlist_id,
}),
song: reference(Song, {
id: 'membership.song',
from: memberships.fields.song_id,
}),
position: from(memberships.fields.position, {
id: 'membership.position',
}),
},
});
const PlaylistSongs = defineRelationship({
id: 'playlist.songs',
forward: 'songs',
reverse: 'playlists',
through: {
from: Membership.properties.playlist,
to: Membership.properties.song,
},
});Register objects: { Playlist, Song, Membership } and
relationships: { PlaylistSongs } in defineGraph, with read policies for all
three objects. Both references must be distinct properties of the same
registered junction object. Relate infers the endpoints from their targets and
sets both traversal cardinalities to many. Use either via or through in a
relationship, never both. Two references to the same target object can also
model a self relationship, with different forward and reverse traversal names.
The junction and endpoints may be source-backed or native. Source-backed records must be adopted before traversal; native records must already exist. The relationship itself does not create records, adopt provider data, or copy links into separate storage.
A direct traversal returns distinct destination objects in object-ID order. It
does not expose membership metadata or follow a membership's position. To work
with individual playlist entries, including repeated songs, register an
additional ordinary relationship:
const PlaylistEntries = defineRelationship({
id: 'playlist.entries',
forward: 'entries',
reverse: 'playlist',
via: Membership.properties.playlist,
});Include PlaylistEntries in the relationship registry, then use
objects.Playlist.traverse.entries(playlistId, { select: ['song', 'position'] })
and apply your desired ordering to the collected entries. You can also query
objects.Membership directly.
Adding or removing a link remains an operation on the junction's owning system.
Use existing native actions for supported native writes; this API adds read
traversal and does not add generic connect, disconnect, update, or delete
operations. See Actions for the supported native write
surface and Reading Data
for traversal examples and access behavior.
4. Graph Compilation & Revision Pinning
compile(graph) from relate/compiler checks the graph and produces its
manifest. createRuntime compiles the graph for you, so you only need to call
it directly to inspect or store the result. Compilation:
- Verifies property IDs, source fields, reference targets, field groups, and
policy dependencies, throwing a
CompileErrorthat lists every issue. - Produces an immutable, serializable manifest (format 5), including discovery
descriptions and the junction object and both reference IDs for
throughrelationships. - Computes a deterministic SHA-256 definition revision of that manifest.
import { compile } from 'relate/compiler';
import { graph } from './graph.js';
const { manifest, definitionRevision } = compile(graph);
console.log(definitionRevision); // 'sha256:…'Stores pin a graph ID to one definition revision. The Postgres store refuses to serve a graph whose revision differs from the one installed for that graph ID. Migrating between revisions is not yet implemented.
Integer fields
Use native(z.int32(), { id: 'invoice.quantity' }) for a signed 32-bit number,
or native(z.int64(), { id: 'invoice.total-minor' }) for a signed 64-bit value.
The same schemas work in sources, action payloads and claims. Optional and
nullable wrappers are supported; additional integer refinements are not.
Ordinary int64 values use decimal strings in reads, writes and filters:
{ totalMinor: '9007199254740993' } and
{ where: { totalMinor: { gt: '9007199254740992' } } }. Comparisons are numeric
and exact. Pass small values as strings too, such as '2'; JavaScript bigint
and number inputs, leading zeros, '-0' and out-of-range values are rejected.
Use BigInt(value) for local arithmetic. int32 values stay JSON numbers.
SQLite source bindings infer this encoding from z.int64() and preserve the
full INTEGER value. Dataset correlations require a matching logical type:
int32 keys match int32 columns and int64 keys match int64 columns.