← back to Hub
lib/db.ts
34 lines
import { Pool, QueryResult, QueryResultRow } from 'pg';
const pools: Record<string, Pool> = {
sdcc: new Pool({ connectionString: 'postgresql://dw_admin@127.0.0.1:5432/sdcc', max: 3 }),
grant: new Pool({ connectionString: 'postgresql://dw_admin@127.0.0.1:5432/grant_app', max: 3 }),
patty: new Pool({ connectionString: 'postgresql://dw_admin@127.0.0.1:5432/patty', max: 3 }),
freddy: new Pool({ connectionString: 'postgresql://dw_admin@127.0.0.1:5432/freddy', max: 3 }),
};
for (const [name, pool] of Object.entries(pools)) {
pool.on('error', (err) => console.error(`[db:${name}] Pool error:`, err.message));
}
export async function query<T extends QueryResultRow = QueryResultRow>(
db: string, text: string, params?: unknown[]
): Promise<QueryResult<T>> {
const pool = pools[db];
if (!pool) throw new Error(`Unknown database: ${db}`);
const start = Date.now();
try {
const result = await pool.query<T>(text, params);
const duration = Date.now() - start;
if (duration > 2000) {
console.warn(`[db:${db}] Slow query (${duration}ms):`, text.slice(0, 120));
}
return result;
} catch (err) {
console.error(`[db:${db}] Query error:`, (err as Error).message, '\n SQL:', text.slice(0, 200));
throw err;
}
}
export default pools;