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

# Changing tables

> Declare column renames and casts in your app, or evolve tables in steps using application mutations.

Every fact always matches its table's declaration. Deploy keeps that true:
it refuses a table change that existing facts would violate, with
`DeclarationBreaksFacts`. The refusal names each change and how to make it.

Use [column migrations](#declare-a-column-rename-or-cast) for supported
renames and casts. For other changes, evolve the table in steps with
application mutations. Retire a non-empty table with
[`drop("<table>")`](#remove-a-table).

## What deploy accepts

Deploy first compares the installed declaration with the new one. A change
the types alone prove safe is accepted without reading any fact:

| Change | Why it is safe |
| - | - |
| A new table | It has no facts |
| A new field that accepts `null` (`t.maybe(x)`) | Absence is `null`, so existing facts read the field as `null` |
| A widened type, such as `t.string` to `t.maybe(t.string)`, or `t.one("a")` to `t.one("a", "b")` | Every value the old type accepts, the new one accepts too |
| A new index, or a removed one | An index orders facts and holds no data of its own |

Without a matching migration, any other change is accepted only if a single fact about the table's
current facts holds. The current facts are the table's facts now (every
valid-time slice, for a series or timeline) and the facts each open branch
has written but not yet landed:

| Change | Accepted only if |
| - | - |
| A new field that refuses `null` | The table holds no fact |
| A removed field that accepts `null` | No fact holds a value of the field |
| A removed field that refuses `null` | The table holds no fact: declare it `t.maybe(…)` first |
| A narrowed or changed type that still accepts `null`, such as `t.maybe(t.string)` to `t.maybe(t.int)` | No fact holds a value of the field |
| Any other narrowed or changed type, such as `t.maybe(t.string)` to `t.string`, or `t.string` to `t.int` | The table holds no fact |
| A changed `key` | The table holds no fact |
| A changed `label` | The table holds no fact |
| A removed table (without `drop`) | The table holds no fact |
| A removed table declared in `migrations: [{ drop: "<table>" }]` | Always accepted: retires the table and its facts |

A field that refuses `null` holds a value in every fact, so only an empty
table proves it empty.

Without a cast, a narrowed type is refused while the field holds values,
even if every value would pass the new type.

Deploy decides these facts from counts. The store keeps two
counts exact at every write, at every place the table's facts live: how
many current facts the table holds, and how many of them hold a value of
each field that accepts `null`. A fact of a series or timeline counts while
any of its valid-time slices holds the value. Deploy reads one count per
place, so the check costs the same however many facts the table holds. An
open branch counts every fact it reads, including facts it
inherited when it was created: while it still reads a value its parent has
since removed, deploy refuses the change until it lands or is dropped.

A field whose values the table keeps sealed (a protected or erasable table,
or a shared-unit field) has no such count, because a count kept per fact
would reveal whether each sealed value is `null`. Deploy accepts a change
to such a field only once the table is empty, and otherwise refuses it with
`DeclarationConditionSealed`.

Use `t.default(type, literal)` to supply a value to earlier facts when a
deploy adds a field. New writes supply the field as part of the fact.

## Check before you deploy

`bijection check` records each table's declared shape in `bijection.lock`,
as a `table <path> <shape>` line, so a review sees the table diff. It
compares the derived shapes with the committed lock and lists every table
change. For each change, it reports either that the change is safe, or the
condition deploy needs before it accepts the change. A matching migration
is named in the same diff.

```text theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
Table changes against the committed bijection.lock:
  fieldAdded orders.note: safe
  fieldRemoved orders.legacyCode: DeclarationBreaksFacts unless no fact holds a value of legacyCode; deploy refuses it otherwise
```

`bijection check --write-lock` also records each declared migration. Commit
the reviewed lock with the app changes. Deploy checks the target's facts.

## Declare a column rename or cast

Change the table declaration and list the instructions beside the root app
tree. In this example, the installed `customers` table had `fullName`
and stored `balance` as text.

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

const customers = table({ name: t.string, balance: t.number });

export default app({ customers }, {
  migrations: [
    { rename: { table: customers, from: "fullName", to: "name" } },
    { cast: { table: customers, field: "balance", to: "number" } },
  ],
});
```

A rename takes the table declaration and top-level column names. It
removes the old column and copies its values into the newly declared column.
A cast takes the table declaration and converts a column whose successor type no longer accepts every value
admitted by the old one. The target is `"string"`, `"number"`, `"int"`, or
`"boolean"`. Casts preserve absent fields and values already of the target
type. A string cast represents null as `"null"`. Other casts preserve null.
Conversions include finite numeric text to numbers, whole
numbers in range to 64-bit integers, and the exact text `true` or `false` to booleans.

Rename, cast, rekey, and relabel apply to app tables. The deploy validates
current facts before activation and publishes the new declaration with the
carried facts. Carried facts keep their IDs, erasure units, and holds.
The column rewrite budget is 4,096 facts.

Declare a changed key as `{ rekey: { table: customers, key: ["name"] } }`.
A collision in the new key among current facts refuses with
`DeclarationBreaksRows`. A rekey carries history when the key fields
are renamed in the same order. Declare `endsHistory` for any other rekey.

A downward relabel requires `{ relabel: { table: customers, release } }`.
The cutover records the release in `sys.disclosures` and moves current facts.
The deployer needs live clearance for every declared place its checks inspect.

Keep the same instructions on later deploys if the successor schema still
matches them. The installed program records which instructions it already
applied.

### Read across a deploy

A table keeps its identity as its layout changes. A new table that reuses
a dropped name starts a fresh identity.

A query at an earlier version reads the relation at that cut and applies
the declared migration chain. A cast that cannot convert every old value
requires an `otherwise` literal. A total cast must omit it. A cast cannot
write a field used by a key or label selector. A field in a `unique` index can
be cast, `otherwise` included: the deploy rebuilds the index over current and
retained facts and refuses with `Exists` (`UniqueTaken`) if two facts convert
to the same value.

Refinements such as bounds, lengths, patterns,
finiteness, and File media types and size limits bind writes from the deploy on.
Earlier values carry unchanged. A field whose static type narrows needs a cast.

A cast can declare `{ cast: { table: orders, field: "quantity", to: "int", otherwise: 0n } }`.
The cast keeps a value the successor type admits, tries the optional conversion,
then uses the literal if the conversion fails or its result is refused. A
completed cast carries historical id points and id-order ranges. A partial cast
needs `endsHistory`. Renames, widening casts, nullable or defaulted additions,
field projections, and compatible index edits can also carry history.

Declare an ending with `{ endsHistory: customers }`. Check and deploy refuse
an undeclared end with `Invalid` and reason `MigrationEndsHistory`.
The lock and `bijection deploy --trial` show which boundaries carry or end
history. A read across an ending boundary refuses `Expired` with reason
`SchemaChanged`. Use `ctx.call(query, args, { in: version, program: version })`
to run the query installed at the cut while its history is retained.

Historical reads need clearance for the original fact's label and the
table's current label. A lens can serve id points, id-order ranges, and
keyed selections with an order the generation chain carries. An aggregate
reads from the generation that held its definition at the selected version.
A request that predates its definition refuses with `SchemaChanged`.

### Change a deferred function contract

A deferred invocation records its function path and calling-contract digest.
The active program resolves the recorded call through the accepted chain.
Check and deploy compare declarations for continuation handlers, target
performers and answer handlers, and internal runs.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
migrations: [
  { rename: { function: "orders.received", from: "order", to: "orderId" } },
  { move: { function: "orders.legacyAck", to: "orders.ack" } },
  { retire: { function: "orders.obsoleteAck", message: "This receiver has closed" } },
]
```

An undeclared contract change refuses `Invalid` with reason
`ContractNeedsMigration`. A retired function or an argument the chain
cannot carry leaves its obligation stuck with `ProgramContractChanged`. A
declared retirement withdraws it with the declared message the next time
it is visited. A compatible handler already at head still accepts it.
A compatible deploy re-arms it at its label on its next visit and keeps its
attempts. Manual `ctx.retry` re-arms it and resets its attempts, and
`ctx.withdraw` closes it. A task whose run function was retired ends
`Withdrawn` (`FunctionRetired`) with the declared message, whether or not it
was claimed.

## Add, migrate, then remove

Changes that need an application backfill follow three steps.

1. Add the new shape, in a form that is safe over the facts that exist.
2. Migrate the facts in app code.
3. Remove the old shape once no fact needs it.

Each step is its own deploy.

### Add a field

Declare the field `t.maybe(x)`. Existing facts read it as `null`, and new
writes set it.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const orders = table({
  number: t.string,
  total: t.decimal,
  currency: t.maybe(t.string), // new: existing facts read null
});
```

A field that refuses `null` can be added only to an empty table. To get a
required field over existing facts, declare a new table. The section
[change a key or a label](#change-a-key-or-a-label) shows how.

### Remove a field

If the field refuses `null`, first declare it `t.maybe(…)`, which is always
safe. Then deploy a mutation that writes `null` to the field in every fact,
and run it until no fact holds a value. Then remove the field.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
// Step 2: walk the table one page at a time. Call it until it returns null.
export const clearLegacyCode = mutation(
  { args: { cursor: t.cursor }, returns: t.cursor },
  async (ctx, { cursor }) => {
    const page = await ctx.page(orders, { size: 100, cursor });
    for (const fact of page.facts) {
      if (fact.legacyCode !== null) await ctx.patch(orders(fact.id), { legacyCode: null });
    }
    return page.next;
  },
);
```

Your writes must also stop setting the field before the backfill starts.
You can also react to `orders.changes` to clear the field as facts are
written.

### Change or narrow a field's type, or rename a field

When a column change needs an application backfill, move the data to a
new field in stages.

1. Add a new field with the new type, as `t.maybe(…)`.
2. Backfill the new field from the old one in app code, and write both
   fields from now on.
3. Move your readers to the new field, and stop writing the old one.
4. Write `null` to the old field in every fact, after declaring it
   `t.maybe(…)` if it refuses `null`.
5. Remove the old field.

### Change a key or a label

Keep the existing key on a populated table. A label change that
tightens access carries facts into the successor layout with their custody
units intact. Historical reads still use the original relation and its labels.

### Remove a table

Either delete the table's facts first and remove its declaration, or retire a
non-empty table explicitly with `drop("<table>")` from `@bijectionhq/bijection`
in `app(tree, { migrations })`:

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

export default app(remainingModules, {
  migrations: [{ drop: "legacy.notes" }],
});
```

* Removing a table that still holds facts without declaring `drop` refuses with
  `DeclarationBreaksFacts`.
* Listing `drop` for a table the app tree still declares refuses with
  `DropDeclaredTable`.
* Listing `drop` for a table already gone is a no-op, so a program may keep
  its drops across deploys.

When a release with `drop` activates, the table leaves the catalog and writes
close immediately. Its facts stay readable inside the table's `history` window
(30 days by default), after which the collector reclaims every fact except
those kept by a standing [legal hold](https://docs.bijection.com/database/legal-holds.md). A held fact
outlives the dropped table until its hold is lifted, and a drop never refuses
because of a hold. A later table declared with the same name gets a fresh
address.

In the console, **Delete table** on a declared table shows the exact schema
edit and deploy command, and offers **Clear facts** (paged operator deletes)
to empty a table without a deploy. Retired tables still inside their history
window appear in the retired-tables list, where an operator with `Deploy`
can **purge** a table to end its retention immediately (refused with
`PurgePinned` while a live pin's version is newer than the retirement; legal
holds are preserved silently).


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