Skip to content
ES2015 tagged template string for preparing SQL statements, works with `pg` and `mysql`
TypeScript
Branch: master
Clone or download

README.md

SQL Template Tag

NPM version NPM downloads Build status Test coverage

ES2015 tagged template string for preparing SQL statements, works with pg and mysql.

Installation

npm install sql-template-tag --save

Usage

import sql, { empty, join, raw } from "sql-template-tag";

const query = sql`SELECT * FROM books WHERE id = ${id}`;

query.sql; //=> "SELECT * FROM books WHERE id = ?"
query.text; //=> "SELECT * FROM books WHERE id = $1"
query.values; //=> [id]

pg.query(query); // Uses `text` and `values`.
mysql.query(query); // Uses `sql` and `values`.

// Embed SQL instances inside SQL instances.
const nested = sql`SELECT id FROM authors WHERE name = ${"Blake"}`;
const query = sql`SELECT * FROM books WHERE author_id IN (${nested})`;

// Join and "empty" helpers (useful for nested queries).
sql`SELECT * FROM books ${hasIds ? sql`WHERE ids IN (${join(ids)})` : empty}`;

Related

The main difference between this module and others is first-class TypeScript. There's also the raw, join and empty helpers. Specific differences are documented below:

sql-template-strings

Promotes mutation via chained methods and lacks nesting SQL statements. The idea to support both sql and text for mysql and pg compatibility came from here.

pg-template-tag

Missing TypeScript and MySQL support. This is the API I envisioned before starting development and, by supporting pg only, it has the ability to dedupe values. Supporting MySQL makes deduping impossible, because of ? placeholders instead of $<num>, so I decided that was a premature optimisation here and opted to keep mysql support here instead.

License

MIT

You can’t perform that action at this time.