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

@jliuhtonen/pg-literally

v0.2.1

Published

SQL template tags and fragments for PostgreSQL

Downloads

5

Readme

pg-literally 📚

SQL template tag literals and SQL fragments for Node and Postgres. Compatible with node-pg and pg-promise.

Why?

It's best to use parameterized queries to prevent SQL injection attacks instead of escaping the interpolated values in your application or library code. However, you need to provide values for your queries and doing that separately clumsy. This library provides a way to build parametrized queries from tagged template literals.

There are also some nice tools for formatting SQL queries in template tag literals like prettier-plugin-sql and syntax highlighting in code editors like VSCode.

How?

import { sql } from "pg-literally"

const name = "Gandalf"
const age = 24000

const query = sql`
  SELECT *
  FROM characters
  WHERE name = ${name}
  AND age = ${age}
`

Result:

{
  "text": "SELECT * FROM characters WHERE name = $1 AND age = $2",
  "values": ["Gandalf", 24000]
}

Here are some examples of how you can use the query with node-pg or pg-promise:

Example 1: Using node-pg

import { Client } from "pg"
import { sql } from "pg-literally"

const name = "Gandalf"
const age = 24000

const query = sql`
  SELECT *
  FROM characters
  WHERE name = ${name}
  AND age = ${age}
`

const client = new Client()
client.connect()

await client.query(query)

Example 2: Using pg-promise

import { Database } from "pg-promise"
import { sql } from "pg-literally"

const name = "Gandalf"
const age = 24000

const query = sql`
  SELECT *
  FROM characters
  WHERE name = ${name}
  AND age = ${age}
`

const db = new Database("connection-string")

await db.one(query)

Reference

sql

The sql function is a template tag that returns an object with a text property and a values property. The text property is the SQL query with placeholders for the values. The values property is an array of the values that should be substituted into the query.

const query = sql`
  SELECT *
  FROM characters
  WHERE name = ${name}
  AND age = ${age}
`

The query object will look like this:

{
  text: 'SELECT * FROM characters WHERE name = $1 AND age = $2',
  values: ['Gandalf', 24000]
}

sqlFragment

The sqlFragment function can be used to create a SQL fragment that can be used in a larger query. It works the same way as the sql function, but it does not return an object with a text and values property. Instead, it returns a SqlFragment type that can be joined and combined together before actually rendering it to query placeholder and values array.

And yes, you can put sql fragments in sql fragments.

const whereFragment = sqlFragment`
  name = ${name}
  AND age = ${age}
`

You can then use the whereFragment in a larger query like this:

const query = sql`
  SELECT *
  FROM characters
  WHERE ${whereFragment}
`

joinSqlFragments

The joinSqlFragments function can be used to join two SqlFragment objects together. It returns a new SqlFragment object that represents the combined fragments.

const whereFragment1 = sqlFragment`name = ${name}`
const whereFragment2 = sqlFragment`age = ${age}`
const combinedFragment = joinSqlFragments(
  whereFragment1,
  whereFragment2,
  "\nAND ",
)

const query = sql`
  SELECT *
  FROM characters
  WHERE ${combinedFragment}
`

Result:

{
  "text": "SELECT * FROM characters WHERE name = $1\nAND age = $2",
  "values": ["Gandalf", 24000]
}

combineFragments

The combineFragments function can be used to combine multiple SqlFragment objects together. It returns a new SqlFragment object that represents the combined fragments. Basically, this is syntactic sugar for reducing an array of SqlFragment objects.

import { combineFragments, sql, sqlFragment as sqlF } from "pg-literally"

const companiesToInsert = [
  { name: "Apple", address: "1 Infinite Loop" },
  { name: "Google", address: "1600 Amphitheatre Parkway" },
  { name: "Microsoft", address: "One Microsoft Way" },
  { name: "Amazon", address: "410 Terry Ave. North" },
]

const result = sql`
  INSERT INTO company (name, address)
  VALUES ${combineFragments(
    ",\n",
    ...companiesToInsert.map(
      (company) => sqlF`(${[company.name, company.address]})`,
    ),
  )}
`

Result:

{
  "text": "INSERT INTO company (name, address) VALUES ($1, $2),\n($3, $4),\n($5, $6),\n($7, $8)",
  "values": [
    "Apple",
    "1 Infinite Loop",
    "Google",
    "1600 Amphitheatre Parkway",
    "Microsoft",
    "One Microsoft Way",
    "Amazon",
    "410 Terry Ave. North"
  ]
}