> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monocle.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Kysely

> Trace database queries made through Kysely

This guide covers how to enable query tracing with Kysely and collect PostgreSQL pool metrics.

* Wrap your Kysely dialect to create query spans
* Control which query and error details are recorded
* Optionally collect PostgreSQL pool metrics

## Overview

`@monocle.sh/instrumentation-kysely` wraps a Kysely dialect and creates OpenTelemetry spans for database operations. It uses your active OpenTelemetry provider and must be configured in your application. The AdonisJS agent does not install or enable this package automatically.

## Installation

Install the instrumentation, Kysely, and the database driver used by your dialect. This package supports Kysely `^0.28.16`.

```bash title="Terminal" theme={"theme":"vesper"}
npm install @monocle.sh/instrumentation-kysely kysely@^0.28.16
```

Install the driver used by your Kysely dialect separately. The example below uses `pg`.

## Configure query tracing

Initialize OpenTelemetry before importing your database module. Wrap your existing dialect with `observeDialect()` and set `dbSystem` to identify the database.

```typescript title="app/services/database.ts" theme={"theme":"vesper"}
import pg from "pg";
import { Kysely, PostgresDialect } from "kysely";
import { observeDialect } from "@monocle.sh/instrumentation-kysely";

interface Database {
  users: { id: number; name: string };
}

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export const db = new Kysely<Database>({
  dialect: observeDialect({
    dialect: new PostgresDialect({ pool }),
    dbSystem: "postgresql",
  }),
});
```

The wrapper traces queries, streams, and transaction commands. If you also enable instrumentation for the underlying database driver, each query can produce a nested driver span. Disable one layer if you want a single span per query.

## Control captured data

Query text and database errors are recorded by default. Query text contains placeholders for bound parameters, but literal values in raw SQL remain in the statement. Error messages can also contain submitted values.

* Set `recordQueryText: false` to omit SQL statements. The default maximum length is 1,022 characters; use `maxQueryLength` to change it.
* Set `recordErrors: false` to omit exception details while keeping the span error status and type.
* Set `requireParentSpan: true` to trace database operations only when a parent span is active.
* Pass `connection` with `host`, `port`, and `database` to add database connection details to spans.

## PostgreSQL pool metrics

Call `registerPgPoolMetrics()` after initializing your metrics provider. It records used and idle connections and pending requests. Call the returned function during shutdown, before closing the pool.

```typescript title="app/services/database.ts" theme={"theme":"vesper"}
import pg from "pg";
import { registerPgPoolMetrics } from "@monocle.sh/instrumentation-kysely";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
const stopPoolMetrics = registerPgPoolMetrics({ pool, max: 10, poolName: "main" });

export async function shutdownDatabase() {
  stopPoolMetrics();
  await pool.end();
}
```
