# Table models

db2kit reads each table from the Db2 catalog and generates a typed model: its columns with their JavaScript types, its primary key, its indexes, and a size class taken from the catalog statistics. The object API (reads without SQL) uses the model to build the query, check every value before any network call, and refuse a filter that would scan a large table.

Models are read-only by default. Writes are enabled table by table with `models.writable` ([Writing](#writing)).

## Workflow

```sh
npx db2kit list MYSCHEMA                       # what the schema holds, and what generate accepts
npx db2kit describe MYSCHEMA.CONTRACT          # read the catalog, print Markdown, write nothing
npx db2kit generate MYSCHEMA.CONTRACT          # write the model, record it in the manifest
npx db2kit generate 'MYSCHEMA.*' -t table,view # every table and view of the schema (-y above 50)
npx db2kit generate                            # regenerate every table and procedure of the manifest
npx db2kit check                               # CI: exit code 1 if a file differs from the catalog
```

Patterns, `-t` and `-y`: [cli.md](cli.md#generate). `generate` finds whether a name is a table or a stored procedure. When a name is both, prefix it: `table:MYSCHEMA.CONTRACT` or `procedure:MYSCHEMA.CONTRACT`. Every command connects in read-only mode and only reads the catalog: `SYSIBM.SYSTABLES`, `SYSCOLUMNS`, `SYSINDEXES`, `SYSKEYS`, `SYSCOLDIST`, and for a view `SYSVIEWDEP` and `SYSVIEWS`.

Tables (`TYPE 'T'` in `SYSIBM.SYSTABLES`) and views over one table ([Views](#views)) are supported. An alias or another type is refused with its name: for an alias, generate the table it points to.

## Views

Legacy applications often read their data through views that rename the coded columns of a table into business names. db2kit generates such a view as a model with the names of the view, and the SQL it sends reads the view: the application needs no privilege on the table. Db2 merges a view of this form into the query, so the indexes of the table serve it.

```sql
CREATE VIEW MYSCHEMA.SHIPMENTS AS
  SELECT C001 AS SHIPMENT_ID, C002 AS DEPOT, C003 AS ROUTE_NO FROM MYSCHEMA.T_SHIPMENTS
```

gives a model with `shipmentId`, `depot` and `routeNo`, whose indexes, size class and selectivity come from `MYSCHEMA.T_SHIPMENTS`, under these names.

Accepted only when every check agrees, otherwise refused with the reason:

| Check                                                                                                                                                                                                                                                                                                                                                                                                      | Source                                                         |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------- |
| The view reads exactly one object, a table                                                                                                                                                                                                                                                                                                                                                                 | `SYSIBM.SYSVIEWDEP`                                            |
| Its text is `SELECT [qualifier.]column [[AS] name], ... FROM [schema.]table [[AS] corr]`, possibly in parentheses (`AS (SELECT ...)`), with an optional column list after the view name and an optional check option. A column may be qualified by the correlation name, the table or `schema.table`. No `WHERE`, join, expression, function, `DISTINCT`, `GROUP BY`, set operation, `SELECT *` or comment | `SYSIBM.SYSVIEWS.STATEMENT`, read whole: its length is checked |
| The text names that view and that table                                                                                                                                                                                                                                                                                                                                                                    | text against the catalog                                       |
| The view columns of the text are those of the catalog, in order                                                                                                                                                                                                                                                                                                                                            | `SYSIBM.SYSCOLUMNS` of the view                                |
| Each view column has the type, length and scale of the table column it reads, and no table column is shown twice. A view column recorded as nullable over a `NOT NULL` table column keeps `NOT NULL`: its values are those of the table                                                                                                                                                                    | `SYSIBM.SYSCOLUMNS` of both                                    |

A view without `WHERE` reads every row of its table, so the statistics of the table describe it. An index of the table whose key uses a column the view does not show is left out, with a warning. The generated file and `describe` name the table the view reads.

## Generated files

```
<codegen.outDir>/
  manifest.json                          tables and procedures generated so far
  AGENTS.md                              instructions for code assistants (procedures.md, Generated files)
  relations.ts                           Models: the models with their relations (written once, owned by the team)
  tables/
    MYSCHEMA.CONTRACT.generated.ts       one model per table
    index.ts                             Tables: every model of the manifest, for completion
```

Like procedure descriptors, `*.generated.ts` files are rewritten by every `generate`, never edited, and committed. Output is deterministic, so `check` compares files byte for byte.

Example (statistics and some columns left out):

<!-- prettier-ignore -->
```ts
// Generated by db2kit from the Db2 catalog. Do not edit: run `npx db2kit generate` again.
// Table MYSCHEMA.CONTRACT
// Warning: NOTES CLOB(4): left out, LOB columns are not read by the object API yet. Read it with db.query().

import { defineTable } from 'db2kit';

export interface ContractRow {
  /**
   * CONTRACT_ID CHAR(10), NOT NULL, primary key.
   * Text of at most 10 bytes, read without trailing blanks.
   */
  contractId: string;
  /**
   * BRANCH_CODE CHAR(4), NOT NULL.
   * Text of at most 4 bytes, read without trailing blanks.
   */
  branchCode: string;
  /**
   * START_DATE DATE, NOT NULL.
   * Text 'YYYY-MM-DD', for instance '2026-01-05'. A filter or a write in another form, '20260105' or '01/05/2026', is refused before sending.
   */
  startDate: string;
  /**
   * AMOUNT DECIMAL(11,2), nullable.
   * Exact number with at most 2 decimals: a filter value with more is refused, never rounded. null when NULL.
   */
  amount: number | null;
}

/**
 * Every property of ContractRow, by name, where the object API takes one as a value:
 * `by: [ContractField.contractId]`, `orderBy: { [ContractField.contractId]: SortOrder.Desc }`.
 */
export const ContractField = {
  /** CONTRACT_ID CHAR(10), NOT NULL, primary key. */
  contractId: 'contractId',
  /** BRANCH_CODE CHAR(4), NOT NULL. */
  branchCode: 'branchCode',
  /** START_DATE DATE, NOT NULL. */
  startDate: 'startDate',
  /** AMOUNT DECIMAL(11,2), nullable. */
  amount: 'amount',
} as const;
export type ContractField = (typeof ContractField)[keyof typeof ContractField];

/** Unique keys: findUnique takes exactly the columns of one, cursor needs one in orderBy. */
export type ContractUniqueKey = ['contractId'];

/**
 * Table MYSCHEMA.CONTRACT.
 *
 * Large table (codegen.largeTableRows): the index guard applies.
 * A where of findMany, findFirst or count must cover the leading keys of an index:
 * - contractId
 * - branchCode + startDate
 * with equalities (=, in), or a range (gt, lt, startsWith) on the last one.
 * Otherwise the read scans the table at every call: a person decides it and writes why,
 * allowScan: 'the reason', logged and recorded in the audit trail.
 *
 * findUnique: { contractId }. cursor: orderBy must include every column of one of them.
 * take: required, at most models.maxTake (1000 by default).
 */
export const contract = defineTable<ContractRow, ContractUniqueKey>({
  schema: 'MYSCHEMA',
  name: 'CONTRACT',
  size: 'large',
  columns: [
    { name: 'CONTRACT_ID', property: 'contractId', type: 'CHAR', length: 10, scale: 0, nullable: false },
    { name: 'BRANCH_CODE', property: 'branchCode', type: 'CHAR', length: 4, scale: 0, nullable: false },
    { name: 'START_DATE', property: 'startDate', type: 'DATE', length: 4, scale: 0, nullable: false },
    { name: 'AMOUNT', property: 'amount', type: 'DECIMAL', length: 11, scale: 2, nullable: true },
  ],
  primaryKey: ['contractId'],
  indexes: [
    { name: 'MYSCHEMA.CONTRACT_IX1', unique: false, selectiveKeys: 2, keys: [{ property: 'branchCode', order: 'ASC' }, { property: 'startDate', order: 'DESC' }] },
    { name: 'MYSCHEMA.CONTRACT_PK', unique: true, selectiveKeys: 1, keys: [{ property: 'contractId', order: 'ASC' }] },
  ],
});
```

## Help in the editor

The generated file is written for the developer who writes the call, and for code assistants that read the project:

- **Hovering a property** shows its Db2 type, whether it can be null, whether it belongs to a key, and the form of its value: `'YYYY-MM-DD'` for a `DATE`, the decimals of a `DECIMAL`, a string for a `BIGINT`.
- **Hovering the model** shows what a read on it needs: whether the index guard applies, the filters it accepts (the same list as its refusal message), the unique keys, and `take`.
- **The unique keys are part of the type of the model.** On a model without primary key nor unique index, `findUnique` and `cursor` are TypeScript errors, whose text explains why:

  ```
  Argument of type '{ where: { loggedAt: string; }; }' is not assignable to parameter of type
  '"This model has no unique key (no primary key, no unique index in the catalog): findUnique
  and cursor are not available. Use findFirst or findMany with orderBy."'.
  ```

  `findUnique` also takes exactly the columns of one key: a missing column, or a column that is not in the key, is underlined while the call is written.

- **The index guard is part of the type of a large table.** `generate` writes the prefixes the guard accepts (`ContractIndexed = ['branchCode'] | ['contractId']`), and every method that filters a large table (`findMany`, `findFirst`, `findPages`, `count`, `exists`, `aggregate`, `groupBy`, `updateMany`, `deleteMany`, and their `db.compile` forms) takes a `where` that gives a value to the keys of one of them, or `allowScan: true`. A `where` that no index serves is underlined while the call is written, and the message names the keys that are missing:

  ```
  Type '{ label: string; }' is missing the following properties from type
  '{ branchCode: string | FieldFilter<string>; }': branchCode
  ```

  On a large table without any index the guard counts (`NoSelectiveIndex`), every `where` needs `allowScan` with the reason of the person who decides the scan, and the message says so. The types check which keys are there, not how: `{ branchCode: { not: 'B001' } }` passes them and is refused when the call runs, as are an `OR` whose branches no index serves and a `where` built at runtime. A call without `where` is left to the run as well (a sort on the leading key of an index, or `findMany` that stops after `take` rows). A small table has no guard, and no such type.

The checks at runtime stay, for calls built at runtime and for models generated before db2kit 0.7.0 (unique keys) or 0.11.0 (index guard), which lack them in their type: run `generate` again to get them. A model written by hand can give them too: `defineTable<Row, ['id']>(...)`, `defineTable<Row, NoUniqueKey>(...)`, and the prefixes as third type parameter, `defineTable<Row, ['id'], ['id'] | ['branchCode']>(...)`.

The rules for code assistants that write calls are in [code-assistants.md](code-assistants.md), shipped in the package.

## Column types

Properties are the mechanical camelCase of the column names. Types follow the reads of `db.query`, except `DECIMAL` beyond 15 digits, read as an exact string:

| Db2 type                                         | JavaScript type     | Note                                                                                                       |
| :----------------------------------------------- | :------------------ | :--------------------------------------------------------------------------------------------------------- |
| `CHAR`, `VARCHAR`, `GRAPHIC`, `VARGRAPHIC`       | `string`            | `CHAR` and `GRAPHIC` without trailing blanks (`trimChar`)                                                  |
| `DATE`, `TIME`, `TIMESTAMP`                      | `string`            | As read by `db.query`, no time zone conversion                                                             |
| `SMALLINT`, `INTEGER`, `REAL`, `DOUBLE`          | `number`            |                                                                                                            |
| `DECIMAL` up to 15 digits                        | `number`            | Exact: 15 digits round-trip through a float                                                                |
| `DECIMAL` beyond 15 digits                       | `string`            | Read as text, exactly `scale` decimals. `orderBy` and `cursor` sort and compare the number, never the text |
| `BIGINT`                                         | `string`            |                                                                                                            |
| `DECFLOAT`                                       | `number`            | Precision beyond 15 digits is lost: generation warns                                                       |
| `BINARY`, `VARBINARY`                            | `Buffer`            |                                                                                                            |
| `CLOB`, `DBCLOB`, `BLOB`                         | left out            | LOB columns are not read by the object API yet                                                             |
| `FOR BIT DATA`, `XML`, `ROWID`, time zone, other | left out            | No confirmed mapping yet                                                                                   |
| nullable column                                  | the type, or `null` |                                                                                                            |

A column left out is listed as a warning in the generated file and by `describe`. Read it with `db.query`.

A property named like a member of every JavaScript object (`constructor`, `toString`, `valueOf`, from a column `CONSTRUCTOR`, `TO_STRING`, `VALUE_OF`) works when the call runs: only the keys given are read, never inherited ones. TypeScript, though, gives every object literal those members, so a `where`, `data` or `orderBy` that leaves such a property out needs `as never`.

## Size class

The size class comes from `CARDF`, the row count of the last `RUNSTATS`, compared with `codegen.largeTableRows` (default 100000):

| `size`    | When                                           | Index guard |
| :-------- | :--------------------------------------------- | :---------- |
| `small`   | `CARDF` below the threshold                    | off         |
| `large`   | `CARDF` at or above the threshold              | on          |
| `unknown` | `CARDF` is -1: statistics were never collected | on          |

Only the class is written to the file: a new `RUNSTATS` changes the model, and `check` reports it, only when the count crosses the threshold.

Generate against a subsystem whose statistics reflect production volumes. A table that is small in a test subsystem but large in production gets a `small` model there, and the guard stays off. When in doubt, ask the DBA which subsystem holds production-like statistics.

## Indexes

The model keeps every index whose keys are all columns of the model, with the order of each key (`ASC`, `DESC`, or `RANDOM`, which only serves equality). An index on an expression, or with a key column left out, is ignored with a warning. Uniqueness comes from `UNIQUERULE`: every value but `D` is unique. A unique index with `UNIQUERULE 'N'` (unique where not null) only identifies a row by non-null values.

A table without primary key nor unique index gets a warning: `findUnique` and cursor pagination need one. Its model is typed `NoUniqueKey`, so both are TypeScript errors on it.

The `INCLUDE` columns of a unique index (blank `ORDERING` in `SYSKEYS`, after `SYSINDEXES.UNIQUE_COUNT`) are stored in the index but are not part of its key: they make no row unique and give no access path, so the model leaves them out of the index.

## Selectivity

A filter can use an index and still read a large part of the table: on a table of 8 million rows, an equality on a leading column with 8 distinct values reads about a million rows. At generation, db2kit estimates for each index the rows an equality on its first 1, 2... key columns reads, and records how many leading keys a filter must cover to stay under `codegen.maxEstimatedRows` (default 10000):

```ts
{ name: 'MYSCHEMA.ORDER_IX2', unique: false, selectiveKeys: 2, keys: [/* depot, routeNo, ... */] }
```

| Prefix of the key | Distinct values taken from                                            |
| :---------------- | :-------------------------------------------------------------------- |
| first column      | `SYSINDEXES.FIRSTKEYCARDF`                                            |
| full key          | `SYSINDEXES.FULLKEYCARDF`, or one row for a unique index              |
| in between        | `SYSIBM.SYSCOLDIST`, `TYPE 'C'`: the group of the same columns        |
| no statistic      | the previous prefix, the whole table for the first: refuse, not guess |

Estimated rows are `CARDF` divided by the distinct values of the prefix. `selectiveKeys: null` means no prefix stays under the threshold: the guard ignores that index for filters, and the generated file says so in a warning. Without table statistics, `selectiveKeys` is 1: any filter on the leading column counts, as before.

`describe` shows the estimate of every prefix and the prefix that counts. The generated file only holds the count, so that a new `RUNSTATS` changes it, and `check` reports it, only when an estimate crosses the threshold.

Limits: the estimate is an average under a uniform distribution, so a frequent value can read much more. An `IN` list counts as one equality, whatever its length. A range counts like an equality, since its width is unknown. A `findMany` whose `orderBy` follows the index can stop after `take` rows, a `count` cannot: the guard treats both alike.

## Reading

Four methods, on `db` and on the `tx` of a transaction. Each takes the generated model first:

| Method                       | Returns                    | SQL                                                    |
| :--------------------------- | :------------------------- | :----------------------------------------------------- |
| `db.findMany(model, args)`   | Array of rows              | `SELECT ... FETCH FIRST take ROWS ONLY FOR FETCH ONLY` |
| `db.findFirst(model, args?)` | The first row, or `null`   | `FETCH FIRST 1 ROWS ONLY`                              |
| `db.findUnique(model, args)` | The row of one key, `null` | equality on a unique key, `FETCH FIRST 2 ROWS ONLY`    |
| `db.count(model, args?)`     | A number                   | `SELECT COUNT(*)`                                      |
| `db.exists(model, args?)`    | `true` or `false`          | `SELECT 1 ... FETCH FIRST 1 ROW ONLY`                  |

```ts
import { Tables } from './db2/generated/tables';

const contracts = await db.findMany(Tables.contract, {
  where: { branchCode: 'B001', status: { in: ['A', 'S'] }, amount: { gte: 100 } },
  select: { contractId: true, startDate: true, amount: true },
  orderBy: [{ startDate: 'desc' }, { contractId: 'asc' }],
  take: 50,
  tag: 'contracts.list',
});
// contracts: Array<{ contractId: string; startDate: string; amount: number | null }>

const one = await db.findUnique(Tables.contract, { where: { contractId: 'C000000001' } });
const total = await db.count(Tables.contract, { where: { branchCode: 'B001' } });
```

`Tables` comes from `tables/index.ts`, rewritten by every `generate` from the manifest: typing `Tables.` lists every generated model, each with its table name on hover. A model imported from its own file works the same. Two tables of different schemas with the same name are prefixed with their schema (`salesContract`, `archiveContract`). Two names of one schema that differ only by `_`, `#`, `$` or `@` map to the same JavaScript name: the index leaves them out with a comment, import them from their files.

Every argument is checked against the model before any network call: an unknown property, a value of the wrong type, `undefined`, a decimal with more digits than the column scale, a text longer than its column (in a filter too: the driver would refuse it, [queries.md](queries.md#accepted-values)), an empty `IN` list. A refusal raises `Db2UsageError` with the method, the table, the path of the argument and the reason, for instance `findMany on MYSCHEMA.CONTRACT, where.amount: (AMOUNT DECIMAL) 3 decimal(s) for a scale of 2: Db2 would round it silently. Round the value first.`

Rows come back by property, every model column unless `select` names some, with the types of [Column types](#column-types).

### `where`

Conditions on several properties are combined with `AND`. A value means equality, `null` means `IS NULL`, an object is a filter:

| Filter                                   | SQL                     | Note                                                          |
| :--------------------------------------- | :---------------------- | :------------------------------------------------------------ |
| `value`, `{ equals: value }`             | `= ?`                   |                                                               |
| `null`, `{ equals: null }`               | `IS NULL`               |                                                               |
| `{ not: value }`                         | `<> ?`                  | Like SQL, never matches a null column                         |
| `{ not: null }`                          | `IS NOT NULL`           |                                                               |
| `{ in: [...] }`, `{ notIn: [...] }`      | `IN (?, ...)`, `NOT IN` | 1 to 1000 values, no `null`                                   |
| `{ lt }`, `{ lte }`, `{ gt }`, `{ gte }` | `<`, `<=`, `>`, `>=`    |                                                               |
| `{ startsWith: 'AB' }`                   | `LIKE 'AB%'`            | `CHAR` and `VARCHAR` only. `%`, `_` are matched as is         |
| `{ contains: 'AB' }`                     | `LIKE '%AB%'`           | Never uses an index                                           |
| `{ endsWith: 'AB' }`                     | `LIKE '%AB'`            | Never uses an index. A `CHAR` is compared without its padding |
| `AND: [...]`, `OR: [...]`, `NOT: {...}`  | `AND`, `OR`, `NOT`      | Nested conditions                                             |

Refused rather than guessed: `undefined` (pass `null` or leave the property out), an array as a value (use `in`), an empty filter, an empty `OR`, an empty nested condition, an empty text for `startsWith`, `contains` or `endsWith` (it matches every row).

`DECIMAL`, `BIGINT`, `SMALLINT` and `INTEGER` values travel as exact text or integers to a marker of the column type, for instance `"AMOUNT" > CAST(? AS DECIMAL(11, 2))`: the comparison stays between equal types, which keeps it indexable, and no float rounding happens on the way. A `DECIMAL` value with more decimals than the column scale is refused, as for a procedure call.

The SQL text does not depend on how the filter is written: conditions follow the column order of the model, operators a fixed order, and `IN` lists are padded to 1, 2, 4, 8 ... 512 or 1000 values by repeating the last one. Db2 then sees a handful of texts and reuses their access plans.

### `select`, `orderBy`, `take`

- `select: { contractId: true, amount: true }` reads these properties only, typed accordingly. Each row gives them in the order of the model, whatever the order of the keys of `select`: the same columns always send the same SQL text, which Db2 prepares once (its dynamic statement cache). Compare rows property by property, never as JSON text.
- `orderBy: { startDate: 'desc' }`, or an array for several keys, in order. One property per object.
- **Names and directions as constants.** Each generated model exports `<Name>Field`, every property by name, with the column in its hover help, and db2kit exports `SortOrder` (`SortOrder.Asc`, `SortOrder.Desc`). Where a property is a value, `by: [ContractField.branchCode]`, and where it is a key, `orderBy: { [ContractField.startDate]: SortOrder.Desc }`: no text repeated across files, and renaming a column shows every use. The words `'asc'` and `'desc'` stay accepted. Both are constant objects with a type of the same name, as `AuditParams`: TypeScript enums are refused by the type stripping of Node.js.
- `take` is required for `findMany`, from 1 to `models.maxTake` (default 1000). It becomes `FETCH FIRST take ROWS ONLY`: Db2 stops there, and Node never holds more.
- There is no `skip`: `OFFSET` makes Db2 read and drop every skipped row, and older compatibility levels refuse it (SQLCODE -4743). Page with `cursor`.

### Pages: `cursor`

```ts
const page1 = await db.findMany(contract, {
  where: { branchCode: 'B001' },
  orderBy: [{ startDate: 'desc' }, { contractId: 'asc' }],
  take: 50,
});
const page2 = await db.findMany(contract, {
  where: { branchCode: 'B001' },
  orderBy: [{ startDate: 'desc' }, { contractId: 'asc' }],
  cursor: page1.at(-1),
  take: 50,
});
```

`cursor` reads the rows strictly after the given one in `orderBy` order (keyset pagination). It needs a value for every `orderBy` property: the last row of the previous page fits. The order must be total, so `orderBy` must include every column of the primary key or of a unique index, and only `NOT NULL` columns: a null value would be skipped. The condition written for the example above:

```sql
"START_DATE" <= ? AND ("START_DATE" < ? OR ("START_DATE" = ? AND "CONTRACT_ID" > ?))
```

The first condition gives Db2 a range on the leading sort key. Unlike Prisma, the cursor row itself is not returned: there is no `skip: 1` to add.

### Every row, page by page: `findPages`

For an export, `findPages` reads every matching row, `take` rows per page, and chains the cursors itself:

```ts
for await (const page of db.findPages(contract, {
  where: { branchCode: 'B001' },
  orderBy: [{ startDate: 'desc' }, { contractId: 'asc' }],
  take: 500,
  tag: 'contracts.export',
})) {
  await write(page);
}
```

| Point       | Rule                                                                                                                                                                                                                   |
| :---------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Statements  | One per page, the first without cursor, each next one from the last row of the previous page. Nothing stays open in Db2 between two pages: the export holds no cursor nor lock while the application writes a page out |
| End         | After a page shorter than `take`. When the last page is full, one more statement finds no row: no empty page is yielded                                                                                                |
| Order       | The rules of `cursor`: `orderBy` on every column of a unique key, `NOT NULL` columns only. A `select` keeps the `orderBy` properties, which give the next cursor. A model without unique key is a TypeScript error     |
| Checks      | Those of `findMany`, the index guard included, when the iteration starts, before the first statement. `cursor` resumes an export after a given row                                                                     |
| Audit       | One event per page, source `findPages`, with the tag of the call                                                                                                                                                       |
| Consistency | Each page is read on its own, as with any keyset pagination: a row written meanwhile after the cursor shows up, a row before it does not. For a fixed picture of the data, a named query or an extract on the Db2 side |

### `findUnique`

`where` must give a non-null value for exactly the columns of the primary key or of one unique index, nothing else. Use `findFirst` for anything else. A table without primary key nor unique index has no `findUnique`. On a generated model, all of this is checked by TypeScript while the call is written ([Help in the editor](#help-in-the-editor)), and again at runtime. When Db2 returns two rows for one key, the unique index the model relies on no longer exists: `findUnique` throws and asks to run `npx db2kit check`.

## Index guard

On a `large` or `unknown` table, a read must be able to use an index, otherwise Db2 scans the whole table. Before any network call, `findMany`, `findFirst`, `count` and `exists` check that:

- the top-level conditions cover the leading keys of an index, at least `selectiveKeys` of them ([Selectivity](#selectivity)): `=`, `IN` and `IS NULL` cover a key, `<`, `<=`, `>`, `>=` and `startsWith` cover the next key when it is not `RANDOM`, and end the prefix. An `OR` counts when each of its branches does. `NOT`, `<>`, `NOT IN`, `contains` and `endsWith` never count, nor a condition on a related row ([Relations](#relations));
- or, without any `where`, the first `orderBy` property leads an index whose key is not `RANDOM`: Db2 reads the first rows of the index in order;
- or, for `findMany`, `findFirst` and `exists`, without `where` nor `orderBy`: `FETCH FIRST take ROWS ONLY` without a sort, so Db2 returns the first rows it reads and stops. Which rows is unspecified, and may change from one call to the next.

On a generated model, TypeScript checks the keys of the `where` while the call is written ([Help in the editor](#help-in-the-editor)); the rules below run when the call does.

`count` without `where` is refused: it reads every row, or every entry of an index. `exists` with a `where` follows the rule of `count`: Db2 reads until a row matches, every row when none does.

A cursor adds a range on the first sort key, which counts like any other condition. A condition on the second key of an index alone does not count.

When the check fails:

| Setting                                | Effect                                                                                                                                                                                                                 |
| :------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| default (`models.indexGuard: 'throw'`) | `Db2UsageError` with `code: 'INDEX_GUARD'`, naming the filters that would use an index selectively, saying whether no index applies or one applies but reads too many rows, and the ways out: a smaller table, a cache |
| `allowScan: 'the reason'` on the call  | Runs. The client logs the scan once per process, with its reason, and the audit event of every call carries `ALLOW_SCAN` and `scanReason`                                                                              |
| `models.indexGuard: 'warn'`            | Runs, with the `SCAN_RISK` warning in the audit trail                                                                                                                                                                  |

`allowScan` is the explicit escape hatch, and it takes the reason of the person who decided the scan, never `true`: `allowScan: 'reference list, read once a day'`, one line of at most 200 characters. A flag was too easy to add to make a refusal or a TypeScript error go away, the scan then running at every call without a word. The reason shows in code review, once in the log of each process that runs it, in the audit event of every call, and in the inventory `npx db2kit check` prints: every `allowScan` of the code, with its file and line ([cli.md](cli.md#check)). Before writing one, prefer a filter on an index, a smaller table that holds what is looked for (a reference table rather than the distinct values of a large one), or a cache of the result. `'warn'` suits a production that should not break on a query reviewed too late, with the audit trail watched. The width of a range stays unknown: `{ startDate: { gte: '2000-01-01' } }` passes when an equality on `startDate` would, and may still read most of the table. `findUnique` always uses a unique index and needs no check.

## Relations

The catalog of an application may declare no foreign key, and a declared one is not always the relation it reads. So relations are declared by the team, in `relations.ts`: `generate` writes it once, next to `tables/`, and never again.

Without a declared foreign key, a link between two tables is a convention: a column holds the key of a row of another table, and the programs that join on it (`WHERE A.X = B.Y`) keep it consistent. Db2 neither checks it (a row can point to nothing, a row still pointed to can be deleted) nor records it in its catalog, so no tool can read it there, db2kit included. Such links are found in the SQL of the programs and views that join on them, with the team that owns those programs, or by the names of the columns, a hint rather than a proof. Declared in `relations.ts`, a relation to one row must join on a unique key of the related model, so that a join never multiplies the rows read.

```ts
// relations.ts, owned by the team
import { defineRelations } from 'db2kit';
import { Tables } from './tables';

export const Models = defineRelations(Tables, {
  contract: {
    office: { one: 'branch', on: { branchCode: 'code' } },
  },
});
```

`office` is the name of the relation, `one` the related model, `on` pairs each property of a unique key of the related model with a property of this one. The editor completes the three. Every model of `Tables` is in `Models`, with its relations when it has some: read through `Models`.

`npx db2kit add MYSCHEMA.CONTRACT`, when it writes a model for the first time, proposes the relations its columns suggest with the models already generated: a column with the name and the kind of type of every column of a unique key of another model, a hint read from the names, never a fact. Each one is a question; accepted, it is declared on both sides, `branch` to one row on the contract and `contracts` to many rows on the branch, checked by `defineRelations` before `relations.ts` is written. `add` writes that file only while it holds exactly what db2kit writes, whatever a formatter changed: a comment or a relation written by hand, and it shows the lines to add instead ([cli.md](cli.md#add)).

```ts
import { Models } from './db2/generated/relations';

const contracts = await db.findMany(Models.contract, {
  select: { contractId: true, amount: true, office: { select: { name: true } } },
  where: { branchCode: 'B001', office: { region: 'N' } },
  take: 50,
});
// Array<{ contractId: string; amount: number | null; office: { name: string } | null }>
```

```sql
SELECT t0."CONTRACT_ID", t0."AMOUNT", t1."CODE" AS "office.CODE", t1."NAME" AS "office.NAME"
FROM "MYSCHEMA"."CONTRACT" t0
LEFT OUTER JOIN "MYSCHEMA"."BRANCH" t1 ON t1."CODE" = t0."BRANCH_CODE"
WHERE t0."BRANCH_CODE" = ? AND t1."REGION" = ?
FETCH FIRST 50 ROWS ONLY FOR FETCH ONLY
```

| Point       | Rule                                                                                                                                                                                                                                                                                                             |
| :---------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Join        | `LEFT OUTER JOIN` on a unique key of the related model: a row meets at most one related row, never multiplies. `defineRelations` refuses properties that are not exactly a unique key, and types that do not compare (a number with a text, a `DATE` with a `TIMESTAMP`), when the module loads                  |
| Name        | A JavaScript identifier, not a property of the model, nor `AND`, `OR` or `NOT` (they combine conditions in a `where`), nor a member every JavaScript object inherits (`constructor`, `toString`, `valueOf`...): TypeScript gives every object literal those members                                              |
| Missing row | The relation reads `null`. Without a declared foreign key, Db2 does not ensure the related row exists: the type always allows `null`                                                                                                                                                                             |
| `select`    | `office: true` reads every column of the related row, `office: { select: { ... } }` some of them. Without `select`, a read gives the columns of the model and no relation. The key of the related row is always read, to see whether it exists                                                                   |
| `where`     | `office: { ... }` takes the conditions of the related row, also inside `AND`, `OR` and `NOT`. A row then needs a related row that matches                                                                                                                                                                        |
| Index guard | A condition on the related row never counts: it filters that row, not the table read. A read through a relation still needs a selective filter on its own table, or `allowScan` ([Index guard](#index-guard)). Without filter nor sort, `findMany` stops after `take` rows, each joined through the unique index |
| SQL text    | Every relation a read uses is joined once, under the name of its declaration order: `t1` for the first declared, `t2` for the second. A read that uses none sends the text of a plain model, so the access plans already cached by Db2 still apply                                                               |
| Depth       | One level: the relations of a related row are not read                                                                                                                                                                                                                                                           |
| Methods     | `findMany`, `findFirst`, `findUnique` (`select`), `count`, `exists`, `aggregate` and `groupBy` (`where`). Writes take the columns of their model only                                                                                                                                                            |

### Relations to many rows

```ts
export const Models = defineRelations(Tables, {
  contract: {
    office: { one: 'branch', on: { branchCode: 'code' } },
    payments: { many: 'payment', on: { contractId: 'contractId' } },
  },
});
```

`many` names the model of the related rows, `on` pairs properties of this model with the properties of the related rows that refer to it. No unique key is needed. They are read with `include`, and filtered with `some`, `none` and `every`:

```ts
const contracts = await db.findMany(Models.contract, {
  select: { contractId: true, label: true },
  where: { branchCode: 'B001', payments: { some: { paid: { gt: 100 } } } },
  include: { payments: { take: 5, select: { paid: true }, orderBy: { paidOn: 'desc' } } },
  take: 50,
});
// Array<{ contractId: string; label: string | null; payments: Array<{ paid: number }> }>
```

`include` reads the related rows in one more statement, whatever the number of rows read (split past 1000 markers, see Keys): their keys in an `IN` list, and `take` rows at most for each, kept by `ROW_NUMBER()` in the order of `orderBy`.

```sql
SELECT "CONTRACT_ID", "PAID" FROM (
  SELECT "CONTRACT_ID", "PAID",
    ROW_NUMBER() OVER (PARTITION BY "CONTRACT_ID" ORDER BY "PAID_ON" DESC) AS DB2KIT_ROW
  FROM "MYSCHEMA"."PAYMENT" WHERE "CONTRACT_ID" IN (?, ?, ?, ?)
) AS DB2KIT_INCLUDE WHERE DB2KIT_ROW <= 5 ORDER BY "CONTRACT_ID", DB2KIT_ROW FOR FETCH ONLY
```

| Point                   | Rule                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| :---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `include`               | `take` is required, from 1 to `models.maxTake`, for each row read. `where`, `select` and `orderBy` of the related rows are optional. Without `orderBy`, which rows `take` keeps is unspecified. A row without related row gets an empty list. Several includes: one statement each, in their order of declaration                                                                                                                                            |
| Keys                    | The key of each row read is read even when not selected, and left out of the result. A row whose key is null gets an empty list. Past 1000 markers, the statement is split, at most 1000 markers each: up to 1000 keys of one column, 256 of two or three, 128 of four or five. The `IN` list is padded like any other ([`where`](#where))                                                                                                                   |
| Matching                | A related row goes to the rows whose key it has, as Db2 compares them: numbers by value whatever their type, texts without trailing blanks                                                                                                                                                                                                                                                                                                                   |
| `some`, `none`, `every` | A correlated `EXISTS`: `some` at least one related row matches, `none` no related row does, `every` no related row fails the condition. `some: {}` means at least one related row, `none: {}` none at all; `every: {}` is refused, it would match every row. A related row whose condition is unknown (a `NULL`) does not break `every`, like SQL                                                                                                            |
| Index guard             | On a large related model, the columns of `on` must lead an index, at least `selectiveKeys` of them (they count as equalities), with the conditions of the related rows: both for `include` and for `some`, `none` and `every`. `allowScan` of the read applies to them too, `findUnique` included: its row is read by its key, `allowScan` only accepts the scan of the related rows of an include. A filter of related rows never counts for the model read |
| Audit                   | The statement of an include is a separate event, its source `findMany:include:payments`, with the tag of the read                                                                                                                                                                                                                                                                                                                                            |
| Transactions            | `tx.findMany` reads the related rows on the pinned connection too                                                                                                                                                                                                                                                                                                                                                                                            |
| Methods                 | `include` with `findMany`, `findFirst` and `findUnique`; `some`, `none` and `every` in the `where` of `findMany`, `findFirst`, `count`, `exists`, `aggregate` and `groupBy`. `select` refuses a relation to many rows: it is read with `include`                                                                                                                                                                                                             |

## Aggregates

```ts
const totals = await db.aggregate(Models.contract, {
  where: { branchCode: 'B001' },
  _count: true,
  _sum: { amount: true },
  _avg: { amount: true },
  _min: { startDate: true },
});
// { _count: number; _sum: { amount: number | null }; _avg: { amount: number | null }; _min: { startDate: string | null } }

const byStatus = await db.groupBy(Models.contract, {
  by: ['status'],
  where: { branchCode: 'B001' },
  _count: true,
  _sum: { amount: true },
  having: { _sum: { amount: { gte: 1000 } } },
  orderBy: { _sum: { amount: 'desc' } },
  take: 20,
});
// Array<{ status: string; _count: number; _sum: { amount: number | null } }>
```

```sql
SELECT "STATUS", COUNT(*) AS "_count", CAST(SUM("AMOUNT") AS DECIMAL(15, 2)) AS "_sum.AMOUNT"
FROM "MYSCHEMA"."CONTRACT" WHERE "BRANCH_CODE" = ?
GROUP BY "STATUS" HAVING CAST(SUM("AMOUNT") AS DECIMAL(15, 2)) >= CAST(? AS DECIMAL(15, 2))
ORDER BY "_sum.AMOUNT" DESC FETCH FIRST 20 ROWS ONLY FOR FETCH ONLY
```

| Aggregate                    | Result                                     | Rule                                                                                                                                                                                                                                                                          |
| :--------------------------- | :----------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `_count: true`               | number                                     | `COUNT(*)`                                                                                                                                                                                                                                                                    |
| `_count: { property: true }` | number per property                        | The values that are not `NULL`                                                                                                                                                                                                                                                |
| `_sum`                       | number, `null` over no row                 | Numbers only. Summed as `DECIMAL(31)`, then given as a number of 15 digits at most, exact: a wider sum fails in Db2 (SQLCODE `-413` or `-802`) instead of being rounded. A column of scale above 15 is refused. `REAL`, `DOUBLE` and `DECFLOAT` sum as floating-point numbers |
| `_avg`                       | number, `null` over no row                 | Numbers only, computed as `DOUBLE`: Db2 would give the average of integers as an integer (1 and 2 give 1). A floating-point number, so not exact: for an exact average of decimals, a [named query](queries.md#named-queries)                                                 |
| `_min`, `_max`               | the type of the column, `null` over no row | Any column but a binary one. A `DECIMAL` beyond 15 digits stays exact text, which `having` compares as a number                                                                                                                                                               |

| Point       | Rule                                                                                                                                                                                                                                                                                                                                                                                 |
| :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Index guard | The rule of `count`: every matching row is read, so on a large table the `where` must use an index selectively, or `allowScan` ([Index guard](#index-guard)). A `where` through relations works as in `findMany`                                                                                                                                                                     |
| `groupBy`   | `by` lists the properties of the groups, `take` (required, at most `models.maxTake`) bounds the groups read. Without `orderBy`, which groups `take` keeps is unspecified                                                                                                                                                                                                             |
| `having`    | Conditions on aggregates asked for too, combined with `AND`: `equals`, `not`, `lt`, `lte`, `gt`, `gte`. `_count: { gt: 1 }` filters the count of rows, `_count: { label: { gt: 1 } }` the count of values of a property. A value is bound with the type of the aggregate: an integer for `_count`, the `DECIMAL` of the sum, a `DOUBLE` for `_avg`, the column for `_min` and `_max` |
| `orderBy`   | One property of `by` or one aggregate asked for per object, `{ _count: 'desc' }`, `{ _count: { label: 'desc' } }` or `{ _sum: { amount: 'desc' } }`; an array for several keys. A `by` property, a `_min` or a `_max` that is a `DECIMAL` beyond 15 digits sorts as a number, by `MIN` or `MAX` of the column: its result is text, which Db2 would sort as text                      |
| Types       | The result follows the aggregates asked for. `by` and `having` are checked against the model. `_sum` and `_avg` accept any property in the types, and refuse a column that is not a number when the call runs: the generated row type does not tell a `CHAR` from a `DECIMAL` read as text                                                                                           |

The distinct values of properties are a `groupBy` without aggregate: `by: ['status']` alone reads each status once, as `SELECT DISTINCT` would, with the same index guard and `take`.

For anything else (distinct rows with their other columns, an exact average, a window function), a [named query](queries.md#named-queries).

## Writing

Models are read-only by default: most writes of a z/OS application go through stored procedures, which hold its rules ([procedures.md](procedures.md)). The object API writes a table or a view only when the configuration of the application lists it:

```ts
createDb2({
  // ...
  models: { writable: ['MYSCHEMA.CONTRACT'] },
});
```

| Method                                              | SQL                                                    | Returns                          |
| :-------------------------------------------------- | :----------------------------------------------------- | :------------------------------- |
| `db.create(model, { data })`                        | `INSERT INTO ... (columns of data) VALUES (...)`       | rows inserted: 1                 |
| `db.update(model, { where, data })`                 | `UPDATE ... SET ... WHERE` the columns of a unique key | 1, or 0 when no row has that key |
| `db.updateMany(model, { where, data, allowScan? })` | `UPDATE ... SET ... WHERE` the filter                  | rows updated                     |
| `db.delete(model, { where })`                       | `DELETE FROM ... WHERE` the columns of a unique key    | 1, or 0 when no row has that key |
| `db.deleteMany(model, { where, allowScan? })`       | `DELETE FROM ... WHERE` the filter                     | rows deleted                     |

Each method also takes `tag`, shown in the audit trail.

```ts
await db.create(contract, {
  data: {
    contractId: 'C000000042',
    branchCode: 'B001',
    startDate: '2026-01-05',
    amount: 12.5,
    status: 'A',
  },
});
const changed = await db.update(contract, {
  where: { contractId: 'C000000042' },
  data: { status: 'X' },
});
if (changed === 0) throw new NotFoundException();
await db.updateMany(contract, {
  where: { branchCode: 'B001', status: 'A' },
  data: { status: 'S' },
});
```

Checked before any network call, each refusal a `Db2UsageError` that names the property:

- The table is listed in `models.writable` (`SCHEMA.NAME`, case does not matter). `readOnly: true` still refuses every write.
- `data` names at least one property of the model. `undefined` is refused: leave the property out, or pass `null`. `null` is accepted only for a nullable column. A value is checked like a filter value (type, integer range, `DECIMAL` scale) and travels the same way: `DECIMAL` and `BIGINT` as exact text to a marker of the column type. A text longer than its column is refused, counted in characters, which never exceed the bytes Db2 counts.
- A property left out of `create` is not written: Db2 gives the column its default, or refuses a `NOT NULL` column without default with SQLCODE -407 (`NULL_NOT_ALLOWED`).
- `update` and `delete` take the `where` of `findUnique`: exactly the columns of one unique key. On a model without one, they are TypeScript errors: use `updateMany` or `deleteMany`.
- `updateMany` and `deleteMany` need a `where`, never empty: a statement that changes every row is written as SQL with `execute`, where code review sees it. On a `large` or `unknown` table the `where` passes the [index guard](#index-guard), like a read: an `UPDATE` or a `DELETE` that scans a large table reads and locks all of it. `allowScan: true` and `models.indexGuard: 'warn'` behave as for reads.
- The SQL text depends only on which properties are given, in model column order: Db2 reuses one access plan per shape of call.

When `update` or `delete` changes more than one row for one key value, the unique index the model relies on no longer exists: the method throws after the statement and asks to run `npx db2kit check`. Outside a transaction that change is already committed. Inside one, the transaction rolls back.

Not built: `createMany` (one round trip for many rows needs array binding or a multi-row `INSERT`, neither checked on Db2 for z/OS yet: insert in a loop inside `db.$transaction`), returning the written row or values generated by Db2 (`SELECT ... FROM FINAL TABLE (INSERT ...)`), upsert (`MERGE`).

## Seeing the SQL: `db.compile`

`db.compile` has every method of the object API, with the same arguments, and returns the statement the call would send instead of sending it. Every check of the call runs, the index guard included: a refused call is refused here too.

```ts
const { sql, params, warnings, includes } = db.compile.findMany(Models.contract, {
  where: { branchCode: 'B001', office: { region: 'N' } },
  take: 50,
});
```

| Field      | What it holds                                                                                                         |
| :--------- | :-------------------------------------------------------------------------------------------------------------------- |
| `sql`      | The text sent to Db2, with its `?` markers: what the audit trail records, and what `EXPLAIN` takes                    |
| `params`   | The values of the markers, as db2kit binds them: text for a `DECIMAL` or a `BIGINT`, the codec applied                |
| `warnings` | `ALLOW_SCAN` or `SCAN_RISK`, as in the audit trail                                                                    |
| `includes` | The relations to many rows of an `include`: each one more statement once the rows are read, which compile cannot know |

Nothing is sent, nothing is audited, and it works inside `db.$transaction`. `params` holds the values of the call: keep it out of logs that personal data must not reach. For a review with the DBA, the SQL text of a call is enough: it does not change with the values.

## In a transaction

`tx.findMany`, `tx.findFirst`, `tx.findUnique`, `tx.count`, `tx.exists`, the aggregates and the writes run on the pinned connection of the transaction, like `tx.query`. Inside the callback, `db.findMany` or `db.create` is refused like any other `db.*` call. See [transactions.md](transactions.md).

## Not supported yet

`distinct` on whole rows (the distinct values of properties are a [`groupBy` without aggregate](#aggregates)), views other than a plain projection of one table, LOB columns, `createMany`, upsert. For a read, write a [named query](queries.md#named-queries). For a write, `db.execute` or a stored procedure.
