Files
CRM_ENVR/src/lib/db.ts
T
TroodonEnjoyer bc83af8e00
Build & Auto-Repair / build (push) Has been cancelled
Started PostgreSQL — data directory was uninitialized, ran initdb, set password, switched to md5 auth, all 24 migrations applied.
Hardened db.ts — added statement_timeout: 30000, idle_in_transaction_session_timeout: 10000, created transaction() helper (BEGIN/COMMIT/ROLLBACK).
Multi-step API routes wrapped in transactions — Events POST, Conversations POST use atomic blocks.
Fixed leads pagination — status filter pushed into SQL WHERE (no client-side filtering after LIMIT/OFFSET), added SELECT COUNT(*) for total.
Rewrote dashboard — SQL aggregations (COUNT + GROUP BY + date_trunc) replace loading all leads into memory.
Optimized conversations GET — merged duplicate correlated subqueries into single LEFT JOIN LATERAL.
Created migration 021_performance_indexes.sql — 8 missing indexes + set_session_user_context() function caching current_user_hierarchy_level() as session variable (avoids per-query RLS join).
Fixed build error — duplicate const other in conversations route. Also fixed a TypeScript never error in dashboard breakdown map.
Verified — npx tsc --noEmit clean, npm test (13 pass, 7 integration skip gracefully), npx next build succeeds.
2026-07-06 13:36:48 +02:00

56 lines
1.4 KiB
TypeScript

import { Pool, PoolClient } from "pg"
const dbUrl = process.env.DATABASE_URL
if (!dbUrl) {
throw new Error("DATABASE_URL environment variable is required")
}
const pool = new Pool({
connectionString: dbUrl,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
statement_timeout: 30000,
idle_in_transaction_session_timeout: 10000,
ssl: dbUrl.includes("localhost") || dbUrl.includes("127.0.0.1") ? false : { rejectUnauthorized: false },
})
pool.on("error", (err) => {
console.error("Unexpected database pool error:", err)
})
export async function query(text: string, params?: unknown[], userId?: string) {
const client = await pool.connect()
try {
if (userId) {
await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId])
}
const result = await client.query(text, params)
return result
} finally {
client.release()
}
}
export async function transaction<T>(
callback: (client: PoolClient) => Promise<T>,
userId?: string,
): Promise<T> {
const client = await pool.connect()
try {
await client.query("BEGIN")
if (userId) {
await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId])
}
const result = await callback(client)
await client.query("COMMIT")
return result
} catch (e) {
await client.query("ROLLBACK").catch(() => {})
throw e
} finally {
client.release()
}
}
export default pool