# Client API

Every method of the client returned by `createDb2`, in one place. Each links to the page that details it.

## `createDb2(config, options?)`

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

const db = createDb2(config, { logger });
```

- Checks the configuration and throws `Db2ConfigError` listing every problem at once ([configuration.md](configuration.md)). With `connectionFromEnv`, the variables are read now, then again at each new connection.
- Warns when `UV_THREADPOOL_SIZE` is too small for `pool.max` ([production.md](production.md#2-libuv-threadpool)).
- Does not connect: the first connection opens on the first statement.

| Option   | Default | Effect                                                                                                                                                                                                                     |
| :------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `logger` | console | Receives the warnings of the client: threadpool, connection settings changed, connection lost, Db2 unreachable and reachable again. Only `warn` is called. In NestJS, `new Logger('Db2')`, which `Db2Module` passes itself |
| `driver` | ibm_db  | Replaces ibm_db: the fake driver, a recording or a replay of `db2kit/testing` ([testing.md](testing.md)), or `ibmDbDriver()` wrapped by a recording. ibm_db is then never loaded                                           |

`config` is read from the configuration file of the project with `await loadConfigFile()` ([configuration.md](configuration.md#the-configuration-file)), never written again in the code. With NestJS, `Db2Module.forRootAsync` calls `createDb2` in its factory and closes the client at shutdown ([nestjs.md](nestjs.md)).

## Statements

| Method                                                                                                     | Returns                                                        | Details                                                                                                                           |
| :--------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| ``query(sql`...`, { tag, maxRows })``                                                                      | the rows of the first result set                               | Reads only: refuses `INSERT`, `UPDATE`, `DELETE`, `MERGE` and `CALL` ([queries.md](queries.md))                                   |
| ``queryOne(sql`...`, { tag })``                                                                            | one row, or `null`                                             | `Db2MaxRowsError` when there are several                                                                                          |
| ``execute(sql`...`, { tag })``                                                                             | the number of affected rows                                    | Writes only: refuses `SELECT` and `CALL`                                                                                          |
| `call(procedure, input, { tag, maxRows })`                                                                 | `{ output, resultSets, outcome, notice }`                      | A generated descriptor, with its input codecs and its outcome rule when it has them ([procedures.md](procedures.md))              |
| `findMany(model, args)`, `findFirst`, `findUnique`, `count`, `exists`, `aggregate`, `groupBy`, `findPages` | typed rows, one row or `null`, a number, a boolean, aggregates | The object API over generated models, with the index guard ([models.md](models.md))                                               |
| `compile.findMany(model, args)`, and every method of the object API                                        | `{ sql, params, warnings, includes }`, nothing sent            | The statement a call would send, every check included ([models.md](models.md#seeing-the-sql-dbcompile))                           |
| `$transaction(fn, { tag, timeoutMs })`                                                                     | what `fn` returns                                              | One connection, commit when `fn` resolves, rollback when it throws or after any error inside ([transactions.md](transactions.md)) |

`tag` labels the statement in the audit trail; without it, the tag of the current context applies. `maxRows` bounds the rows read per result set (default `query.defaultMaxRows`). Both are checked before any network call: a `tag` that is not a string, a `maxRows` that is not a positive integer, or an option the method does not take, raise `Db2UsageError`.

Inside `$transaction`, the callback receives `tx`, with the same statement methods and `tx.id`, the number of the transaction in the audit trail. A statement through `db` instead of `tx` inside the callback is refused: it would run on another connection, outside the transaction.

## Context

| Method                     | Effect                                                                                                                                                                                                                                                                                                                                     |
| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `withContext(context, fn)` | Runs `fn` within a context: `tag`, `correlationId` and `user`. Every statement started inside, even after `await`, carries the tag and the correlation id in the audit trail. `user` serves the functions of `procedures.defaultInputs` and is never audited. A nested context inherits from its parent. Also exported as `withDb2Context` |

The NestJS interceptor sets the context of each request by itself ([nestjs.md](nestjs.md#context-interceptor)).

## Connections and health

| Method        | Sends to Db2                                                                          | Returns                                                                                                                                                                                                                                                                           |
| :------------ | :------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ping()`      | one statement (`SELECT 1 AS OK FROM SYSIBM.SYSDUMMY1`), audited with `source: 'ping'` | the round trip in ms. Throws like any statement when Db2 does not answer                                                                                                                                                                                                          |
| `poolStats()` | nothing                                                                               | `{ used, free, pending, opening }`: borrowed connections, open and available ones, requests waiting for one, connections being opened. The same figures are in every audit event                                                                                                  |
| `health()`    | nothing                                                                               | `{ pool, connection }`: `pool` as `poolStats()`, `connection` with `state` (`closed`, `open`, `half-open`), `failures`, `since`, `retryAt`, `lostConnections` and `lastError` (code, SQLCODE, SQLSTATE, never the message) ([production.md](production.md#8-connection-recovery)) |
| `close()`     | the closing of each connection                                                        | Closes the pool and the audit sinks. Call it when the application shuts down: `Db2Module` does it on `app.close()`, and on a signal with `app.enableShutdownHooks()`                                                                                                              |

`config` holds the effective configuration, every default applied, frozen.

## Other exports

| Export                                                    | Use                                                                                                                |
| :-------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
| `ibmDbDriver()`                                           | The real driver, loading ibm_db at the first connection: to wrap with `recordingDriver` ([testing.md](testing.md)) |
| `sql`                                                     | The tag of every statement: values become markers ([queries.md](queries.md))                                       |
| `defineRelations`                                         | The relations of the generated models, in `relations.ts` ([models.md](models.md#relations))                        |
| `codecs`, `defineInputs`, `defineOutcome`                 | Input codecs and outcome rules of a procedure ([procedures.md](procedures.md))                                     |
| `defineFieldStatus`, `FieldGrouping`, `FieldVerdict`      | Status per field of the procedures ([procedures.md](procedures.md#status-per-field))                               |
| `defineConfig`, `connectionFromEnv`, `env`, `AuditParams` | The configuration file ([configuration.md](configuration.md))                                                      |
| `consoleSink`, `jsonlSink`, `statsSink`, `ConsoleLevel`   | Audit sinks ([audit.md](audit.md))                                                                                 |
| Error classes, `messageWithoutDb2Text`                    | [errors.md](errors.md)                                                                                             |
