Relations
Typed links between subjects (blocks, parent, relates or your own kinds) with inverse names, cycle checks, one-target kinds, ancestors, descendants, rollups and undo tokens.
relations links two records of any subject type: a task that blocks
another, an issue under an epic, a person who reports to a manager. Each kind
of link is declared once, with its inverse name, whether it may form a
cycle, and whether a record can have more than one target. Links carry a
small data object, such as a Gantt dependency's type and lag.
better-supabase add relationsimport {
createRelations,
toGanttTasks,
toTreeItems,
} from "better-supabase/blocks/relations";Kinds
Without kinds, the module declares four:
blocks: {
relations: {
options: {
kinds: {
blocks: { inverse: "blocked_by", acyclic: true },
parent: { inverse: "children", cardinality: "one", acyclic: true },
relates: { symmetric: true },
created_from: { inverse: "converted_to", cardinality: "one", acyclic: true },
},
},
},
},| Option | What it does |
|---|---|
inverse | The kind's name from the target's side. link accepts it and stores the link from the other end |
acyclic | Refuses a link whose target already reaches its source through links of the same kind |
cardinality | one: a source has at most one target; a new link replaces the old one |
symmetric | The link reads the same from both ends and is stored once |
types | { source, target }: the subject types each end accepts. A left-out end accepts any type |
types names the ends in the stored direction, so link checks them after
an inverse name has swapped the ends. A symmetric kind accepts either order.
A link whose ends don't match fails with RELATION_TYPE_NOT_ALLOWED:
kinds: {
mitigated_by: {
inverse: "mitigates",
types: { source: ["risk"], target: ["control", "task"] },
},
},A link reads "source kind target": link("parent", issue, epic) makes the
epic the issue's parent, and link("blocks", design, build) means design
blocks build. The cycle check runs a recursive query under an advisory lock
per organization and kind, so two concurrent links can't close a cycle
between them.
The subjects come from config.recordTypes, or from on with the
same shape. Both ends must exist in the organization and be readable by the
caller, and linking needs relations.manage. A subject with cascade: true
deletes its links when its row is deleted.
Kinds from other blocks
A block that needs its own kind of link contributes it to relations, the
same way blocks contribute number sequences to numbering. Installing both
adds the kind next to yours (or next to the four defaults when you don't set
kinds), with the subject types the block names after its entity names.
Declare a kind with the same name in kinds to replace the contributed one;
your entry wins as a whole, including its types and any check the block
makes on the link's data (link refuses data the check rejects with
RELATION_DATA_INVALID). Contacts
contributes represents this way. Two blocks that contribute
the same kind to one relations instance fail at render time; point one
instance's uses.relations at another relations instance.
Link and unlink
Server code calls the relations instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useRelations } = defineDataHooks(
"relations",
(db: AppDb) => db.relations,
);const result = await db.relations
.link(
{ type: "task", id: designId },
{ type: "task", id: buildId },
{ kind: "blocks", data: { type: "FS", lag: 2 } },
)
.orThrow();
await db.relations.unlink(
{ type: "task", id: buildId },
{ type: "task", id: designId },
{ kind: "blocked_by" },
);"use client";
import { useRelations } from "@/lib/supabase/hooks";
const rows = useRelations({ limit: 50 });The ends are RecordRefs, { type, id }, and every call acts in the
block's tenant, an organization id or a function that returns the current
one. createBlocks and createBlockClient pass the request's tenant; a call
without one fails with invalid_request and the hint TENANT_REQUIRED.
link resolves to the stored link, created: false when it already existed
(its data is updated when you pass data), and replaced with the old
target when a one-target kind moved. Both methods return an undo token
that reverses the change, including putting a replaced parent back. See
Undo tokens.
| Hint | When |
|---|---|
RELATION_FORBIDDEN | The caller lacks relations.manage |
RELATION_SUBJECT_FORBIDDEN | An end is missing, in another organization or unreadable |
RELATION_KIND_UNKNOWN | The kind is not declared |
RELATION_TYPE_NOT_ALLOWED | An end's subject type is not in the kind's types |
RELATION_DATA_INVALID | A contributed kind's check rejects the link's data |
RELATION_SELF | Both ends are the same record |
RELATION_CYCLE | The link would close a cycle of an acyclic kind |
RELATION_INVALID | data is not an object |
Read links
| Method | Returns |
|---|---|
of(subject, kind?) | A record's links in both directions, each named from its side (blocked_by) |
edges(kind) | Every link of a kind, up to 10,000, for a chart or a tree |
ancestors(subject, kind) | The records above a subject (its parent's parents), with their depth |
descendants(subject, kind) | The records below it |
rollup(subject, input) | count, sum, avg, min or max of a column over the descendants of a type |
Reads run as the caller and need relations.read, which the default member
role has. rollup also reads the subject table as the caller, so its
policies decide which rows count:
const points = await relations
.rollup(
{ type: "issue", id: epicId },
{ kind: "parent", of: "issue", agg: "sum", column: "estimate" },
)
.orThrow();The SQL functions are link, unlink, relations_of, relations_by_kind,
ancestors, descendants, converted_into and relation_rollup. Walks
stop at 100 levels.
Conversions
When one record turns into another (a deal into a quote, a quote into an
order and an invoice, an application into an employee), link the new record
to its origin with created_from. A record has one origin, and the link
can't close a cycle. Check convertedInto before you create the new record,
so converting the same deal twice returns the first quote:
const existing = await relations
.convertedInto({ type: "deal", id: dealId }, "quote")
.orThrow();
const quoteId = existing ?? (await createQuoteFrom(dealId));
if (existing === undefined) {
await relations
.link(
{ type: "quote", id: quoteId },
{ type: "deal", id: dealId },
{ kind: "created_from" },
)
.orThrow();
}
const { origins, conversions } = await relations
.lineage({ type: "quote", id: quoteId })
.orThrow();
// origins: the deal; conversions: the orders and invoices made from the quotelineage reads ancestors and descendants of created_from, nearest
first, for a breadcrumb such as deal, quote, order, invoice. An app that sets
its own kinds adds created_from to use them.
Your own fields
Columns you add to relations with alter table in your own schema files are fields of the block (details). link writes them from fields,
and link, of and edges return them in fields. Pass a Standard Schema as fields
to type them: writes are validated before they reach the database (a
validation error), and reads are parsed. hooks refuses, rewrites or
observes any method; see extending blocks.
alter table "better_supabase"."relations" add column "weight" integer;const client = createRelations({
transport,
fields: v.object({ weight: v.optional(v.number()) }),
});
await client.link(
{ type: "task", id: a },
{ type: "task", id: b },
{ kind: "blocks", fields: { weight: 2 } },
);Events
link and unlink record subject.linked and subject.unlinked with the
kind and both ends, and call the before_relation_link and
after_relation_link hooks.
Over your own tables
Map tables.relations onto an existing table with the same columns, and the
module runs over it. Tables that hold one kind each, such as a sub-issue
table or a reporting-line table, can't stand in for relations yet.
With ReUI
- Gantt:
toGanttTasks(tasks, await relations.edges("blocks"))adds each task'sdependencieswith the type and lag from the link'sdata. - Tree:
toTreeItems(items, await relations.edges("parent"))returns the flat{ [id]: { name, children } }map a tree view takes, for sub-issues or a reporting line. - Data Grid: a "Blocked by" column from
of(task, "blocked_by"), and an undo toast from theundotoken.
The free c-gantt-* and c-tree-* examples show both views. ReUI's Tempo
and Roster templates show sub-issues and reporting trees; Pro blocks are
licensed per user, so copy them from reui.io.
Without the client
db.relations is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const relations = createRelations({ transport, tenant: organizationId });
const result = await relations
.link(
{ type: "task", id: designId },
{ type: "task", id: buildId },
{ kind: "blocks", data: { type: "FS", lag: 2 } },
)
.orThrow();
await relations.unlink(
{ type: "task", id: buildId },
{ type: "task", id: designId },
{ kind: "blocked_by" },
);Walk a tree
walk({ subject, kind, direction }) returns the ancestors for "up" and the descendants for "down".
Last updated on
Saved views
Named list views per user, team or organization, with the filter tree, sort, columns, grouping and density checked against the list definition, personal defaults, duplicates, and useSavedViews for nuqs.
BulkActions actions
Run one action over many rows with a result per row, in one call up to a limit and as a background run on the jobs queue beyond it, as the user who started it.