npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

postgres-pool

v9.0.3

Published

Node postgres connection pool implementation for node-pg

Downloads

13,249

Readme

postgres-pool

NPM version node version Known Vulnerabilities

Connection pool implementation for pg. Compatible with pg-pool options and syntax.

Why?

Getting Started

Simple query (automatically releases connection after query - recommended)

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
});

const userId = 42;
const results = await pool.query('SELECT * from "users" where id=$1', [userId]);

console.log('user:', results.rows[0]);

Using named parameters in the query

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
});

const userId = 42;
const results = await pool.query('SELECT * from "users" where id=@id', {
  id: userId,
});

console.log('user:', results.rows[0]);

More control over connections (not recommended)

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
});

const userId = 42;
const connection = await pool.connect();
try {
  const results = await connection.query('SELECT * from "users" where id=$1', [userId]);
  console.log('user:', results.rows[0]);
} finally {
  // NOTE: You MUST call connection.release() to return the connection back to the pool
  await connection.release();
}

Handle errors from connections in the pool

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
});

pool.on('error', (err) => {
  console.error('Unexpected error on idle client', err);
  process.exit(-1);
});

Graceful shutdown

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
});

await pool.end();

Explicit connection details instead of a connection string

import { Pool } from 'postgres-pool';

const pool = new Pool({
  host: '127.0.0.1',
  database: 'db_name',
  user: 'foo',
  password: 'bar',
  port: 1234,
});

AWS RDS specific TLS settings for connections

Setting ssl='aws-rds' will:

  • configure the AWS root certificate
  • reject any connection which is not authorized with the list of supplied CAs.
  • attempt to use TLSv1.2 as the minimum TLS version.

It is the same as:

import { Pool } from 'postgres-pool';

const pool = new Pool({
  ssl: {
    rejectUnauthorized: true,
    ca: fs.readFileSync('./certs/rds-global-bundle.pem'),
    minVersion: 'TLSv1.2',
  },
});
import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
  ssl: 'aws-rds',
});

TLS details for a connection

import { Pool } from 'postgres-pool';

const pool = new Pool({
  host: '127.0.0.1',
  database: 'db_name',
  user: 'foo',
  password: 'bar',
  port: 1234,
  ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
    key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),
    cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),
  },
});

Change size of the pool

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
  poolSize: 10, // Default is 10 connections
});

Change retry on error settings

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
  // Number of retries to attempt when there's an error matching `retryConnectionErrorCodes`. A value of 0 will disable connection retry.
  retryConnectionMaxRetries: 5,
  // Milliseconds to wait between retry connection attempts after receiving a connection error with code that matches `retryConnectionErrorCodes`. A value of 0 will try reconnecting immediately.
  retryConnectionWaitMillis: 100,
  // Error codes to trigger a connection retry.
  retryConnectionErrorCodes: ['ENOTFOUND', 'EAI_AGAIN'],
});

Change timeout thresholds

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
  // Time to keep a connection idle. Default is 10s
  idleTimeoutMillis: 10000,
  // Time to wait to obtain a connection from the pool. Default is 90s
  waitForAvailableConnectionTimeoutMillis: 90000,
  // Max time to connect to postgres. Default is 5s
  connectionTimeoutMillis: 5000,
});

Handle cluster failover gracefully

When a cluster has a failover event, promoting a read-replica to master, there can be a couple sets of errors that happen with already established connections in the pool as well as new connections before the cluster is available in a ready state.

By default, when making a new postgres connection and the server throws an error with a message like: the database system is starting up, the postgres-pool library will attempt to reconnect (with no delay between attempts) for a maximum of 90s.

Similarly, if a non-readonly query (create/update/delete/etc) is executed on a readonly connection, the server will throw an error with a message like: cannot execute UPDATE in a read-only transaction. This can occur when a connection to a db cluster is established and the cluster fails over before the connection is terminated, thus the connected server becomes a read-replica instead of the expected master. The postgres-pool library will attempt to reconnect (with no delay between attempts) for a maximum of 90s and will try to execute the query on the new connection.

Defaults can be overridden and this behavior can be disabled entirely by specifying different values for the pool options below:

import { Pool } from 'postgres-pool';

const pool = new Pool({
  connectionString: 'postgres://username:[email protected]/db_name',
  // Enable/disable reconnecting on "the database system is starting up" errors
  reconnectOnDatabaseIsStartingError: true,
  // Milliseconds to wait between retry connection attempts while the database is starting up
  waitForDatabaseStartupMillis: 0,
  // If connection attempts continually return "the database system is starting up", this is the total number of milliseconds to wait until an error is thrown.
  databaseStartupTimeoutMillis: 90000,
  // If the query should be retried when the database throws "cannot execute X in a read-only transaction"
  reconnectOnReadOnlyTransactionError: true,
  // Milliseconds to wait between retry queries while the connection is marked as read-only
  waitForReconnectReadOnlyTransactionMillis: 0,
  // If queries continually return "cannot execute X in a read-only transaction", this is the total number of milliseconds to wait until an error is thrown
  readOnlyTransactionReconnectTimeoutMillis: 90000,
  // If the query should be retried when the database throws "Client has encountered a connection error and is not queryable"
  reconnectOnConnectionError: true,
  // Milliseconds to wait between retry queries after receiving a connection error
  waitForReconnectConnectionMillis: 0,
  // If queries continually return "Client has encountered a connection error and is not queryable", this is the total number of milliseconds to wait until an error is thrown
  connectionReconnectTimeoutMillis: 90000,
});

Compatibility

  • Node.js v16 or above

License

MIT