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();How it works
PostgreSQL Pool With Parameterized Queries keeps everything in the functions listRecentOrders and withTransaction.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Configuration comes from the environment — it reads DATABASE_URL, so the same code switches behavior between environments without edits.
The result comes back as an object carrying rows.
What to watch for
- Requires
pgas a package; the snippet will not run without it.
Putting it to use
The primary signature is async function listRecentOrders(customerId, limit = 25)
The file announces its steps in the output: idle client error:, found.
The call returns rows.
Core lines
const recent = await listRecentOrders('c-812');
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],
);
const client = await pool.connect();
Interactive Tools for This Topic
FAQ
- Does `listRecentOrders` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Are there third-party dependencies?
- `pg` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.