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-sql-strings

v1.0.8

Published

Postgres parametrized query builder

Downloads

42

Readme

Postgres parametrized query builder

Usage:

At first, let`s create simple wrapper, that provides convenient query interface

// create postgres pool
import { Statement } from "pg-sql-strings";

const pool = new Pool({
    connectionString: 'postgres://user:pass@localhost:5432/db'
});

// prepare your own query interface
async function query<T>(statement: Statement) {
    const { rows, rowCount } = await pool.query<T>(statement);
    return [rows, rowCount];
}

// also, we can create handy interface to interact with transactions
export async function transaction() {
    const connection = await pool.connect();
    return {
        begin: () => connection.query('BEGIN'),
        commit: () => connection.query('COMMIT'),
        rollback: () => connection.query('ROLLBACK'),
        release: () => connection.release(),
        query: async <T>(statement: Statement) => {
            const { rows, rowCount } = await connection.query<T>(statement);
            return [rows, rowCount];
        },
    };
}

Simple statement:

import { sql } from "pg-sql-strings";

const number = 99
const statement = sql`SELECT 1 + ${number} AS sum`

const [rows] = await query(statement)
console.log(rows) // returns [ { sum: 100 } ]

Append statement:

import { sql, query } from "pg-sql-strings";
const params = { age: 18 }

const statement = sql`SELECT name, age FROM users`

if (params.age) {
    statement.append(sql`WHERE age > ${params.age}`)
}

const [rows] = await query(statement)
console.log(rows) // returns [ { name: 'Mary', age: 39 }, { name: 'Ingvar', age: 27 } ]

Join statement:

import { sql, transaction } from "pg-sql-strings";

const params = { age: 18, name: 'Lo' }

const statement = sql`SELECT name, age FROM users`
const conditions = []

if (params.age) {
    conditions.push(sql`age > ${params.age}`)
}

if (params.name) {
    conditions.push(sql`name iLike ${params.name + '%'}`)
}

if (conditions.length) {
    statement.append(sql`WHERE`)
    statement.join(conditions, 'AND')
}

const [rows] = await query(statement)
console.log(rows) // returns [ { name: 'Lotar', age: 19 } ]

Transactional statement:

import { sql, transaction } from "pg-sql-strings";

const { begin, rollback, release, query } = await transaction()

try {
    await begin()
    const params = {
        id: 1,
        age: 30
    }
    const statement = sql`UPDATE users SET age = ${params.age}`

    if (params.id) {
        statement.append(sql`WHERE id = ${params.id}`)
    }

    statement.append(sql`RETURNING *`)

    const [rows] = await query(statement)
    console.log(rows) // returns [ { id: 1, name: 'John', age: 30 } ]
} catch (error) {
    // handle error
    await rollback()
} finally {
    await release()
}