# Configuration

The configuration is one file, `db2kit.config.mts`, read by the CLI at each command and by the application when it creates its client (`loadConfigFile()`, below), which passes it to `createDb2(config)`. `defineConfig()` only helps with typing. `connectionFromEnv` names the variables that hold the connection settings, read again at each new connection. `env('NAME')` reads any other required variable once, at startup, and throws a clear error when it is missing.

Every configuration error is listed at once in a `Db2ConfigError` at startup. A key db2kit does not know, at the top level or in a section, is one of them, with the right spelling when only the case differs (`pool.acquireTimeOutMs is not a db2kit setting: did you mean pool.acquireTimeoutMs?`), and so is a section that is not an object. Ignored, such a key would leave its default in place without a word: TypeScript flags it in a `defineConfig` literal, but not in a JavaScript file, nor in a `.ts` file loaded without a type check as the CLI does. The free names stay free: extra keywords, outcome convention, default inputs.

## The configuration file

Name it `db2kit.config.mts`: the `.mts` extension is always loaded as an ES module, even in a CommonJS project such as NestJS. The CLI looks for, in order: `db2kit.config.mts`, `.ts`, `.mjs`, `.js`. The `-c` option points to another file.

The file must do `export default defineConfig({ ... })`: the default export is the configuration, never a function that returns it: db2kit never calls it, and the CLI and `loadConfigFile` refuse it with a message that says so (`export default await settings()` for a function). The CLI loads it alone, without the application: it imports `db2kit` and, by relative paths, files of the project ([below](#the-settings-of-the-application-inside-its-build)), never a path alias (the `imports` field of `package.json`, the `paths` of a tsconfig) nor NestJS. A TypeScript file goes through the type stripping of Node.js, on by default from Node.js 22.18: no `enum`, no `namespace`. On an earlier 22, write it as `db2kit.config.mjs`.

The application reads the same file, never a copy written in its code:

```ts
import { loadConfigFile } from 'db2kit';

const config = await loadConfigFile(); // or loadConfigFile({ path }), relative to the current folder
const db = createDb2(config, { logger });
```

`loadConfigFile` imports the file when it is called. A value the file reads from `process.env` is therefore the one of the running process at that moment: one file, set per environment by its variables (`pool: { max: process.env.NODE_ENV === 'production' ? 8 : 2 }`). It loads no environment file, `cli.envFile` included: call it once the application has loaded its own environment (with `@nestjs/config`, after `await ConfigModule.envVariablesLoaded`, [nestjs.md](nestjs.md#module)). A missing file, or one without a default export, throws a `Db2ConfigError`. The file is imported once per process: a second call returns what the first read. In production, the image holds the file in the working folder of the process, or the application gives its path.

What the CLI does with the settings of the application: it connects read-only, sends no audit event and opens one connection, whatever `readOnly`, `audit.sinks` and `pool` say. The application ignores `cli` and `codegen`.

`cli: { envFile: '.env' }` names the environment file the commands load, relative to the configuration file, so that none needs `-e`. See [cli.md](cli.md#common-options).

### The settings of the application inside its build

`db2kit.config.mts` at the root is outside what the build of the application compiles: an image that holds only the build copies it apart, and it holds `cli` and `codegen`, which the application ignores. Moving it into the sources breaks the CLI, which takes the folder of the configuration file for the root of the project (`codegen.outDir`, `cli.envFile`, `db2kit-cases/`, `tsconfig.json`). Without a change to db2kit, split it in two files, one source for both programs:

```ts
// src/database/database.config.ts: compiled with the application.
import { connectionFromEnv, defineConfig, type Db2KitConfig } from 'db2kit';

// A function, called once the environment is loaded: a constant would read process.env when
// the module is imported, before the application loaded its .env.
export function databaseConfig(): Db2KitConfig {
  return defineConfig({
    connection: connectionFromEnv('DB_APP'),
    pool: { max: process.env.NODE_ENV === 'production' ? 8 : 2, min: 1 },
    audit: { applicationName: 'my-api' },
  });
}
```

```ts
// db2kit.config.mts, at the root: read by the CLI only.
import { defineConfig } from 'db2kit';
import { databaseConfig } from './src/database/database.config';

export default defineConfig({
  ...databaseConfig(),
  cli: { envFile: '.env' },
  codegen: { outDir: 'src/db2/generated' },
});
```

- The root file imports the module of the sources by a relative path. The CLI resolves it as TypeScript does, without its extension, from Node.js 22.15 (before, write `./src/database/database.config.ts`), and compiles it. A path alias (`#database/...` of the `imports` field of `package.json`) resolves where that field says, often the compiled `dist`: absent or stale before a build.
- The module of the sources is loaded by the CLI alone too: it imports `db2kit` and relative paths only, no NestJS, no service, no secret store.
- An `async` function is exported the same way: `...(await databaseConfig())`. The default export stays the object.
- The CLI loads `cli.envFile` after the configuration file: a value the function reads from `process.env` is the one of the process, or of `-e`. The connection read with `connectionFromEnv` is read at each new connection, after the file.
- The application calls the function itself, in the factory of `Db2Module.forRootAsync` after `await ConfigModule.envVariablesLoaded`, and never `loadConfigFile` ([nestjs.md](nestjs.md#settings-compiled-with-the-application)).

## `cli`

Read by the command line only. `createDb2` ignores it: the application loads its own environment.

| Key               | Default | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| :---------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `envFile`         | none    | Environment file every command loads after the configuration file, relative to it. Never overrides a variable already set. `-e` replaces it for one command. An absent file is skipped (CI sets its own variables), and a variable still missing is refused with the reason                                                                                                                                                                        |
| `rollbackServers` | none    | The locations (`CURRENT SERVER`) of the test subsystems where `npx db2kit add --rollback` may call a procedure that modifies data, each case in a transaction always rolled back ([cli.md](cli.md#trying-a-procedure-that-modifies-data)). Compared before any call, whatever the case: another location is refused. Never the location of production. A location names a subsystem, not a secret: it may be committed, or read from `process.env` |
| `verifyServers`   | none    | The locations (`CURRENT SERVER`) where `npx db2kit verify` may run: it calls every procedure that reads with its cases and reads a few rows of every model, on a read-only connection ([cli.md](cli.md#verify)). Compared before any call: another location is refused. A test subsystem, as a rule                                                                                                                                                |
| `language`        | `'en'`  | The language of what `add`, `probe` and `status` print for a procedure, of the sheet for the team that owns the program and of the help: `'en'` or `'fr'`. `--language` replaces it for one command, `DB2KIT_LANGUAGE` for one person. Error messages and generated files stay in English ([cli.md](cli.md#language))                                                                                                                              |

## `connection`

| Key             | Type   | Required | CLI keyword     | Purpose                                                |
| :-------------- | :----- | :------- | :-------------- | :----------------------------------------------------- |
| `database`      | string | yes      | `DATABASE`      | Db2 location name                                      |
| `host`          | string | yes      | `HOSTNAME`      | Server host                                            |
| `port`          | number | yes      | `PORT`          | DRDA port, an integer from 1 to 65535                  |
| `user`          | string | yes      | `UID`           | User                                                   |
| `password`      | string | yes      | `PWD`           | Password, masked in every output                       |
| `currentSchema` | string | no       | `CURRENTSCHEMA` | Schema for unqualified objects                         |
| `extraKeywords` | object | no       | as is           | Other CLI keywords, for instance `{ SECURITY: 'SSL' }` |

A value containing `;`, `{` or `}` is automatically wrapped in braces.

`extraKeywords` follows the rules of the extra keywords variable: each name is a CLI keyword (letters, digits and `_`, case-insensitive), never one db2kit sets itself (`DATABASE`, `HOSTNAME`, `PORT`, `PROTOCOL`, `UID`, `PWD`, `CURRENTSCHEMA`, and `RECEIVETIMEOUT`, set by `pool.receiveTimeoutMs`), never twice, and each value is a non-empty string or a number. A keyword whose name holds `PWD` or `PASSWORD` is masked like the password.

### From environment variables, read at each new connection

`connectionFromEnv` puts in the configuration the **names** of the variables, never their values. db2kit reads them in `process.env` at startup, to check them, then again **at each new connection**: a value changed in the environment of the process (rotated password, corrected host) applies to the next connection, without restart.

```ts
// Variables of a prefix
connection: connectionFromEnv('DB_APP'),

// Or the variables the application already has, under their own names
connection: connectionFromEnv({
  database: 'DB2_LOCATION',
  host: 'DB2_HOST',
  port: 'DB2_PORT',
  user: 'DB2_USER',
  password: 'DB2_PASSWORD',
  currentSchema: 'DB2_SCHEMA', // optional
  extraKeywords: 'DB2_KEYWORDS', // optional
}),
```

| Variable with a prefix    | Explicit name   | Key                                                    | Required |
| :------------------------ | :-------------- | :----------------------------------------------------- | :------- |
| `<PREFIX>_DATABASE`       | `database`      | `database`                                             | yes      |
| `<PREFIX>_HOST`           | `host`          | `host`                                                 | yes      |
| `<PREFIX>_PORT`           | `port`          | `port`, an integer from 1 to 65535                     | yes      |
| `<PREFIX>_USERNAME`       | `user`          | `user`                                                 | yes      |
| `<PREFIX>_PASSWORD`       | `password`      | `password`                                             | yes      |
| `<PREFIX>_CURRENT_SCHEMA` | `currentSchema` | `currentSchema`, none when absent or empty             | no       |
| `<PREFIX>_EXTRA_KEYWORDS` | `extraKeywords` | `extraKeywords`, as `KEY=VALUE` pairs separated by `;` | no       |

These seven are the only variables db2kit reads. Another variable with the same prefix does nothing: `<PREFIX>_READ_ONLY=true`, for instance, leaves the application free to write. Read-only mode is `readOnly: true` in the configuration ([`readOnly`](#readonly)), and every other setting is a key of the configuration too.

What happens when:

| Moment                         | Behavior                                                                                                                                                                                                                |
| :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createDb2` (startup)          | Every missing or invalid variable is listed at once in a `Db2ConfigError`, with the other problems of the configuration. A name that is not a variable name, or an unknown key in the explicit form, is refused as well |
| New connection                 | The variables are read again. A missing or invalid one refuses this connection with a `Db2ConfigError` (audit code `CONFIG`), without any login. The next connection reads them again                                   |
| A value changed                | The next connection uses it. The logger of `createDb2` receives one warning that names the variables changed, never their values                                                                                        |
| Connections already open       | They keep the login they opened with until they close (idle timeout, broken connection, `db.close()`). A password rotation does not cut them                                                                            |
| `db.config.connection`         | Holds the names of the variables, not their values                                                                                                                                                                      |
| Error messages and audit trail | Name the variable, never its value. A faulty item of the extra keywords is named by its position, since its text could hold a secret                                                                                    |

db2kit reads `process.env` only, never a `.env` file at runtime. The operating system cannot change the environment of a running process from outside: a change reaches `process.env` only when the application writes it there. The `.env` file is not loaded automatically either: the CLI loads the file named by `cli.envFile` or given with `-e .env`, the application with its own mechanism (NestJS `ConfigModule`, `node --env-file`...).

To apply an edited `.env` file without restart, the application reloads it itself, for instance on a signal. `process.loadEnvFile()` does not do it: it keeps the variables already set. Parse the file and overwrite them:

```ts
import { readFileSync } from 'node:fs';
import { parseEnv } from 'node:util';

process.on('SIGHUP', () => {
  Object.assign(process.env, parseEnv(readFileSync('.env', 'utf8')));
});
```

A variable removed from the file stays in `process.env` with its old value: delete it explicitly if that matters.

With fixed values (`connection: { database: ..., password: ... }`, or `env('NAME')`, which reads a variable once), the settings are read once, at startup.

### Coming from a JDBC client (DBeaver)

DBeaver and other Java tools use the JDBC driver (JCC), whose properties have different names from the CLI keywords used by ibm_db. A connection that works in DBeaver tells nothing about the CLI settings until they match.

| JDBC property         | CLI keyword (`extraKeywords`)   | Meaning                                     |
| :-------------------- | :------------------------------ | :------------------------------------------ |
| `securityMechanism=3` | `AUTHENTICATION=SERVER`         | User and password sent in clear text        |
| `sslConnection=true`  | `SECURITY=SSL`                  | TLS connection, usually on a different port |
| `currentSchema`       | `currentSchema` (dedicated key) | Schema for unqualified objects              |

## `pool`

| Key                 | Default      | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| :------------------ | :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max`               | **required** | Maximum open connections. ibm_db enforces no limit: without this key, a burst of queries would open as many connections. How to size it: [production.md](production.md#3-pool-size). 1 for the CLI                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `min`               | 0            | Connections kept open at all times. 1 in production, so that the first request after a quiet period does not wait for a login                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `acquireTimeoutMs`  | 5000         | Maximum wait for a free connection, then `Db2PoolTimeoutError`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `connectTimeoutMs`  | 30000        | Maximum time to open a connection. Passed to the driver as its login timeout, rounded up to whole seconds                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `receiveTimeoutMs`  | 60000        | Longest time a statement may wait on Db2, sent as the CLI keywords `ReceiveTimeout` and `QueryTimeout`, in whole seconds rounded up (0 to 32767 s). Past it, the driver gives the connection up: the statement fails with `CONNECTION_LOST`, flagged `NO_REPLY` in the audit trail, and is never retried. Bounds a statement on a connection cut without notice (VPN) instead of the TCP timeout of the system, minutes. Set it above the slowest expected statement. 0: db2kit sets neither, the driver settings apply (no limit by default) ([production.md](production.md#8-connection-recovery)). Both keywords, since `ReceiveTimeout` alone was observed not to end a read whose network was cut without notice, and `QueryTimeout` did (Db2 13 for z/OS, ibm_db 4.0 on Windows: SQLSTATE 40003, the driver having dropped the connection). Neither may be set in the extra keywords |
| `idleTimeoutMs`     | 300000       | A connection idle for this long is closed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `breakerThreshold`  | 3            | Connection attempts failing on the network in a row after which Db2 counts as unreachable: requests needing a new connection, those already waiting for one included, fail at once with `Db2UnavailableError` ([production.md](production.md#8-connection-recovery))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `breakerMaxDelayMs` | 60000        | Longest delay between two attempts while Db2 is unreachable. The delay starts at 1 s and doubles after each failed attempt                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

On a cold pool, the first query waits for a connection to open. When `acquireTimeoutMs` is shorter than `connectTimeoutMs` and the server does not answer, that query fails with a `Db2PoolTimeoutError` saying a connection was still being opened, before the driver reports its own error. `doctor` and the integration tests wait longer than `connectTimeoutMs` on purpose, to show the driver error.

### Setting up the pool

A starting point, then adjusted from the audit trail:

```ts
// db2kit.config.mts
pool: process.env.NODE_ENV === 'production'
  ? {
      max: Number(process.env.DB2_POOL_MAX ?? 8), // sized by production.md, section 3, within the DBA quota
      min: 1, // one connection kept open: no login wait after a quiet period
      acquireTimeoutMs: 10000,
      connectTimeoutMs: 8000, // below acquireTimeoutMs: the driver error comes first
    }
  : { max: 4, acquireTimeoutMs: 15000, connectTimeoutMs: 10000 },
```

Three rules:

- **`max` is a load limit on the mainframe**, not only a performance setting: every instance of the application opens up to `max` connections, and they all count against the limits of the subsystem. Size it from the load and agree the total with the DBA ([production.md](production.md#3-pool-size)). The CLI needs 1.
- **`acquireTimeoutMs` above `connectTimeoutMs`.** Otherwise, when Db2 does not answer, every request fails with `POOL_TIMEOUT` ("a new connection was still being opened") for as long as the login lasts, up to `connectTimeoutMs`, and the network error of the driver comes only after it. Above it, the driver error comes first, counts for `breakerThreshold`, and the breaker opens within seconds rather than tens of seconds. Keep `connectTimeoutMs` well above the slowest login `doctor` measures from the same network.
- **`min: 1` in production.** With `0`, the pool closes every connection after `idleTimeoutMs`, and the first request after a quiet period waits for a login: a few seconds on z/OS, enough to pass a short `acquireTimeoutMs`.

**The threadpool of Node.js.** `ibm_db` runs every call on the libuv threadpool, 4 threads by default, shared with `fs`, `dns` and `crypto`. Set `UV_THREADPOOL_SIZE` to `max + 2` ([production.md](production.md#2-libuv-threadpool)). It is a variable of Node.js, not a key of db2kit, read once when the process starts:

- set it **in the environment that starts the process**, never in the code: `process.env.UV_THREADPOOL_SIZE = '10'` in `main.ts`, or a `.env` file the application loads (dotenv, the `ConfigModule` of NestJS), comes after the threadpool may have started, and has no reliable effect;
- in the scripts of `package.json`, the same on Windows and Linux with `cross-env`: `"start:prod": "cross-env UV_THREADPOOL_SIZE=10 node dist/main"`;
- in a PowerShell session: `$env:UV_THREADPOOL_SIZE = "6"; npm run start:dev`;
- in a container: `ENV UV_THREADPOOL_SIZE=10` in the Dockerfile, or `env:` of the container in a Kubernetes manifest.

`createDb2` and `doctor` warn when it is lower than `max + 2`. To keep the two values together, read `max` from a variable (`DB2_POOL_MAX` above) and set both variables side by side, where the process starts.

**What a request sees** when the pool cannot lend a connection, through the exception filter of `db2kit/nestjs` ([nestjs.md](nestjs.md)):

| Cause                                                    | Error and code                        | HTTP answer                                                |
| :------------------------------------------------------- | :------------------------------------ | :--------------------------------------------------------- |
| No connection within `acquireTimeoutMs`                  | `Db2PoolTimeoutError`, `POOL_TIMEOUT` | 503, "The database is busy. Try again later."              |
| `breakerThreshold` network failures in a row             | `Db2UnavailableError`, `UNAVAILABLE`  | 503 at once, with `Retry-After`, until an attempt succeeds |
| Login refused (SQL30082N), never tried again by the pool | `AUTHENTICATION_FAILED`               | 503, "The database is not available. Try again later."     |

The answer never carries a host, a statement nor a Db2 message; the log line of the audit trail holds the tag, the fingerprint, the statement with its markers and the counters of the pool. Those counters read: `used` connections lent, `free` open and waiting, `pending` requests waiting for one, `opening` logins in progress or waiting for their turn. All at 0 but `opening`: Db2 has not answered a login yet, a network or VPN matter as a rule, which `npx db2kit doctor` tells apart from a slow login. `used` equal to `max` with requests `pending`: the pool is saturated, look first for the statement that holds the connections. `db2HealthCheck` of `db2kit/nestjs` gives a readiness probe, so that a load balancer stops sending requests to an instance that cannot reach Db2.

### Protection of the account

Repeated failed logins can revoke a z/OS account (RACF). The pool limits them:

- until one login has succeeded with the settings in effect, logins are tried one at a time: with a wrong password, a burst of requests costs one failed login, not one per request. After a change of the settings (rotated password), logins are tried one at a time again until one succeeds;
- after an authentication failure (SQL30082N, code `AUTHENTICATION_FAILED`), the pool tries no login with the same settings again: every request that needs a new connection fails at once with that error. Connections already open keep working;
- with `connectionFromEnv`, changing a variable lifts that lock for **one** login with the new settings, one at a time again until a login succeeds. If it fails too, the new settings are locked in turn. Coming back to the settings that failed last does not try them again. Each attempt therefore needs a change of the variables: never a loop. With fixed values, or when the account itself was fixed without changing any variable, restart the application;
- a network error (SQL30081N) says nothing about the credentials: the next request tries again, until `breakerThreshold` failures in a row ([production.md](production.md#8-connection-recovery)).

The pool compares settings through a digest of the connection string: it keeps neither a failed password nor the previous one after a rotation.

Measured before this protection, with the fake driver: 4 parallel requests with a wrong password gave 7 failed logins. Now: 1.

Sizing: see [production.md](production.md).

## `query`

| Key                 | Default   | Purpose                                                                                                                                                                                                                                                   |
| :------------------ | :-------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultMaxRows`    | 1000      | Maximum rows read per result set when the call does not set `maxRows`                                                                                                                                                                                     |
| `onMaxRowsExceeded` | `'throw'` | `'throw'` raises `Db2MaxRowsError`. `'truncate'` cuts the result and flags it in the audit                                                                                                                                                                |
| `retryLostReads`    | true      | A pure read outside a transaction whose connection was lost runs once more on a new connection, flagged `RETRIED` in the audit trail. Never a write, a `CALL` nor a statement inside a transaction ([production.md](production.md#8-connection-recovery)) |

The limit protects Node memory. It does not replace `FETCH FIRST n ROWS ONLY` in the SQL, which limits the work done by Db2 itself.

## `types`

| Key        | Default | Purpose                                                                 |
| :--------- | :------ | :---------------------------------------------------------------------- |
| `trimChar` | true    | Strips trailing blanks from `CHAR` and `GRAPHIC` columns, padded by Db2 |

## `audit`

| Key                 | Default             | Purpose                                                                                                                                                                                                                                                                                                                                    |
| :------------------ | :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `applicationName`   | **required**        | Sent to Db2 (`CLIENT_APPLNAME`): the DBA sees which application consumes resources                                                                                                                                                                                                                                                         |
| `slowQueryMs`       | 200                 | Above this, the query is flagged as slow                                                                                                                                                                                                                                                                                                   |
| `params`            | `AuditParams.Types` | `AuditParams.None` (`'none'`): no parameter. `AuditParams.Types` (`'types'`): type and length, no data. `AuditParams.Full` (`'full'`): values, development only (personal data). Also the text of a Db2 error in the audit trail and in the log of `db2kit/nestjs`: kept with `'full'` only ([audit.md](audit.md#the-text-of-a-db2-error)) |
| `sinks`             | `[consoleSink()]`   | Event destinations, see [audit.md](audit.md)                                                                                                                                                                                                                                                                                               |
| `nPlusOneThreshold` | 10                  | Executions of the same query within one context above which an N+1 is reported                                                                                                                                                                                                                                                             |
| `refusals`          | false               | A call of the object API refused before sending adds an event, code `USAGE`, to the audit trail ([audit.md](audit.md#error-codes))                                                                                                                                                                                                         |

## `codegen`

| Key                   | Default             | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| :-------------------- | :------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `outDir`              | `src/db2/generated` | Folder of generated files and of `manifest.json`, relative to the configuration file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `largeTableRows`      | 100000              | Row count (`CARDF`) at or above which a generated table model counts as large: its filters must use an index. See [models.md](models.md#size-class)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `maxEstimatedRows`    | 10000               | Rows an indexed equality filter may read, by the catalog statistics, for the index guard to accept it on a large table. See [models.md](models.md#selectivity)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `projectInstructions` | `'AGENTS.md'`       | Instruction file of the project for code assistants, relative to the configuration file. `init` writes in it, and each `generate` keeps up to date, a short section between db2kit markers: the rules no assistant may break, and where the documentation and the `AGENTS.md` written next to the generated files are. The rest of the file is never touched. A file that does not exist is created only after a yes in a terminal. `doctor` warns while the section is missing or out of date. Another file for another assistant (`'CLAUDE.md'`, `'.github/copilot-instructions.md'`), or `false` to leave every file alone                                                                                                                                                                                                                                                                                                                                                                                                       |
| `importExtension`     | `'auto'`            | The extension of the relative imports in the files db2kit writes (`./X.generated`). `'auto'` reads the `tsconfig.json` and the `package.json` next to the configuration file: `'.ts'` when `rewriteRelativeImportExtensions` or `allowImportingTsExtensions` is set, `'.js'` for an ES module package (`"type": "module"`) whose `module` or `moduleResolution` is `node16` to `node20` or `nodenext`, none otherwise (CommonJS, a bundler, no `tsconfig.json`). No form fits every project: none is refused at `nodenext` in an ES module package, `.js` by a CommonJS Jest that looks for the `.js` file, `.ts` without one of the two settings. `'none'`, `'.js'` or `'.ts'` names it, when the `tsconfig.json` cannot be read or the project needs another. `doctor` shows the form in effect and why. The files db2kit rewrites take it at the next `generate`; the rule of a procedure and `relations.ts`, written once and owned by the team, keep their imports, and `generate` and `check` say when they have another form |

## `transactions`

| Key         | Default | Purpose                                                                                                                                                                   |
| :---------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `timeoutMs` | 10000   | Maximum duration of `db.$transaction`. Beyond it the transaction is rolled back to release its locks. Overridable per transaction, see [transactions.md](transactions.md) |

## `models`

Object API: `db.findMany`, `findFirst`, `findUnique`, `count`, `exists`, `aggregate`, `groupBy`. See [models.md](models.md).

| Key          | Default   | Purpose                                                                                                                                                                                                                               |
| :----------- | :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `maxTake`    | 1000      | Largest `take` accepted by `findMany`                                                                                                                                                                                                 |
| `indexGuard` | `'throw'` | A read of a large table whose filter cannot use any index: `'throw'` refuses it before sending, `'warn'` runs it with the `SCAN_RISK` audit warning. `allowScan` on a call, with the reason a person writes, accepts it in both cases |
| `writable`   | none      | Tables and views the object API may write, as `'SCHEMA.NAME'`. Every other model is read-only. See [models.md](models.md#writing)                                                                                                     |

## `procedures`

Stored procedures: `db.call` and the outcome rules. The success values live in each rule, written by `probe` ([procedures.md](procedures.md#success-values-written-by-probe)), or in a convention the rule names ([procedures.md](procedures.md#conventions)): `outcomeConvention`, a default every rule took without naming it, was removed in 0.22.0, and a configuration that still has it is refused with where its values go.

| Key             | Default | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :-------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultInputs` | none    | Inputs most procedures take, by catalog name of the parameter: a text, a number, `null`, or a function called at each call with `{ procedure, parameter, context }` (`context.user` set by `withDb2Context` or the NestJS interceptor). Applied to every procedure with an `IN` or `INOUT` parameter of that name, when the call leaves the property out: a value given by the call wins, an explicit `null` sends NULL. `generate` writes these properties as optional. See [procedures.md](procedures.md#inputs-every-procedure-takes)                               |
| `fieldStatus`   | none    | How the procedures report a status per field, built with `defineFieldStatus`: how outputs form one group per field and how a group is classified (accepted, warning, rejection). The default of every procedure: a rule takes it with `fieldStatus: null`, overrides it with its own `defineFieldStatus(...)`, or has none without the key. `generate` writes `fieldStatus: null` in the draft of a procedure it fits, and an example built from the outputs in the draft of one whose outputs come one per field. See [procedures.md](procedures.md#status-per-field) |
| `conventions`   | none    | The conventions of the programs, each built with `defineConvention` under a name: by catalog name, the success value of each status output, the values that mean a refusal (HTTP 422), the status per field (its own, or `null` for `fieldStatus` above). A rule takes one by its name, `convention: 'standard'`, and `add` proposes the one whose outputs a procedure has. See [procedures.md](procedures.md#conventions)                                                                                                                                             |

## `readOnly`

| Key        | Default | Purpose                                                          |
| :--------- | :------ | :--------------------------------------------------------------- |
| `readOnly` | false   | Refuses, before sending to Db2, anything that is not a pure read |

Refused: `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `CALL` of a procedure that modifies data (allowed through `db.call` for a procedure the catalog declares `READS SQL DATA`, `CONTAINS SQL` or `NO SQL`), DDL, `SET`, `LOCK`, and also reads that modify data (`SELECT ... FROM FINAL TABLE (INSERT ...)`, `NEXT VALUE FOR`). A statement starting with a comment is refused out of caution. The refusal raises `Db2UsageError` and shows up in the audit trail with code `USAGE`, without using a connection.

Use it for services that only read and for integration tests. It is not an absolute guarantee: only a Db2 account without write privileges is.

## Full example

```ts
import {
  AuditParams,
  ConsoleLevel,
  connectionFromEnv,
  consoleSink,
  defineConfig,
  defineFieldStatus,
  FieldGrouping,
  FieldVerdict,
  jsonlSink,
  statsSink,
} from 'db2kit';

export const stats = statsSink();

// The values of the project, never magic strings.
enum FieldCode {
  Accepted = '000',
  WarningPrefix = 'W',
}

export default defineConfig({
  connection: connectionFromEnv('DB_APP'),
  pool: {
    max: 8,
    min: 1,
    acquireTimeoutMs: 5000,
    receiveTimeoutMs: 60000, // above the slowest expected statement
    breakerThreshold: 3, // network failures in a row before Db2 counts as unreachable
    breakerMaxDelayMs: 60000,
  },
  query: { defaultMaxRows: 500, retryLostReads: true },
  audit: {
    applicationName: 'my-api',
    slowQueryMs: 200,
    params: AuditParams.Types, // or 'types'
    sinks: [
      consoleSink({ only: ConsoleLevel.SlowAndErrors }),
      jsonlSink({ path: 'logs/db2-audit.jsonl', retentionDays: 30 }), // see audit.md, Retention
      stats,
    ],
  },
  transactions: { timeoutMs: 10000 },
  models: { maxTake: 500, indexGuard: 'throw' },
  procedures: {
    // Inputs most procedures take, by catalog name: a value, or a function called at each call.
    defaultInputs: { REQUEST_HEADER: ({ context }) => context.user ?? '' },
    // How the procedures report a status per field (procedures.md, Status per field).
    fieldStatus: defineFieldStatus({
      group: { by: FieldGrouping.Suffix, parts: { code: '_CODE', message: '_TEXT' } },
      classify: [
        { when: { code: [FieldCode.Accepted, null] }, then: FieldVerdict.Ok },
        { when: { code: { startsWith: FieldCode.WarningPrefix } }, then: FieldVerdict.Warn },
        { when: {}, then: FieldVerdict.Reject },
      ],
    }),
  },
  codegen: { outDir: 'src/db2/generated' },
  cli: { envFile: '.env' }, // the CLI only: no -e at each command
});
```
