[READ-ONLY] Mirror of https://github.com/Schniz/cuery. A composable SQL query builder using template literals ✨
0

Configure Feed

Select the types of activity you want to include in your feed.

32 3 4

Clone this repository

https://tangled.org/schlez.in/cuery https://tangled.org/did:plc:jnuqqci7ha5wzbohmk6gkpht
git@tangled.org:schlez.in/cuery git@tangled.org:did:plc:jnuqqci7ha5wzbohmk6gkpht

For self-hosted knots, clone URLs may differ based on your setup.



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