{"library":"pg","title":"Node-Postgres Client (pg)","description":"pg (node-postgres) is a robust and non-blocking PostgreSQL client for Node.js, providing both a pure JavaScript implementation and optional native `libpq` bindings, both exposing the exact same API. Currently at version 8.20.0, the library maintains an active development pace with regular updates and bug fixes, indicated by its consistent major version releases and community support. Key features include efficient connection pooling, extensible data-type coercion between JavaScript and PostgreSQL types, support for parameterized queries to prevent SQL injection, named statements with query plan caching, and asynchronous notifications via `LISTEN/NOTIFY`. It also facilitates bulk data operations using `COPY TO/COPY FROM`. Its design prioritizes being a light abstraction layer, encouraging users to leverage companion modules for higher-level ORM or query building needs.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install pg"],"cli":null},"imports":["import { Pool } from 'pg';","import { Client } from 'pg';","import { types } from 'pg';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { Pool } from 'pg';\nimport dotenv from 'dotenv';\n\ndotenv.config();\n\nconst pool = new Pool({\n  connectionString: process.env.DATABASE_URL ?? 'postgresql://user:password@localhost:5432/mydb',\n  ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : undefined, // Adjust SSL for production\n});\n\nasync function queryDatabase() {\n  let client;\n  try {\n    client = await pool.connect(); // Acquire a client from the pool\n    const res = await client.query('SELECT $1::text as message, NOW() as currentTime;', ['Hello from pg!']);\n    console.log('Query result:', res.rows[0].message);\n    console.log('Current DB Time:', res.rows[0].currenttime);\n\n    const insertRes = await client.query('INSERT INTO users(name, email) VALUES($1, $2) RETURNING id;', ['John Doe', 'john.doe@example.com']);\n    console.log('Inserted user with ID:', insertRes.rows[0].id);\n\n    const usersRes = await client.query('SELECT * FROM users WHERE email = $1;', ['john.doe@example.com']);\n    console.log('Found user:', usersRes.rows[0]);\n\n  } catch (err) {\n    console.error('Database operation failed:', err);\n    process.exit(1);\n  } finally {\n    if (client) {\n      client.release(); // Release the client back to the pool\n      console.log('Client released.');\n    }\n  }\n}\n\nasync function setupDatabase() {\n  const setupClient = await pool.connect();\n  try {\n    console.log('Setting up database...');\n    await setupClient.query(`\n      CREATE TABLE IF NOT EXISTS users (\n        id SERIAL PRIMARY KEY,\n        name VARCHAR(100) NOT NULL,\n        email VARCHAR(100) UNIQUE NOT NULL,\n        created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n      );\n    `);\n    console.log('Table \"users\" ensured.');\n  } catch (err) {\n    console.error('Database setup failed:', err);\n  } finally {\n    setupClient.release();\n  }\n}\n\nsetupDatabase().then(() => queryDatabase().then(() => pool.end()));\n","lang":"typescript","description":"This quickstart demonstrates how to use `pg` with connection pooling, parameterized queries for safety, and basic database setup/teardown. It utilizes environment variables for configuration and handles connection acquisition and release from the pool.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}