ES6 SQL-escaping tagged template literal that spits out a sanitized SQL string
npm install sql-tagged-template-literal``sh`
npm install sql-tagged-template-literal
Useful for data dumps and other "just gimme a query" tasks.
`jsRobert'); DROP TABLE Students;--
const userInput =
const query = sqlINSERT INTO awesome_table (sweet_column) VALUES (${userInput})
query // => INSERT INTO awesome_table (sweet_column) VALUES ('Robert\\'); DROP TABLE Students;--')`
- Unlike node-sql-template-strings, this module returns a string
- Unlike sql-concat, this module isn't great at building queries dynamically
Uses the sqlstring library for escaping.
Only meant for escaping values - you shouldn't put table or column names in expressions.
`jsSELECT ${null} IS NULL
sql // => SELECT NULL IS NULL`
`jsSELECT ${undefined} IS NULL
sql // => SELECT NULL IS NULL`
`jsSELECT ${"what's up"} AS lulz
sql // => SELECT 'what\\'s up' AS lulz`
`jsSELECT ${13} AS totally_lucky
sql // => SELECT 13 AS totally_lucky`
`jsSELECT ${true} = ${false}
sql // => SELECT true = false`
MySQL has a JSON data type, after all.
`js
const legitObject = { fancy: 'yes\'m' }
const jsonInsertQuery = sqlINSERT INTO document_store (json_column) VALUES (${legitObject})
jsonInsertQuery // => INSERT INTO document_store (json_column) VALUES ('{\\"fancy\\":\\"yes\\'m\\"}')`
`jsWHERE name IN(${[
const arrayQuery = sqlAlice, userInput ]})
arrayQuery // => "WHERE name IN('Alice', 'Robert\\'); DROP TABLE Students;--')"
`
`jsWHERE value IN(${ mySet })
const mySet = new Set([ 1, 42 ])
sql // => "WHERE value IN(1, 42)"`
`jsa
const twoDimensionalArray = [[, 1], [b, 2], [c, 3]]INSERT INTO tablez (letter, number) VALUES ${twoDimensionalArray}
const twoDimensionalQuery = sql
twoDimensionalQuery // => INSERT INTO tablez (letter, number) VALUES ('a', 1), ('b', 2), ('c', 3)``