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

# Declare a SQL virtual table

> Compile bounded warehouse selections and read dated answers in Bijection.

Use `warehouse` and `virtualTable` from `@bijectionhq/app-sql`. Place the
warehouse, its credential and the virtual table in the app tree. The
warehouse declares the receiving label and the provider's reviewed finite
request-log policy with `requests: { retain, message }`.
Its required `isolation` statement describes what confines the
credential, such as a row access policy, or the reviewed `"none"` when every
answer lands at the one receiving label. A warehouse whose answers land at
several members needs a statement. The lock prints both choices.
`analytics.relation(...)` declares a source relation's world facts once: its
key, typed fields, physical columns, subject, deletion signal and travel
window. A source relation lands nothing. The virtual table reads it and
declares landing policy only: the answer label, the selections the
warehouse can serve, freshness, eviction and lifetime. The relation selects
its receiver. Set `via` to use a federating receiver with the required
`forwards`. The key, column types, contributors and deletion coverage are
derived from the relation. A written
`key` is a pin that must equal the relation's key.

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

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",
});

export const orderRows = analytics.relation("SALES.PUBLIC.ORDERS", {
  key: ["orderId"],
  fields: { orderId: t.string, region: t.string, amount: t.decimal, placed: t.instant },
  columns: { orderId: "ORDER_ID", region: "REGION", amount: "AMOUNT", placed: "PLACED" },
});

const orders = virtualTable(orderRows, {
  label: label.public,
  pushdown: { where: [["region"]], by: [["placed"]], first: 100, keys: 100 },
  fresh: { minutes: 15 },
  lifetime: { days: 7 },
  evict: { days: 1 },
});

const refreshOrders = mutation({ args: { ids: t.array(t.string) } }, (ctx, { ids }) =>
  ctx.call(orders.refresh, { keys: ids, bindings: null }),
);

export default app({ credential, analytics, orders, refreshOrders });
```

Set the receiver credential with `bijection secret set credential`. Its
sealed JSON contains `token` and the provider's `settings`. For an engine
reached over its own wire, `token` is the password or access token.

| Protocol | Engines | Endpoint | Settings | Travel | `requests` |
| - | - | - | - | - | - |
| `sqlSnowflake` | Snowflake | `https://` origin | `{ kind: "snowflake", warehouse, role }` | `AT (TIMESTAMP => …)` | `{ retain, message }` |
| `sqlBigquery` | BigQuery | `https://bigquery.googleapis.com` | `{ kind: "bigquery", project, location, maxBytesBilled }` | `FOR SYSTEM_TIME AS OF` | `{ retain, message }` |
| `sqlDatabricks` | Databricks SQL | `https://` origin | `{ kind: "databricks", warehouseId }` | `TIMESTAMP AS OF` | `{ retain, message }` |
| `sqlTrino` | Trino | `https://` origin | `{ kind: "trino", user }` | `FOR TIMESTAMP AS OF` | `{ retain, message }` |
| `sqlClickhouse` | ClickHouse, ClickHouse Cloud | `https://` origin, any port (Cloud: `8443`) | `{ kind: "clickhouse", user }` | none | `{ retain, message }` |
| `sqlRedshift` | Redshift, Redshift Serverless | `host:port` (TLS, `5439`) | `{ kind: "redshift", user, database }` | none | `{ retain, message }` |
| `sqlServer` | SQL Server, Azure SQL, Synapse, Fabric | `host:port` (TLS, `1433`) | `{ kind: "sqlServer", database, user? }` | `FOR SYSTEM_TIME AS OF` on temporal tables | `{ retain, message }` |
| `sqlPostgres` | PostgreSQL, AlloyDB, Aurora PostgreSQL, Supabase, Neon | `host:port` (TLS, `5432`) | `{ kind: "postgres", user, database, ca? }` | none | `{ retain, message }` |
| `sqlMysql` | MySQL, Aurora MySQL, PlanetScale | `host:port` (TLS, `3306`) | `{ kind: "mysql", user, database?, ca?, planetscale? }` | none | `{ retain, message }` |
| `sqlOracleNet` | Oracle Database, Autonomous Database | `host:port` (TCPS, `2484`) | `{ kind: "oracle", user, service }` | `AS OF TIMESTAMP` (flashback query) | `{ retain, message }` |
| `sqlMotherduck` | MotherDuck (DuckDB SQL) | `pg.<region>.motherduck.com:5432` | `{ kind: "motherduck", database? }` | none | `{ retain, message }` |
| `sqlHana` | SAP HANA, SAP HANA Cloud | `host:port` (TLS; Cloud `443`, on-premise `3<instance>15`) | `{ kind: "hana", user, database }` | `FOR SYSTEM_TIME AS OF` on system-versioned tables | `{ retain, message }` |
| `sqlDb2` | IBM Db2 (LUW, Db2 on Cloud, z/OS) | `host:port` (TLS, commonly `50001`) | `{ kind: "db2", user, database, queryPackage: { collection, name, token, section } }` | `FOR SYSTEM_TIME AS OF` on system-period temporal tables | `{ retain, message }` |
| `sqlVertica` | Vertica, OpenText Analytics Database | `host:port` (TLS, `5433`) | `{ kind: "vertica", user, database, ca? }` | none | `{ retain, message }` |
| `sqlExasol` | Exasol | `host:port` (TLS WebSocket, `8563`) | `{ kind: "exasol", database }` | none | `{ retain, message }` |
| `sqlNetezza` | IBM Netezza Performance Server | `host:port` (TLS, `5480`) | `{ kind: "netezza", user, database }` | `FOR SYSTEM_TIME AS OF` on temporal tables | `{ retain, message }` |
| `sqlAse` | SAP ASE (Sybase) | `host:port` (TLS, `5000`) | `{ kind: "ase", user, server, database }` | none | `{ retain, message }` |

