Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

sql-template-tag

3.4.0 • Public • Published

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

Install

npm i sql-template-tag

DownloadsWeekly Downloads

1,239

Version

3.4.0

License

MIT

Unpacked Size

27.3 kB

Total Files

9

Last publish

Collaborators

  • avatar