A template tag for writing elegant sql strings
npm install sql-tagA template tag for writing elegant parameterized SQL queries based on ES2015 tagged template literals.
Compatible with pg, pg-native, mysql and mysql2. Read more about sequelize support.
[![npm version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
Install the package via npm:
``bash`
$ npm install --save sql-tag
#### Arguments
1. query (string): The sql query.[...]
2. (...\): The query replacements.
#### Returns
(Object): A structured object with the sql query string and its replacements.
#### Examples
`jsSELECT * FROM biz WHERE id = ${'foo'}
const sql = require('sql-tag');
const out = sql;`
// => { sql: 'SELECT FROM biz WHERE id = ?', query: 'SELECT FROM biz WHERE id = $1', values: ['foo'] }
`jsSELECT * FROM biz
const sql = require('sql-tag');
const foo = 'bar';
const out = sql
WHERE id = ${foo};`
// => { sql: 'SELECT FROM biz\n WHERE id = ?\n', query: 'SELECT FROM biz\n WHERE id = $1\n', values: ['bar'] }
The tag itself is framework agnostic. It should just require a small modification to the query generator function.
NOTE: the sql tag does not provide any kind of escaping safety. It delegates that work to the underlying framework.
The output format is sql-tag is directly compatible with pg and pg-native parameterized queries.
`js
const pg = require('pg');
const client = new pg.Client();
const sql = require('sql-tag');
client.connect(function (err) {
if (err) throw err;
client.query(sqlSELECT * FROM foo WHERE id = ${'foo'}).then(console.log);`
});
`js
const mysql = require('mysql');
const connection = mysql.createConnection({ user: 'root', password: 'root' });
const sql = require('sql-tag');
connection.query(sqlSELECT * FROM foo WHERE id = ${'foo'}, (err, rows) => console.log(err, rows));`
Sequelize requires a special format to be able to handle parameterized queries. Check out the sequelize-sql-tag plugin which builds on top of sql-tag to provide this functionality.
`sh`
npm test
`sh``
npm version [
MIT
[npm-image]: https://img.shields.io/npm/v/sql-tag.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/sql-tag
[travis-image]: https://img.shields.io/travis/seegno/sql-tag/v1.0.0.svg?style=flat-square
[travis-url]: https://travis-ci.org/seegno/sql-tag