> ## 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.

# Tables

> Declare tables, series and timelines with their keys, labels, unique field sets and indexes.

A table is declared with its fields and options, and placed in the app tree.
Its path in the tree is its name: the table `orders` in the module mounted at
`shop` is `shop.orders`.

```ts bijection/shop.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, t, table } from "@bijectionhq/bijection";

export const finance = label();

export const customers = table(
  { email: t.string, name: t.string },
  { unique: [["email"]] },
);

export const orders = table(
  {
    number: t.string,
    customer: t.key(customers),
    state: t.one("placed", "paid", "shipped"),
    total: t.decimal,
    margin: finance.seal(t.decimal),
    placed: t.instant,
  },
  { unique: [["number"]], index: [["customer", "placed"], ["state", "placed"]] },
);
```

## Options

| Option | Meaning |
| - | - |
| `key` | The fields that identify a fact. Absent, the host mints the key. |
| `label` | The label of the table's facts: a label, a label family, or `family.and(label)`. Absent, facts are public. |
| `unique` | Field sets unique within one Place. Use `{ fields, scope, release }` for a family-stem claim. A point such as `customers({ email })` needs a single namespace and an admitted row lookup. |
| `index` | The field orders that serve selections (plain tuples or `{ fields, across, release }`). Unnamed and [matched by structure](https://docs.bijection.com/database/indexes.md). `release` can keep a [protected table](https://docs.bijection.com/database/protected-tables.md) index clear and in order through a public release. Ordered values of erasable and lifetime facts stay sealed. |
| `across` | Declared cover targets (`family.all`, `family`, or a fixed label) serving wide reads across every path, total and change feed of the table. |
| `changesAcross` | Declared cover targets specifically for `.changes` wide reads. |
| `history` | How long superseded versions, and their changes, stay readable: `{ days: 365 }`. |
| `lifetime` | How long after it is written a fact is erased: `{ days: 30 }`. |
| `erasable` | Each fact is its own erasure unit, so `ctx.erase` can take it. |
| `writers` | Restricts which mutations or subtrees may write to the table (`writers: () => [landing]`). |
| `private` | Keeps reads and writes inside the subtree that places the table (`private: true`). |
| `presence`, `total`, `machine`, `pin`, `mark` | [Table capabilities](https://docs.bijection.com/database/capabilities.md). |

Durations are `Temporal.Duration` values or duration literals such as
`{ days: 30 }`. See [History and lifetime](https://docs.bijection.com/database/history-and-lifetime.md).

## Keys

Without `key`, the host mints each fact's key. `ctx.insert(table, fact)` returns
it, and a read fact carries it in its `id` field. Store it in another fact with
`t.key(table)`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const customer = await ctx.insert(customers, { email, name });
await ctx.insert(orders, { number: orderNumber, customer, state: "placed", total, margin, placed: ctx.frame.now.entry });
const fact = await ctx.get(customers(customer)); // { id, email, name } | null
```

With `key`, the named fields identify the fact. A one-field key is passed
alone, and a longer key as an object. The fact a write supplies leaves the key
fields out, because the point already holds them.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const stock = table(
  { warehouse: t.string, sku: t.string, onHand: t.number },
  { key: ["warehouse", "sku"] },
);
export const prices = table({ sku: t.string, amount: t.decimal }, { key: ["sku"] });

await ctx.put(stock({ warehouse: "lyon", sku }), { onHand: 12 });
await ctx.insert(prices(sku), { amount });
```

## Labels

A table's `label` is the audience of its facts. A frame reads a labelled fact
only when its roles clear the label, and a function writes into it only when
its `under` flows to the label. A field declared `label.seal(type)` is sealed
above the fact's label: a read returns it as a `Sealed<V>`, and `ctx.open`
shows the value within the frame's clearance. A label family puts each fact in
the frame's member: see [Family tables](https://docs.bijection.com/database/family-tables.md). Label rules
are in [Read rules](https://docs.bijection.com/access/labels.md) and [Write rules](https://docs.bijection.com/access/labels.md).

A labelled, erasable or expiring table is
[protected](https://docs.bijection.com/database/protected-tables.md): its indexes keep tokens of their
fields at the store, so a selection that does not fix every field of an index
is read with `ctx.list(selection.atMost(n))`.

## Constraints are reads

`unique`, a capacity, a `pin` quota and a `t.shared` field are constraints
checked where the write lands. An erasure owner reference
(`erasable: { subject: "<field>" }`) is also a constraint. A write of an owned
image checks it at the owner's fixed place, even if the image lands at
another place. Each check must read at or below the function's `under`,
including in a blind `insert`, `put` or `retract`. A table's own `lifetime`
starts at the write's commit. A referenced owner's lifetime bounds the
commit of an owned image.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const invoices = table({ number: t.string }, { label: finance, unique: [["number"]] });

// Refused: ConstraintAboveWriter. The insert would read the unique path at finance.
export const file = mutation({ under: label.public, args: { number: t.string } }, (ctx, { number }) =>
  ctx.insert(invoices, { number }),
);
```

`bijection check` reports such a write at its call site, and the host refuses
it with `ConstraintAboveWriter`. Use a function whose `under` clears the
place where the constraint is checked. An erased owner refuses
`Erased`/`OwnerClosed`. A past-due owner refuses `Expired`/`OwnerExpired`,
including before the lifetime sweep records its closure. Deploy
also refuses a constraint on a table the host itself writes across labels,
such as a marks table.

Here the post and comment both sit at `finance`. The mutation runs under
`finance` so it can check whether the post's erasure unit is still open.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const posts = table({ title: t.string }, { label: finance, erasable: true });
export const comments = table(
  { post: t.key(posts), body: t.string },
  { label: finance, erasable: { subject: "post" } },
);

export const comment = mutation(
  { under: finance, args: { post: t.key(posts), body: t.string } },
  (ctx, { post, body }) => ctx.insert(comments, { post, body }),
);
```

## Declared covers (`across`)

A fact lives once, at its own label's partition. When a wide frame reads across
a family stem (`under: tenant.all`) or a disjunctive share
(`label.principals`), declare `across` on the table or on the specific index,
search field, vector field, total or `.changes` feed it reads:

* **Table-level `across`** covers every path (including by-id points), totals
  and `.changes`: `across: tenant.all` serves `under: tenant.all`;
  `across: label.principals` serves each member of a disjunctive share at its
  own place.
* **Path-level `across`** covers only that path (`index: [{ fields: ["state", "placed"], across: tenant.all }]`,
  `t.text({ across: tenant.all })`, `t.vector(1536, { across: tenant.all })`,
  `total: [{ group: ["state"], across: tenant.all }]`, or `changesAcross`). On
  a strict update, only changed covered values write to the cover.
* **`bijection.lock`** prints each member-placed table's witness count and
  declared covers per fact (for example, `orders: 1 cover (tenant.all)`).
* **Keyed and by-id points.** A minted id such as `orders(id)` identifies one
  fact across the admitted roots. A point by a Place-local key such as
  `users.of(member)({ email })` needs one Place. A selection under the family
  stem can return every matching email through a declared read cover. To
  serve a shared handle point, declare a family-stem unique scope and a
  separate read cover for the handle index.
  [Shared claims](https://docs.bijection.com/database/protected-tables.md#share-a-unique-claim-release)

## Series and timelines

`series` and `timeline` declare tables with valid time. Both require `key`.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { series, t, timeline } from "@bijectionhq/bijection";

export const readings = series({ meter: t.string, kwh: t.decimal }, { key: ["meter"] });
export const tariffs = timeline({ sku: t.string, amount: t.decimal }, { key: ["sku"] });
```

See [Series and timelines](https://docs.bijection.com/database/series-and-timelines.md).

## Acceptance time

`t.accepted()` is a `Temporal.Instant` the store fills with the commit's own
time when it accepts the write. A write omits it, a table declares at most
one, and it is never a key, sealed or in a `unique` set (the store fills it
after every unique claim is planned, so nothing could hold it unique). An
index on it sorts every later
commit's facts after every fact any frame has seen, so a full page read oldest
first never conflicts with later arrivals
([Reading a queue](https://docs.bijection.com/database/transactions-and-conflicts.md#reading-a-queue-that-others-keep-filling)).

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const events = table({ body: t.string, at: t.accepted() });
```

## Fact types

`FactOf<typeof orders>` is a read fact, and `KeyOf<typeof orders>` its key.
As value types, `t.fact(orders)` and `t.key(orders)` declare a function's
arguments or return value. `t.key(() => orders)` names a table declared later
in the module, and `t.key.self` the key of the table the field belongs to.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const parts = table({ name: t.string, parent: t.maybe(t.key.self) });
```

## Writers and synced tables

Synced tables (from connector apps and [`@bijectionhq/library-replicas`](https://docs.bijection.com/integrations/replica))
are ordinary keyed tables declared with `writers: () => [landing]` and exposed
to callers through `table.readOnly(...)`. `writers` compiles into a host write
guard on `act.write(table)` that permits only the named mutations or subtrees
to write from application code, while `table.readOnly(...)` rejects writes at
compile time. Direct operator writes to these tables refuse `Forbidden`. See [Writers](https://docs.bijection.com/database/capabilities.md#writers).

## Where to declare tables

Declare a table in the module that owns its functions, and place the module
in the app tree. A library that owns tables is a function returning a subtree
with its tables and functions; each call makes a fresh set at the path where
the installer places it. See [Mountable apps](https://docs.bijection.com/mountable-apps).


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