Performance: PostgreSQL connection with pg
This affects the initial page load speed and responsiveness by controlling how database queries impact server response time.
import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); async function fetchData() { const res = await pool.query('SELECT * FROM users'); return res.rows; }
import { Client } from 'pg'; async function fetchData() { const client = new Client({ connectionString: process.env.DATABASE_URL }); await client.connect(); const res = await client.query('SELECT * FROM users'); await client.end(); return res.rows; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| New client per query | N/A | N/A | N/A | [X] Bad |
| Connection pool reuse | N/A | N/A | N/A | [OK] Good |
pg library in Node.js?pgpg library is designed specifically to connect Node.js applications to PostgreSQL databases.pg library?pg library requires creating a new Client instance using new pg.Client() with a config object.new pg.Client({ connectionString: ... }). Options B, C, and D use invalid syntax or methods that do not exist.const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });
async function run() {
await client.connect();
const res = await client.query('SELECT 1 AS number');
console.log(res.rows[0].number);
await client.end();
}
run();SELECT 1 AS number returns one row with a column named 'number' having value 1.res.rows[0].number, which accesses the first row's 'number' field, so it prints 1.pg to connect to PostgreSQL:const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });
client.connect();
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
client.end();client.connect() method returns a promise and must be awaited to ensure connection before querying.await before client.query() is correct. Calling client.end() after query is also correct.pg that connects to PostgreSQL, runs a query, and always closes the connection even if an error occurs. Which pattern is best?client.end() is called in the finally block.Pass the test and this pattern moves unknown