# Database Integrations

Comprehensive database instrumentation for MongoDB, PostgreSQL, MySQL, Redis, Prisma, and more.

## Capabilities

### MongoDB Integration

Automatic instrumentation for MongoDB operations.

```typescript { .api }
/**
 * Create MongoDB integration for automatic database operation tracing
 * @param options - MongoDB integration configuration options
 * @returns MongoDB integration instance
 */
function mongoIntegration(options?: MongoOptions): Integration;

/**
 * Create Mongoose integration for MongoDB ODM tracing
 * @param options - Mongoose integration configuration options
 * @returns Mongoose integration instance
 */
function mongooseIntegration(options?: MongooseOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { MongoClient } from "mongodb";
import mongoose from "mongoose";

// Initialize with MongoDB integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.mongoIntegration({
      operations: ["find", "insert", "update", "delete"], // Operations to trace
      captureQueries: true, // Include query details in spans
    }),
    Sentry.mongooseIntegration({
      captureQueries: true,
    }),
  ],
});

// MongoDB native driver - automatically traced
const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("myapp");

// These operations will create spans
const users = await db.collection("users").find({ active: true }).toArray();
await db.collection("users").insertOne({ name: "John", email: "john@example.com" });

// Mongoose - automatically traced
await mongoose.connect("mongodb://localhost:27017/myapp");

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  active: Boolean,
});
const User = mongoose.model("User", UserSchema);

// These operations will create spans
const activeUsers = await User.find({ active: true });
const newUser = await User.create({ name: "Jane", email: "jane@example.com" });
```

### PostgreSQL Integration

Automatic instrumentation for PostgreSQL operations.

```typescript { .api }
/**
 * Create PostgreSQL integration using pg driver
 * @param options - PostgreSQL integration configuration options
 * @returns PostgreSQL integration instance
 */
function postgresIntegration(options?: PostgresOptions): Integration;

/**
 * Create Postgres.js integration
 * @param options - Postgres.js integration configuration options
 * @returns Postgres.js integration instance
 */
function postgresJsIntegration(options?: PostgresJsOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { Pool } from "pg";
import postgres from "postgres";

// Initialize with PostgreSQL integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.postgresIntegration({
      captureQueries: true, // Include SQL queries in spans
      maxQueryLength: 1000, // Maximum query length to capture
    }),
    Sentry.postgresJsIntegration({
      captureQueries: true,
    }),
  ],
});

// pg driver - automatically traced
const pool = new Pool({
  user: "dbuser",
  host: "localhost",
  database: "myapp",
  password: "secret",
  port: 5432,
});

// These queries will create spans
const result = await pool.query("SELECT * FROM users WHERE active = $1", [true]);
await pool.query("INSERT INTO users (name, email) VALUES ($1, $2)", ["John", "john@example.com"]);

// postgres.js - automatically traced
const sql = postgres("postgres://username:password@localhost/database");

// These queries will create spans
const users = await sql`SELECT * FROM users WHERE active = ${true}`;
await sql`INSERT INTO users ${sql({ name: "Jane", email: "jane@example.com" })}`;
```

### MySQL Integration

Automatic instrumentation for MySQL operations.

```typescript { .api }
/**
 * Create MySQL integration using mysql driver
 * @param options - MySQL integration configuration options
 * @returns MySQL integration instance
 */
function mysqlIntegration(options?: MysqlOptions): Integration;

/**
 * Create MySQL2 integration using mysql2 driver
 * @param options - MySQL2 integration configuration options
 * @returns MySQL2 integration instance
 */
function mysql2Integration(options?: Mysql2Options): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import mysql from "mysql";
import mysql2 from "mysql2/promise";

// Initialize with MySQL integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.mysqlIntegration({
      captureQueries: true,
    }),
    Sentry.mysql2Integration({
      captureQueries: true,
      maxQueryLength: 1000,
    }),
  ],
});

// mysql driver - automatically traced
const connection = mysql.createConnection({
  host: "localhost",
  user: "me",
  password: "secret",
  database: "my_db",
});

// These queries will create spans
connection.query("SELECT * FROM users WHERE active = ?", [1], (error, results) => {
  if (error) throw error;
  console.log(results);
});

// mysql2 driver - automatically traced
const connection2 = await mysql2.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test",
});

// These queries will create spans
const [rows] = await connection2.execute("SELECT * FROM users WHERE active = ?", [1]);
await connection2.execute("INSERT INTO users (name, email) VALUES (?, ?)", ["John", "john@example.com"]);
```

### Redis Integration

Automatic instrumentation for Redis operations.

```typescript { .api }
/**
 * Create Redis integration for automatic Redis operation tracing
 * @param options - Redis integration configuration options
 * @returns Redis integration instance
 */
function redisIntegration(options?: RedisOptions): Integration;

/**
 * Create IORedis integration for automatic Redis operation tracing using ioredis
 * @param options - IORedis integration configuration options
 * @returns IORedis integration instance
 */
function ioredisIntegration(options?: IoredisOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { createClient } from "redis";

// Initialize with Redis integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.redisIntegration({
      captureCommands: true, // Include Redis commands in spans
      maxCommandLength: 100, // Maximum command length to capture
    }),
  ],
});

// Redis client - automatically traced
const client = createClient({
  url: "redis://localhost:6379",
});

client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();

// These operations will create spans
await client.set("key", "value");
const value = await client.get("key");
await client.hSet("user:123", { name: "John", email: "john@example.com" });
const user = await client.hGetAll("user:123");
```

