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
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.babelrc
.flowconfig
.gitignore
.npmignore
.travis.yml Added DATABASE_URL to travis Apr 3, 2018
LICENSE
README.md
package.json Update package.json Jun 30, 2018
yarn.lock implementation Apr 3, 2018

README.md

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.

Installation

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

Usage

import { sql, execute } from "cuery";

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

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

Transformations

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

const limit = query =>
  sql`
    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.