A simple yet powerful module to allow you to use ES6 tagged template strings for prepared/escaped statements in mysql / mysql2 and postgres.
Example for escaping queries (callbacks omitted):
let SQL = require('sql-template-strings')
let book = 'harry potter'
mysql.query('SELECT author FROM books WHERE name = ?', [book])
mysql.query(SQL`SELECT author FROM books WHERE name = ${book}`)
pg.query('SELECT author FROM books WHERE name = $1', [book])
pg.query(SQL`SELECT author FROM books WHERE name = ${book}`)
This might not seem like a big deal, but when you do an INSERT with a lot columns writing all the placeholders becomes a nightmare:
db.query(
'INSERT INTO books (name, author, isbn, category, recommended_age, pages, price) VALUES (?, ?, ?, ?, ?, ?, ?)',
[name, author, isbn, category, recommendedAge, pages, price]
)
db.query(SQL`
INSERT
INTO books
(name, author, isbn, category, recommended_age, pages, price)
VALUES (${name}, ${author}, ${isbn}, ${category}, ${recommendedAge}, ${pages}, ${price})
`)
Also template strings support line breaks, while normal strings do not.
Adding raw values
Some values cannot be replaced by placeholders in prepared statements, like table names. In these cases, you need to use SQL.raw()
so the values get inserted directly. Please note that you are then responsible for escaping these values with proper escaping functions first if they come from user input. Also, executing many prepared statements with changing raw values in a loop will quickly overflow the prepared statement buffer (and destroy their performance benefit), so be careful. Examples:
let table = 'books'
let order = 'DESC'
let column = 'author'
db.query(SQL`SELECT * FROM ${SQL.raw(table)} WHERE author = ${author} ORDER BY ${column} ${SQL.raw(order)}`)
mysql.query(SQL`SELECT * FROM ${SQL.raw(mysql.escapeId(someUserInput))} WHERE name = ${book} ORDER BY ${column} ${SQL.raw(order)}`)
pg.query(SQL`SELECT * FROM "${SQL.raw(table)}"`)
mysql.query(SQL`SELECT * FROM \`${SQL.raw(table)}\``)
for (let table of largeArray) {
mysql2.execute(SQL`SELECT * FROM ${SQL.raw(table)}`)
}
Prepared Statements in Postgre
Postgre requires prepared statements to be named, otherwise the parameters will be escaped and replaced on the client side.
You can still use SQL template strings though, you just need to assign a name to the query before using it:
pg.query({name: 'my_query', text: 'SELECT author FROM books WHERE name = $1', values: [book]})
let query = SQL`SELECT author FROM books WHERE name = ${book}`
query.name = 'my_query'
pg.query(query)
pg.query(_.assign(SQL`SELECT author FROM books WHERE name = ${book}`, {name: 'my_query'}))
Contributing
- Tests are written using mocha (BDD style) and chai (expect style)
- This module follows standard coding style
- You can use
npm test
to run the tests and check coding style - Since this module is only compatible with ES6 versions of node anyway, use all the ES6 goodies
- Pull requests are welcome :)