PostgreSQL Pool Parameterized Query
Use pg Pool for parameterized queries with connection pooling transaction support and error handling.
Code
import{Pool}from'pg';export function createPool(config){const pool=new Pool(config);async function query(text,params){const client=await pool.connect();try{return await client.query(text,params);}finally{client.release();}}async function transaction(fn){const client=await pool.connect();try{await client.query('BEGIN');const result=await fn(client);await client.query('COMMIT');return result;}catch(e){await client.query('ROLLBACK');throw e;}finally{client.release();}}return{query,transaction,end:()=>pool.end()};}How it works
PostgreSQL Pool Parameterized Query comes down to the functions createPool, query and transaction.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. From pg it pulls Pool — the imports name exactly which library surface the snippet touches.
The result comes back as an object carrying query, transaction.
What to watch for
- Plan for an install step:
pgis a real dependency, resolved by the package manager.
Using it
The primary signature is export function createPool(config)
Treat createPool as the API: import it, and ignore the supporting code.
The call returns query, transaction — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `pg`, which the package manager must provide.
- What does `createPool` return?
- An object carrying `query`, `transaction`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.