`sqlServer` signs in with SQL authentication when `settings.user` is set,
and otherwise presents `token` as a Microsoft Entra access token (Fabric
and Synapse serverless). `sqlPostgres` verifies the server against `ca`
(PEM) when you set it, else against the public roots.

`sqlMysql` sets `planetscale: true` for PlanetScale, which signs in with a
native password and selects `database` with `USE`. It verifies the server
against `ca` (PEM) when you set it. `sqlOracleNet` connects to the named
`service`; Oracle names are case-sensitive in a statement, so spell the
relation as the dictionary stores it, usually upper case, and note that
Oracle reads an empty string as null. `sqlMotherduck` presents `token` as
the MotherDuck access token and opens `md:<database>`.

`sqlHana` signs in to the tenant `database` with SCRAM-PBKDF2-SHA256 and
checks that the endpoint serves that tenant. `sqlDb2` prepares each
statement in the dynamic SQL package section `queryPackage` names (for
example `NULLID.SYSSH200`, with its 16-hex-digit consistency token).
`sqlVertica` verifies the server against `ca` (PEM) when you set it.
HANA and Db2 fold unquoted names to upper case, so spell the relation as
the catalog stores it. These three wires carry only text, so the provider
reads each declared column as its exact text form: an instant must sit on
the microsecond grid, and a decimal or integer column that returns a
floating-point spelling refuses with `WarehouseRowMismatch`. HANA and Db2
read text cells up to 256 characters and 1024 bytes; a longer string
refuses with `ResultTooLarge`. HANA and Db2 `TIMESTAMP` columns hold no
zone, so they are read as UTC.

`sqlExasol` presents `token` as an Exasol OpenID access token and checks
that the session opened `database`. `sqlNetezza` signs in as `user` with
`token` as the password and reads inside a read-only transaction.
`sqlAse` signs in as `user` at the ASE server named `server`, with `token`
as the password (at most 30 characters, the TDS 5.0 login field), on a
server and client character set of UTF-8. Exasol and Netezza fold unquoted
names to upper case, so spell relations and columns as the catalog stores
them. Exasol `TIMESTAMP` and Netezza timestamps carry no time zone; they
are read as UTC, and the Netezza observation clock assumes a host in UTC.
Netezza's text wire carries no exact double, so a `t.number` field refuses
on `sqlNetezza`. ASE has no window functions and its `datetime` is not on
the microsecond grid: a `sqlAse` table declares only `keys`, `total` and
`changes` pushdown (a `where`, `by`, `search` or deletion shape refuses with
`PushdownMissing`), no `timeline`, and no
`t.instant` field.

