Overview
Use Drizzle ORM with NestJS. Includes connection pool and transaction support.
Features
- PostgreSQL connection pool
- Transaction helper
- Raw SQL execution
- Health check
Installation
npx hanma add drizzle-service --framework nest
Dependencies
drizzle-orm, pg
Code
import {
Injectable,
OnModuleInit,
OnModuleDestroy,
Logger,
} from "@nestjs/common";
import { drizzle, NodePgDatabase } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
@Injectable()
export class DrizzleService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(DrizzleService.name);
private pool: Pool;
public db: NodePgDatabase;
async onModuleInit() {
this.pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: parseInt(process.env.DB_POOL_SIZE || "10", 10),
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
});
this.pool.on("error", (err) => {
this.logger.error("Unexpected error on idle client", err);
});
this.db = drizzle(this.pool);
try {
await this.pool.query("SELECT 1");
this.logger.log("Successfully connected to database");
} catch (error) {
this.logger.error("Failed to connect to database", error);
throw error;
}
}
async onModuleDestroy() {
await this.pool.end();
this.logger.log("Disconnected from database");
}
async isHealthy(): Promise<boolean> {
try {
await this.pool.query("SELECT 1");
return true;
} catch {
return false;
}
}
// Execute raw SQL
async executeRaw<T = unknown>(
sql: string,
params: unknown[] = []
): Promise<T[]> {
const result = await this.pool.query(sql, params);
return result.rows as T[];
}
// Transaction helper
async transaction<T>(
fn: (tx: NodePgDatabase) => Promise<T>
): Promise<T> {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
const txDb = drizzle(client);
const result = await fn(txDb);
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
}
Usage
constructor(private drizzle: DrizzleService) {}
const users = await this.drizzle.db.select().from(users);
Dependencies
drizzle-ormpg
Frequently Asked Questions
How do I install Drizzle Service?
Run the following command:
npx hanma add drizzle-service --framework nestWhat dependencies are required?
This snippet requires: drizzle-orm, pg. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/providers/drizzle.service.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.