> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Typed relations

> Compose warehouse and dataset relations with @bijectionhq/library-relations; Bijection derives keys, types and lineage and renders each dialect's SQL.

`@bijectionhq/library-relations` is the typed relation builder. It is the
one query syntax Bijection analyses. Virtual tables, pipeline outputs and
query-language connectors all take a `Relation<Row>`, and `bijection check`
compiles it through the semantics guest. The guest derives the relation's
key, column types, lineage and change class, and renders the statement in
the receiver's own dialect. You never write a digest, a key proof or a
column list twice.

A source relation handle is already a relation: there is no entry word.
Handles come from `warehouse.relation(locator, { … })` in
[`@bijectionhq/app-sql`](https://docs.bijection.com/sql/application-api), from
`dataset(name, { fields, key })` in
[`@bijectionhq/library-pipelines`](https://docs.bijection.com/transforms/pipelines), and from an S3
connector's relation. Every method returns another `Relation`.

```ts bijection/relations.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, secret, t } from "@bijectionhq/bijection";
import { warehouse } from "@bijectionhq/app-sql";
import { at, union } from "@bijectionhq/library-relations";

export const credential = secret();
export const analytics = warehouse({
  protocol: "sqlSnowflake",
  endpoint: "https://acme.snowflakecomputing.com",
  credential,
  label: label.public,
  skew: { seconds: 5 },
  requests: { retain: { days: 365 }, message: "Configured request-log retention for this receiver." },
  isolation: "none",
});

const orderFields = { orderId: t.string, customerId: t.string, amount: t.int, placed: t.instant };
const orders = analytics.relation("SALES.PUBLIC.ORDERS", { key: ["orderId"], fields: orderFields });
const webOrders = analytics.relation("SALES.PUBLIC.WEB_ORDERS", { key: ["orderId"], fields: orderFields });
const storeOrders = analytics.relation("SALES.PUBLIC.STORE_ORDERS", { key: ["orderId"], fields: orderFields });
const customers = analytics.relation("SALES.PUBLIC.CUSTOMERS", {
  key: ["id"],
  fields: { id: t.string, region: t.string },
});

export const recent = orders
  .where((o) => o.placed.greaterOrEqual(at.subtract({ days: 30 })))
  .pick((o) => ({ orderId: o.orderId, customerId: o.customerId, amount: o.amount }));

export const withRegion = recent.join(customers, (o, c) => o.customerId.equals(c.id));
export const withMaybe = recent.join(customers, (o, c) => o.customerId.equals(c.id), { maybe: true });
export const buyers = customers.where((c) => orders.has((o) => o.customerId.equals(c.id)));
export const idle = customers.where((c) => orders.has((o) => o.customerId.equals(c.id)).not());

export const perCustomer = withRegion.group(["customerId"]).pick((g) => ({
  orders: g.count(),
  revenue: g.amount.sum(),
  largest: g.amount.maximum(),
  regions: g.region.count({ distinct: true }),
}));
export const overall = recent.group([]).pick((g) => ({ orders: g.count() }));
export const latest = orders.group(["customerId"]).by("placed").descending().first(1);
export const channels = union({ web: webOrders, store: storeOrders });
```

## Operators

| Operator | Spelling |
| - | - |
| Filter | `.where((row) => predicate)` |
| Projection and computed fields | `.pick((row) => ({ … }))` |
| Inner join, within one receiver | `a.join(b, (x, y) => predicate)`. The row is `{ ...a, ...b }`. A field name both sides share is a type error and refuses `ColumnUnresolved`: rename it with `.pick` first. |
| Left join | `a.join(b, on, { maybe: true })`. b's fields become `t.maybe`. |
| Semi join | `a.where((x) => b.has((y) => predicate))` |
| Anti join | `a.where((x) => b.has(…).not())`. The negation's spelling is still open. |
| Aggregate | `.group(keys).pick((g) => …)`: `g.count()`, `g.<field>.sum()`, `.minimum()`, `.maximum()`, `.count({ distinct: true })`. Key fields read as values. Other fields expose only aggregate methods. |
| One-row aggregate | `.group([]).pick(…)`: one row, key `()` |
| Per-group rank | `.group(keys).by(field).descending().first(n)`. `first(1)` is keyed by the group keys. |
| Distinct | `.group(fields)`: there is no `.distinct` |
| Tagged union | `union({ name: relation, … })`: adds a `kind` field holding the member name, with key `(kind, …member key)`. Members have identical row types. |

Predicates and values use the guard builder's words: `equals`, `notEquals`,
`lessThan`, `lessOrEqual`, `greaterThan`, `greaterOrEqual`, `oneOf`,
`isNull`, `isNotNull`, `and`, `or`, `not`, `add`, `subtract` and `multiply`.
An instant takes an exact span: `at.subtract({ days: 30 })`. The library also
exports:

* `at`, the clock: the source instant, `now − skew` on an undated read and
  the cut on a dated one. It is never part of an effective key. `at`, `from`
  and `to` are reserved bind names. A clock function in SQL text refuses
  `FunctionRefused`.
* `arg(name, t.x)`, a typed bind. A pipeline's `args` give its value.
* `constant(t.x, value)`, a typed literal sent as a bind.
* `coalesce(value, …fallbacks)` and `when(condition, value).when(…).otherwise(…)`.
* `builtin({ dialect, name, returns })`, a deterministic built-in of one
  dialect that its [function catalog](https://docs.bijection.com/reference/sql) classifies. A relation
  that calls one is pinned to that dialect, and lowering for another refuses
  `DialectMissing`.

Reusable logic is a TypeScript function over builder expressions. It is
inlined into the relation. There are no warehouse UDF handles, and
Bijection never installs a function in a warehouse.

## What check derives

* **Key.** The key is proved from the source keys, never accepted on
  assertion. With exactly one minimal key, `key` may be omitted. With
  several, `key` must name one (`KeyAmbiguous`). A written key is a pin: it
  must equal the proved key, and an edit that changes the proof refuses
  `KeyUnproved`.
* **Types.** The builder's TypeScript row type must equal the guest's
  inference, or check refuses `TypeMismatch`.
* **Lowering.** Each dialect lowers the relation exactly, pinning casts,
  null-safe equality and null ordering. A construct a dialect cannot lower
  exactly refuses `DialectMissing`; there is no lowest common denominator.
  Retargeting means changing the receiver.
* **Read set and lineage.** The read set is the source handles the relation
  reaches. A pipeline step's change class (`linear`, `group`, `bilinear`,
  `keyed(…)` or `opaque`) comes from the same derivation.

The rendered statements are committed under `bijection.statements/` beside
the lock (see [`bijection.lock`](https://docs.bijection.com/development/cli/lock#committed-statements)).

## Native text

For what a relation cannot say, write native text in the receiver's
dialect: ``receiver.sql({ key, fields })`…` ``. A pipeline run target also
takes `sql(dialect).file(path, { inputs, args, key, fields })`; the file
form on a warehouse receiver is not implemented yet. Native text is pinned to
its dialect and never retargeted. Its key and fields are checked on every
answer. See [native text](https://docs.bijection.com/sql/application-api.md#native-text) for what check
admits.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.