{"library":"pg-pool","title":"PostgreSQL Connection Pool","description":"pg-pool is a specialized connection pooling library for Node.js applications using `node-postgres` to interact with PostgreSQL databases. Currently stable at version 3.13.0, it is actively maintained as part of the `node-postgres` family, with releases typically aligning with updates to the core `pg` client. This library is designed to improve application performance and reliability by managing a set of reusable database connections, thus reducing the overhead of repeatedly establishing and tearing down connections. Key features include configurable connection limits (`max`), idle timeouts (`idleTimeoutMillis`), connection establishment timeouts (`connectionTimeoutMillis`), and the ability to replace connections after a certain number of uses (`maxUses`). A crucial differentiator from some other database clients is that `pg-pool` does not directly accept a database URL string; instead, developers must parse the URL into a configuration object before passing it to the Pool constructor. It offers a modern, promise-based API that integrates smoothly with `async/await` patterns, simplifying resource management (client acquisition and release) compared to manual connection handling. It also supports pooling both the standard `pg.Client` and `pg.native.Client` instances.","language":"javascript","status":"active","last_verified":"Tue Apr 21","install":{"commands":["npm install pg-pool"],"cli":null},"imports":["const Pool = require('pg-pool')","import Pool from 'pg-pool'","import type Pool from 'pg-pool'"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"const Pool = require('pg-pool');\nconst { URL } = require('url'); // Node.js built-in URL parser\n\n// In a real application, ensure process.env.DATABASE_URL is set,\n// e.g., DATABASE_URL=postgres://user:password@localhost:5432/mydatabase\nconst databaseUrl = process.env.DATABASE_URL || 'postgres://testuser:testpass@localhost:5432/testdb';\n\nconst params = new URL(databaseUrl);\nconst auth = params.username && params.password ? params.username.split(':') : [params.username, params.password];\n\nconst config = {\n  user: auth[0],\n  password: auth[1],\n  host: params.hostname,\n  port: parseInt(params.port || '5432'), // Default PostgreSQL port\n  database: params.pathname.split('/')[1],\n  ssl: params.protocol === 'https:' || (process.env.NODE_ENV === 'production' && databaseUrl.includes('sslmode=require')), // Use SSL in production or if protocol specifies\n  max: 10, // Max clients in the pool\n  idleTimeoutMillis: 30000, // Close idle clients after 30 seconds\n  connectionTimeoutMillis: 2000, // Return error after 2 seconds if connection not established\n};\n\nconst pool = new Pool(config);\n\n(async () => {\n  let client;\n  try {\n    // Acquire a client from the pool\n    client = await pool.connect();\n    console.log('Client acquired from pool.');\n\n    // Execute a query using the client\n    const res = await client.query('SELECT $1::text as message', ['Hello from pg-pool with async/await!']);\n    console.log('Query result:', res.rows[0].message);\n\n    // Demonstrate direct pool.query (acquires, queries, and releases client automatically)\n    const timeRes = await pool.query('SELECT NOW() as current_time');\n    console.log('Current database time via direct query:', timeRes.rows[0].current_time);\n\n  } catch (err) {\n    console.error('Database operation failed:', err.message, err.stack);\n  } finally {\n    // Release the client back to the pool to prevent resource leaks\n    if (client) {\n      client.release();\n      console.log('Client released back to pool.');\n    }\n    // It's good practice to end the pool when the application is shutting down\n    // For a quickstart, we end it here, but in a real app it's usually on process exit.\n    await pool.end();\n    console.log('Pool has been ended.');\n  }\n})();","lang":"javascript","description":"This quickstart demonstrates how to initialize `pg-pool` by parsing a database URL, acquire and release clients using `async/await`, and use the convenient `pool.query` helper, along with proper error handling and pool shutdown.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}