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

pg-client-helper

v1.1.0-beta.0

Published

Postgres Client Helper providing named param objects, connection pooling

Downloads

613

Readme

pg-client-helper

A Postgres pg client based helper which:

  • provides async query functions explicitly returning multiple rows, a single row, a scalar value or nothing
  • allows you to write SQL queries with named parameters (instead of positional parameters)
  • handles your connections
  • supports transactions (since v1.1.0)

Logging

pg-client-helper logs out certain events. To control the level use the PG_CLIENT_HELPER_LOGLEVEL environment variable. Valid values are:

  • DEBUG
  • INFO
  • WARN
  • ERROR
  • SILENT (default)

Query Functions

pg-client-helper provides the following async query functions:

| Function Name | Description | Suitable for | | ----------------- | ------------------------------------------ | ---------------------------------------------------------- | | queryMultiple | returns an array of rows | SELECT * FROM public.users | | querySingle | returns the first row as an object | SElECT * FROM public.users WHERE id_users = 1337 | | queryScalar | returns the first value of the first row | SELECT user_name FROM public.users WHERE id_users = 1337 | | query | return null | DELETE FROM public.users WHERE id_users = 1337 |

Named Parameters

You can provide named parameters in your query and the params object. These parameters must start with a Dollar sign ($).

Example:

import * as PG from "pg-client-helper";

const query = `
    INSERT INTO public.users (
        user_name
        , email_address
        , active
    )
    VALUES (
        $user_name
        , $email_address
        , $active
    )`;

const params = {
  $user_name: "John Doe",
  $email_address: "[email protected]",
  $active: true,
};

PG.query(query, params);

pg-client-helper

  • takes your params object
  • iterates through all properties sorted descending by the length of their names
  • builds up the params array as expected by the pg client
  • replaces all occurences of the property name with the index expected by the pg client

So ultimately the query run with pg will be:

pg.query(
  `    INSERT INTO public.users (
        user_name
        , email_address
        , active
    )
    VALUES (
        $2
        , $1
        , $3
    )`,
  ["[email protected]", "John Doe", true]
);

If an attribute of your params object is an Array, pg-client-helper will spread the content of the array into the parameter list.

Example:

import * as PG from "pg-client-helper";

const query = `SELECT * FROM public.users WHERE id_users IN ($id_users)`;

const params = {
  $id_users = [13, 666, 1337]
};

PG.queryMultiple(query, params);

pg-client-helper spreads the content of the $id_users array into the parameter list.

So ultimately the query run with pg will be:

pg.query(
  `SELECT * FROM public.users WHERE id_users IN ($1, $2, $3)`,
  [13, 666, 1337]
);

pg-client-helper is backwards compatible to the default pg parameter list:

import * as PG from "pg-client-helper";

const query = `
    INSERT INTO public.users (
        user_name
        , email_address
        , active
    )
    VALUES (
        $1
        , $2
        , $3
    )`;

PG.query(query, ["John Doe", "[email protected]", true]);

Connection Handling

pg-client-helper manages your database connection by utilizing connection pooling. It also supports connections to AWS RDS via IAM using AWS Signer.

If you want to use transactions, please use the following approach:

import * as PG from "pg-client-helper";

async function myfunc() {
  const client: any = PG.beginTransaction();  // begins the transaction and returns a client to be used for ALL 

  try {
    // 1st query
    const $id_mytable1 = await PG.query(
      `INSERT INTO mytable1 (val1) VALUES 'foo' RETURNING id_mytable1`
    );

    // 2nd query
    const $id_mytable2 = await PG.query(
      `INSERT INTO mytable2 (id_mytable1, val2) VALUES ($id_mytable1, 'bar')`,
      { $id_mytable1 }
    );

    // 3rd query
    await PG.query(
      `UPDATE mytable3 SET val3 = 'baz' WHERE id_mytable1 = $id_mytable1 AND id_mytable2 = $id_mytable2`,
      { $id_mytable1, $id_mytable2 }
    );

    await PG.commitTransaction(client); // commits all changes made since beginTransaction
  } catch (error) {
    if (client) {
      await PG.rollbackTransaction(client); // we faced an error after beginTransaction, roll back all changes since then
    }
  }
}

| Environment Variable | Description | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PGHOST | (Mandatory) The hostname of your PostgreSQL server. This could be a local hostname, IP address, or a remote server address. | | PGPORT | (Mandatory) The port number on which your PostgreSQL server is running. The default PostgreSQL port is 5432. | | PGUSER | (Mandatory) The username you wish to authenticate with when connecting to your PostgreSQL server. | | PGDATABASE | (Mandatory) The name of the database you want to connect to on your PostgreSQL server. | | PGPASSWORD | (Optional) The password associated with the provided PGUSER. If using PG_USE_AWS_RDS_SIGNER (see below), this is replaced by the IAM authentication. | | PG_SSL_REQUIRED | (Optional) If set to true, SSL will be required for connections. This helps ensure encrypted connections for added security. | | PG_SSL_ALLOW_SELFSIGNED | (Optional) If set to true, self-signed SSL certificates will be allowed, which can be useful in development or internal network scenarios. It's generally recommended to use certified SSL certificates in production. | | PG_USE_AWS_RDS_SIGNER | (Optional) If set to true, the module will use AWS RDS Signer for IAM-based authentication to your RDS database. This means PGPASSWORD is not required as authentication is handled by the IAM role. |