PostgreSQL Pool With Parameterized Queries
Query PostgreSQL through a pg pool with always-parameterized statements, statement timeouts, idle client recycling, and pool sizing guidance.
Code
import pg from 'pg';
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
max: 20,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
statement_timeout: 10_000,
query_timeout: 12_000,
application_name: 'orders-service',
});
pool.on('error', (err) => console.error('idle client error:', err.message));
async function listRecentOrders(customerId, limit = 25) {
const { rows, rowCount } = await pool.query(
'SELECT id, total, created_at FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT $2',
[customerId, limit],
);
return { rows, rowCount };
}
async function withTransaction(fn) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await fn(client);
await client.query('COMMIT');
return result;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
const recent = await listRecentOrders('c-812');
console.log('found', recent.rowCount, 'orders');
await pool.end();Report a problem with this exampleOpens a pre-filled issue on GitHub.