A table that declares `travel` on an engine with no table history refuses
with `TravelMissing`. A `sqlServer` table travels only over a
system-versioned temporal table: the statement reads it `FOR SYSTEM_TIME AS
OF` the source instant. A `sqlOracleNet` table travels through a flashback
query, `AS OF TIMESTAMP` the source instant, so declare a `travel` window no
longer than the database's undo retention.
A `sqlHana` or `sqlDb2` table travels only over a system-versioned
(HANA) or system-period temporal (Db2) table, read `FOR SYSTEM_TIME AS OF`
the source instant; keep the history table at least as long as the
`travel` window. Vertica's historical queries cut a whole statement at an
epoch above the ancient history mark, not a table at an instant, so a
`sqlVertica` table that declares `travel` refuses with `TravelMissing`.
A `sqlNetezza` table travels through Netezza Performance Server 11.1 time
travel: the statement reads a temporal table `FOR SYSTEM_TIME AS OF` the
source instant, so declare a `travel` window no longer than the table's
`DATA_VERSION_RETENTION_TIME`.

Set `requests.retain` to the provider's configured request-log retention and
state that policy in `requests.message`. The SQL connector gateway refuses
warehouse request-erasure declarations with `ReceiverErasureRequired`.

A PostgreSQL `interval` reads into a `t.duration` field when it has no
month part. The other engines have no exact duration column, so a
`t.duration` field there refuses with `SourceShape`. ClickHouse has no
admitted `LEAD` window, so a ClickHouse table declares no `timeline`. Every
ClickHouse statement uses `join_use_nulls=1` so a left join's or a fused
chain's missing row reads null. Write `ifNull` or `coalesce` in native text
to fill defaults. The profile also uses `count_distinct_implementation=uniqExact`
for exact population floors. A statement never carries `SETTINGS`. The
[dialect catalogs](https://docs.bijection.com/reference/sql) list each engine's capabilities and
function classes. Provision the virtual table's `suppressionKey` with an
HMAC-SHA256 key owned by the installation.

Call `orders.lookup` with `{ key }` to read a landed point. The answer
carries its state and observation time. A ready answer can contain null
when the warehouse confirmed absence. Such an answered absence closes
nothing; only the deletion signal, the lifetime or `orders.erase` does. `orders.where({ region }).by("placed")`
is a bound selection for views. `pushdown.first` bounds a page and
`pushdown.keys` bounds the key list. The lock records the digest of each
statement. The warehouse order appends the effective key. An explicit
`.first(n)` uses that order and stays within the declared page bound.

## Name bounded warehouse reads

Declare reusable pages and aggregates in `reads`. A page fixes its equality
filters, per-field order and maximum row count. The compiler appends any
missing key columns in ascending order to break ties. Bind the filters in a
view with `orders.reads.recentForCustomer({ customer: c.crmId })`. The same
route can contribute a field or carry a link. Use `.first(n)` within its
declared maximum to contribute fewer rows.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
reads: {
  recentForCustomer: {
    kind: "page", where: ["customer"],
    order: [["placed", "desc"], ["order", "asc"]], max: 50,
  },
  openByCustomer: {
    kind: "aggregate", where: ["customer"], fixed: { state: "open" },
    measures: { count: "count", amount: { sum: "amount" } },
  },
}
```

Each named page has one reviewed shape per supported source-time variant.
Read bindings take the declared column's value type or a compatible symbolic
field from a view. Use `ReadBind<typeof orderRows, "customer">` to type a
helper shared by a field and a link.
Use `pushdown: { point: true }` to also support direct point lookups. A
named-read-only table needs no `pushdown.first`. Generic pages, timelines
and polled deletions carry their own `pushdown.first` as applicable.

## Read several measures from one query

Declare an aggregate with `where` and `measures`. A measure is `"count"`
or `{ sum: "field" }` over a declared exact numeric field. A `reads` aggregate
can fix equality filters at declaration. Bind the remaining filters with
`orders.reads.openByCustomer({ customer: c.crmId })` in `sources`, then select
its measures as fields.
A fixed-label source binds its declared subject among the filters. An
authorized empty answer has count zero and null sums. All measures from
that aggregate share one landed answer and its observation time. The
source basis also carries the time from the accepted request to landing.
For a nonempty group, a non-nullable column must have a non-null sum. A
nullable column may yield a null sum when every input is null.
Each compiled aggregate uses the receiver's statement bounds and meter
when declared. [Customer example](https://docs.bijection.com/objects/views.md#compose-a-customer).

Declare `pushdown.total` for grouped counts or sums. A population total
declares `minimum: { n, message }` and a `subjects` cap of at least `n`.
The installed statement certifies a bounded list of distinct subjects
from the same source cut as the aggregate. SQL still refuses population
requests and writes.

Publishing population totals with same-place identity custody and population erasure is designed, not implemented.

## Stream changes per member

A member-labelled virtual table can use PostgreSQL logical changes with a
dedicated publication and slot for each member. Give `postgresLogical` the
same label family as the virtual table and install a
`secret({ under: tenants })` credential for each member. On the stream signal,
declare `member` as the source column whose text equals the receiving member's
key. PostgreSQL's replica identity must contain that column and all declared
signal key columns. The stream requests only this key image.

Each PostgreSQL credential names the dedicated database, publication,
schema, and table and includes `member: { tag, column }`. Here `tag` is
the full registered Bijection member tag. Provision the logical slot as
`bj_` plus the first 60 hex digits of the SHA-256 of compact UTF-8 JSON for
`[slot, database, publication, schema, table, incarnation, member.tag, member.column]`.
The credential's `slot` field is the deployment's chosen namespace. The
publication serves one member's relation. Row-level security cannot partition
a shared PostgreSQL replication log.

Each member's first refresh starts its own polling chain. A deletion closes
rows at that member, and a reply containing another member's key is treated
as a gap. Member-scoped stream receivers currently use PostgreSQL logical
decoding. Other SQL change receivers support fixed labels.

## Compose typed relations

A source relation handle is also a [typed relation](https://docs.bijection.com/sql/relations.md).
Compose handles on one receiver with `.where`, `.pick`, `.join`, `.has`,
`.group` and `union`, and pass the result to `virtualTable`:

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

const euOrders = orderRows
  .where((o) => o.region.equals("EU"))
  .pick((o) => ({ orderId: o.orderId, region: o.region, amount: o.amount }));
const eu = virtualTable(euOrders, {
  label: label.public,
  pushdown: { first: 100, keys: 100 },
  fresh: { minutes: 15 },
  evict: { days: 1 },
});
```

`bijection check` compiles the relation through the semantics guest, which
proves its key, infers its column types and renders each shape's statement
in the receiver's dialect. The builder's row type must equal the guest's
(`TypeMismatch`). Such a table closes coarsely: a deletion in any read
relation's signal closes every landed row and total, as for native text. A
relation that aggregates a subject-bearing input away refuses
`TotalNeedsRelease`. The declaration analysis hosts the guest; a composed
relation evaluated without it refuses.

## Native text

Native text in the receiver's dialect is the escape for what a relation
cannot say. It is a tag on the receiver, never a plain string, and it
declares its output contract as the tag's options:

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

const tagged = analytics.sql({ key: ["orderId"], fields: { orderId: t.string, amount: t.decimal } })`
  SELECT o.ORDER_ID AS orderId, o.AMOUNT AS amount
  FROM ${orderRows} AS o
  WHERE o.PLACED >= ${at} - INTERVAL '30 DAYS'`;
const recent = virtualTable(tagged, { label: label.public, pushdown: { first: 100 }, fresh: { minutes: 15 }, evict: { days: 1 } });
```

A splice is a relation handle or `at`, the source instant (`now − skew`, or
the cut on a dated read); any other value refuses. The read set is the
spliced handles. Native text runs only on the receiver it was written for.
Check parses it with the receiver's dialect module and refuses:

| Refusal | When |
| - | - |
| `RelationUndeclared` | A relation reference that is not a spliced handle or a CTE in the statement. |
| `SourceShape` | Output names that differ from the declared fields, a top-level `*`, a ClickHouse table alias spelled `FINAL`, or a handle over a relation whose `columns` renames a field. |
| `ColumnUnresolved` | An unresolved or ambiguous column, or an unqualified column with two or more relations in scope. |
| `TypeMismatch` | A cast, bind or outer-join nullability that contradicts a declared field type. |
| `FunctionRefused` | A relation-reading, nondeterministic, credential-context, clock or external call. Splice `${at}` for the clock. |
| `FunctionUnclassified` | A function the dialect's catalog does not classify, or a qualified name. |
| `TotalNeedsRelease` | Text that combines rows (`GROUP BY`, `HAVING`, `QUALIFY`, `DISTINCT`, a window, a deduplicating set operator, an aggregate, a subquery or a top-n) over a relation that declares a `subject`. Write the aggregate as a typed relation instead. |
| `SubjectUnbound` | A `subject` that is not a top-level passthrough of the one subject-bearing relation's subject field. |

The key and fields are checked on every answer. Native text yields no
per-key lineage, so a deletion in any read relation's signal closes every
landed row and total, and keys re-acquire on demand. The closure's instant
is the table's deletion floor: a dated refresh at or before it refuses
`SourceRetention`, and an answer observed at or before it lands nothing.
Inline typed `args` on a virtual table's native text, and the
`.sql.file(path)` form on a warehouse receiver, are not implemented yet.

## ClickHouse merged reads

A ClickHouse `ReplacingMergeTree` relation can declare merged reads on its
source relation, `merge: { deleted: "<column>" }`. The key spelling `merge`
is provisional. Every reference to the relation, from a typed relation or a
native handle, renders as `(SELECT <columns> FROM <locator> FINAL WHERE <deleted> = 0)`, so the committed statement shows the merge. Never write
`FINAL` yourself. The declaration refuses `DialectMissing` on another
dialect or through a forward, and a relation that is also a deletion signal
refuses: keep deletions in a separate append-only relation. The gateway
admits `FINAL` only on the locators the installed record says Bijection
rendered. A duplicate key that survives the merge still refuses the reply
with `SourceShape`.

## Deletion signals and lifetimes

A relation without a `deletions` signal requires a table `lifetime`.
With a signal on every read relation, each answer and total depends on the
current signal leases. A lease lasts `every + skew`. A final deletion page
can renew it within the poll budget, `every`. When a lease lapses, the kernel
closes its dependent answers and totals. Reads and landings refuse with
`SignalStalled` while a required lease is absent. The erasure bound for a
polled relation is `2 × every + 2 × skew`.

A deletion page applies its closures and moves the cursor in one commit.
A reset closes prior coverage and moves the cursor without renewing. A
positionless head query resets to the source head. A retained-position gap
resumes at the earliest retained boundary. Renewal extends the live
singleton lease, and re-arming after a lapse starts a fresh unit.
Deletion pages never publish answer rows or totals. A signal can also
report declared fields of its relation with
`deletions(relation, { key, every, fields })`.

Additional SQL input deletion signals currently fail placement because
their generated lease names exceed the app-tree segment limit.

A virtual table acquires answers on demand. Set `copy: true` to consent to a
bounded local copy when a view plan calls for one. The view planner derives
standing demand from a reviewed `serve` population and checks it against the
receiver's budget. [Serve a view](https://docs.bijection.com/objects/views.md#serve-a-view)

SQL source deletions set the ban cutoff at the landing commit. An observation
at or before that cutoff is withheld. An explicit erase keeps a standing ban
until audited readmission. Subject-bound rows read a live identity at their
own place before landing.

The virtual table owns erasable bucket facts for warehouse rows in view
datasets. Deletions close a matching bucket when the source reports the
partition key. Other deletions close the contributor's partition. Resets
close the contributor's buckets, and each bucket has a kernel deadline
within the source coverage window. The Datasets writer verifies the file's
subject bucket and stamps the SQL pin's row address. [View dataset erasure](https://docs.bijection.com/datasets#view-dataset-erasure)

## Forward a source erase

Declare `upstream: { erase, lifetime }` to review an explicit source erase.
The lock lists the target, lifetime, explicit erasers and acknowledgement
handler as pending. The submit guard currently refuses dispatch.

The designed forward is an ordinary submit with no survival. It sends
the caller's key or subject as a value and, for a member-scoped source,
the request place's minted member. The explicit eraser orders the submit,
the standing ban and the blind address closure together. The address uses
an immutable key, an eligible issued `_id` or one same-place unique.
The acknowledgement uses the delivered rows to update finite ban cutoffs,
preserves any standing ban and closes the forward task. The task lifetime
also closes the task. This closure applies the receiver's request-log policy.

End-to-end upstream erase dispatch and acknowledgement are designed, not implemented.

## Review compiled statements

`bijection check --write-lock` writes every rendered statement under
`bijection.statements/<tree path>/`, one file per shape, with a header giving
the dialect, statement digest, compiler revision, settings profile, binds,
columns, merged reads and origin (typed `ir=` or native `template=`). The
clock bind prints `at:instant(cut)` on a dated statement and
`at:instant(observed)` otherwise. `bijection describe <tree path>` prints a
table's contract and its statements, and `bijection describe sha256:<hex>`
prints one statement. See [`bijection.lock`](https://docs.bijection.com/development/cli/lock#committed-statements).

`bijection describe orders --read openByCustomer` shows the current local
declaration and the last reviewed read when available. The reviewed entry
includes bind types, fixed values, measures or effective order, bounds,
subject and credential scope, retention, snapshot eligibility and statement
digests. The source explanation for a view field or action links back to it.


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