### Prisma Integration

Automatic instrumentation for Prisma ORM operations.

```typescript { .api }
/**
 * Create Prisma integration for automatic ORM operation tracing
 * @param options - Prisma integration configuration options
 * @returns Prisma integration instance
 */
function prismaIntegration(options?: PrismaOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { PrismaClient } from "@prisma/client";

// Initialize with Prisma integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.prismaIntegration({
      captureQueries: true, // Include SQL queries in spans
    }),
  ],
});

// Prisma client - automatically traced
const prisma = new PrismaClient();

// These operations will create spans
const users = await prisma.user.findMany({
  where: { active: true },
});

const newUser = await prisma.user.create({
  data: {
    name: "John",
    email: "john@example.com",
    active: true,
  },
});

await prisma.user.update({
  where: { id: newUser.id },
  data: { active: false },
});
```

### SQL Server Integration

Automatic instrumentation for SQL Server operations using Tedious.

```typescript { .api }
/**
 * Create Tedious integration for SQL Server tracing
 * @param options - Tedious integration configuration options
 * @returns Tedious integration instance
 */
function tediousIntegration(options?: TediousOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { Connection, Request } from "tedious";

// Initialize with Tedious integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.tediousIntegration({
      captureQueries: true,
    }),
  ],
});

// Tedious connection - automatically traced
const config = {
  server: "localhost",
  authentication: {
    type: "default",
    options: {
      userName: "username",
      password: "password",
    },
  },
  options: {
    database: "mydatabase",
    encrypt: true,
  },
};

const connection = new Connection(config);

// These queries will create spans
const request = new Request("SELECT * FROM users WHERE active = @active", (err, rowCount) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`${rowCount} rows returned`);
  }
});

request.addParameter("active", TYPES.Bit, true);
connection.execSql(request);
```

### Knex.js Integration

Automatic instrumentation for Knex.js query builder.

```typescript { .api }
/**
 * Create Knex.js integration for query builder tracing
 * @param options - Knex integration configuration options
 * @returns Knex integration instance
 */
function knexIntegration(options?: KnexOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import knex from "knex";

// Initialize with Knex integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.knexIntegration({
      captureQueries: true,
    }),
  ],
});

// Knex instance - automatically traced
const db = knex({
  client: "postgresql",
  connection: {
    host: "localhost",
    port: 5432,
    user: "username",
    password: "password",
    database: "myapp",
  },
});

// These queries will create spans
const users = await db("users").where("active", true).select("*");
await db("users").insert({ name: "John", email: "john@example.com" });
await db("users").where("id", 1).update({ active: false });
```

### Additional Database Integrations

Additional database and connection pool integrations for specialized use cases.

```typescript { .api }
/**
 * Create Generic Pool integration for connection pool tracing
 * @param options - Generic Pool integration configuration options
 * @returns Generic Pool integration instance
 */
function genericPoolIntegration(options?: GenericPoolOptions): Integration;

/**
 * Create Dataloader integration for automatic batching and caching tracing
 * @param options - Dataloader integration configuration options
 * @returns Dataloader integration instance
 */
function dataloaderIntegration(options?: DataloaderOptions): Integration;

/**
 * Create AMQP integration for RabbitMQ message queue tracing
 * @param options - AMQP integration configuration options
 * @returns AMQP integration instance
 */
function amqplibIntegration(options?: AmqplibOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import DataLoader from "dataloader";
import amqp from "amqplib";

// Initialize with additional integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.genericPoolIntegration(),
    Sentry.dataloaderIntegration({
      captureKeys: true, // Include batch keys in spans
    }),
    Sentry.amqplibIntegration({
      captureMessages: true, // Include message content in spans
    }),
  ],
});

// DataLoader - automatically traced
const userLoader = new DataLoader(async (userIds) => {
  // Batch loading logic will be traced
  return fetchUsersByIds(userIds);
});

// AMQP - automatically traced
const connection = await amqp.connect("amqp://localhost");
const channel = await connection.createChannel();
await channel.assertQueue("task_queue");

// Publishing and consuming messages will create spans
await channel.sendToQueue("task_queue", Buffer.from("Hello World"));
```

## Types

### Integration Options

```typescript { .api }
interface MongoOptions {
  /** MongoDB operations to trace */
  operations?: string[];
  /** Include query details in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface MongooseOptions {
  /** Include query details in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface PostgresOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface PostgresJsOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface MysqlOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface Mysql2Options {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface RedisOptions {
  /** Include Redis commands in spans */
  captureCommands?: boolean;
  /** Maximum command length to capture */
  maxCommandLength?: number;
}

interface PrismaOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface TediousOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface KnexOptions {
  /** Include SQL queries in spans */
  captureQueries?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface IoredisOptions {
  /** Include Redis commands in spans */
  captureCommands?: boolean;
  /** Maximum command length to capture */
  maxCommandLength?: number;
}

interface GenericPoolOptions {
  /** Include pool operation details in spans */
  captureOperations?: boolean;
}

interface DataloaderOptions {
  /** Include batch keys in spans */
  captureKeys?: boolean;
  /** Maximum key count to capture */
  maxKeyCount?: number;
}

interface AmqplibOptions {
  /** Include message content in spans */
  captureMessages?: boolean;
  /** Maximum message length to capture */
  maxMessageLength?: number;
}
```