# Database API

Every export of kitr/db, with its signature.

Every export of `kitr/db`, read from the published type definitions. The [guide](/packages/db) shows them in use.

## kitr/db

### defineDb

```ts
function defineDb<T>(definition: DbDefinition<T>): DbDefinition<T>;
```

Declares how the app connects to its database, in `config/db.ts`. Returns the definition
unchanged; it exists so `disconnect` and `onReady` receive the client type `connect` returns.

### useDb

```ts
function useDb<T>(app: KitrApp): T;
```

Returns the connected client from an app's container, typed as `T`: `useDb<AppDb>(ctx.app)`.
Throws when the app has no `db` binding, or when an async `connect` has not finished (call it after `app.boot()`).

### dbProvider

```ts
const dbProvider: KitrProvider;
```

The provider `kitr add db` puts in `kitrrc.ts`. It binds `db` in the container from `config/db.ts`,
connects during boot, runs `onReady` when the server is ready and `disconnect` on shutdown.

### defineConfig

```ts
const defineConfig: <const C extends DbDefinition<any>>(config: C) => C;
```

Untyped alias of `defineDb` for the `defineConfig` convention; prefer `defineDb`, which infers the client type.

### DbDefinition

```ts
interface DbDefinition<T> {
  /** Opens the connection and returns the client. Runs once during `app.boot()`; a rejection fails boot. */
  connect: (app: KitrApp) => T | Promise<T>;
  /** Closes the client when the server shuts down (SIGINT, SIGTERM or `server.close()`). */
  disconnect?: (db: T, app: KitrApp) => void | Promise<void>;
  /** Runs once the server is ready to serve, after boot. Use it to check for pending migrations or warm a pool. */
  onReady?: (db: T, app: KitrApp) => void | Promise<void>;
}
```

kitr ships no ORM. `defineDb` binds whatever you use (Drizzle, Prisma, Kysely,
a raw pool) as `db` in the container with connect/disconnect in the lifecycle.

```ts
// config/db.ts
export default defineDb({ connect: () => drizzle(process.env.DATABASE_URL!), disconnect: (db) => db.$client.end() })
```

<!-- GENERATED by scripts/api-docs.mjs from the type definitions. Do not edit. -->
