Skip to content
A composable SQL query builder using template literals
Branch: master
Clone or download
Schniz Update package.json
Change license to MIT
Latest commit 16cba7a Jun 30, 2018
Type Name Latest commit message Commit time
Failed to load latest commit information.
.travis.yml Added DATABASE_URL to travis Apr 3, 2018
package.json Update package.json Jun 30, 2018
yarn.lock implementation Apr 3, 2018

Cuery - Composable SQL Querying build status

A composable SQL query builder based inspired by styled-components 💅

In 2016, I wrote a blog post about composing SQL queries and published this library as a reference. The years passed, and there are much cooler ways of doing it, so this is the new way - using template literals.


yarn add cuery pg
# or
npm install --save cuery pg


import { sql, execute } from "cuery";

const usersQuery = sql`SELECT * FROM users`;
const usersWithNameQuery = sql`
  SELECT * FROM (${usersQuery})
  WHERE name = ${params =>}

execute(usersWithNameQuery, { name: "John" }); // => Promise(<all the users named "John">)


You can declare helper methods that do magic on your queries, like limit:

const limit = query =>
    SELECT *
    FROM (${query}) limited_query_${Math.floor(Math.random() * 100000)}
    LIMIT ${p => p.limit}
    OFFSET ${p => p.offset}

// then you can just compose your queries!

const users = sql`SELECT * FROM users`;
const usersWithLimit = users.compose(limit); // or limit(users)
execute(usersWithLimit, { limit: 10, offset: 10 }); // start with offset of 10, then take 10 records.

Running tests

  • set the DATABASE_URL env variable for your PostgreSQL server - defaults to node-postgres' default
  • yarn test
You can’t perform that action at this time.