ES6 SQL-escaping tagged template literal that spits out a sanitized SQL string
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore
.travis.yml
index.js
package-lock.json
package.json
readme.md

readme.md

sql-tagged-template-literal

npm install sql-tagged-template-literal

Useful for data dumps and other "just gimme a query" tasks.

const userInput = `Robert'); DROP TABLE Students;--`

const query = sql`INSERT INTO awesome_table (sweet_column) VALUES (${userInput})`

query // => `INSERT INTO awesome_table (sweet_column) VALUES ('Robert\\'); DROP TABLE Students;--')`

Uses the sqlstring library for escaping.

Only meant for escaping values - you shouldn't put table or column names in expressions.

Escape mechanisms

null is an unqouted NULL

sql`SELECT ${null} IS NULL` // => `SELECT NULL IS NULL`

Strings are escaped and quoted

sql`SELECT ${"what's up"} AS lulz` // => `SELECT 'what\\'s up' AS lulz`

Numbers are not quoted

sql`SELECT ${13} AS totally_lucky` // => `SELECT 13 AS totally_lucky`

Booleans are converted to text

sql`SELECT ${true} = ${false}` // => `SELECT true = false`

Objects are JSONed, then escaped

MySQL has a JSON data type, after all.

const legitObject = { fancy: 'yes\'m' }

const jsonInsertQuery = sql`INSERT INTO document_store (json_column) VALUES (${legitObject})`

jsonInsertQuery // => `INSERT INTO document_store (json_column) VALUES ('{\\"fancy\\":\\"yes\\'m\\"}')`

License

WTFPL