SQL Escaper is a rework of sqlstring (created by Douglas Wilson), by using an AST-based approach to parse and format SQL queries while maintaining its same API.
Distinguishes between multiple clauses/keywords in the same query.
Reasonable conservative support for Node.js v12(sqlstring supports Node.js v0.6).
[!TIP]
SQL Escaper has the same API as the original sqlstring, so it can be used as a drop-in replacement. If SQL Escaper breaks any API usage compared to sqlstring, please, report it as a bug. Pull Requests are welcome.
[!IMPORTANT]
🔐 SQL Escaper is intended to fix a potential SQL Injection vulnerability reported in 2022. By combining the original sqlstring with mysqljs/mysql or MySQL2, objects passed as values could be expanded into SQL fragments, potentially allowing attackers to manipulate query structure. See sidorares/node-mysql2#4051 for details.
Regardless of the stringifyObjects value, objects used outside of SET or ON DUPLICATE KEY UPDATE contexts are always stringified as '[object Object]'. This is a security measure to prevent SQL Injection and is not interpreted as a breaking change for sqlstring usage.
Next, clean the node_modules and reinstall the dependencies (npm i).
Please, note the minimum supported version of Node.js is 12.
Usage
For up-to-date documentation, always follow the README.md in the GitHub repository.
Quickstart
import { escape, escapeId, format, raw } from 'sql-escaper';escape("Hello 'World'", true);// => "'Hello \\'World\\''"escapeId('table.column');// => '`table`.`column`'format('SELECT * FROM ?? WHERE id = ?', ['users', 42]);// => 'SELECT * FROM `users` WHERE id = 42'format('INSERT INTO users SET ?', [{ name: 'foo', email: 'bar@test.com' }]);// => "INSERT INTO users SET `name` = 'foo', `email` = 'bar@test.com'"escape(raw('NOW()'), true);// => 'NOW()'
Import
ES Modules
import { escape, escapeId, format, raw } from 'sql-escaper';
CommonJS
const { escape, escapeId, format, raw } = require('sql-escaper');
Temporal values are supported too.
Temporal.Instant and Temporal.ZonedDateTime are absolute points in time and
honor the timezone argument exactly like Date (millisecond precision):
Temporal.PlainDateTime, Temporal.PlainDate and Temporal.PlainTime are
wall-clock values and are emitted verbatim as DATETIME / DATE / TIME
literals, ignoring timezone:
Function properties in objects are ignored (discouraged):
escape({ a: 'b', c: () => {} });// => "`a` = 'b'"
[!CAUTION]
Without stringifyObjects, plain objects are converted to key = value pairs, so an object reaching escape where a value is expected reshapes the query, for example:
const userInput = { id: true }; // e.g. JSON.parse('{"id":true}')/** Unsafe 🔓 (value position) */'DELETE FROM entries WHERE id = ' + escape(userInput);// => "DELETE FROM entries WHERE id = `id` = true"// `id` = `id` is always true, so every row is deleted ❗️/** Valid ✅ (SET assignment) */'UPDATE users SET ' + escape({ name: 'foo', role: 'admin' });// => "UPDATE users SET `name` = 'foo', `role` = 'admin'"
[!TIP]
Instead, format only expands an object where it is safe (e.g., a SET assignment) and stringifies it everywhere else, so the same input cannot reshape the query:
const userInput = { id: true }; // e.g. JSON.parse('{"id":true}')/** Unsafe 🔐 (value position) */format('DELETE FROM entries WHERE id = ?', [userInput]);// => "DELETE FROM entries WHERE id = '[object Object]'"// stringified to an inert value/** Valid ✅ (SET assignment) */format('UPDATE users SET ?', [{ name: 'foo', role: 'admin' }]);// => "UPDATE users SET `name` = 'foo', `role` = 'admin'"// expanded on purpose
Arrays
Arrays are turned into comma-separated lists:
escape([1, 2, 'c'], true);// => "1, 2, 'c'"
Nested arrays are turned into grouped lists (useful for bulk inserts):
format('SELECT * FROM ?? WHERE id = ?', ['users', 42]);// => 'SELECT * FROM `users` WHERE id = 42'format('? and ?', ['a', 'b']);// => "'a' and 'b'"
Triple (or more) question marks are ignored:
format('? or ??? and ?', ['foo', 'bar', 'fizz', 'buzz']);// => "'foo' or ??? and 'bar'"
If no values are provided, the SQL is returned unchanged:
format('SELECT ??');// => 'SELECT ??'
Objects in SET clauses
When stringifyObjects is falsy, objects used in SET or ON DUPLICATE KEY UPDATE contexts are automatically expanded into key = value pairs:
format('UPDATE users SET ?', [{ name: 'foo', email: 'bar@test.com' }]);// => "UPDATE users SET `name` = 'foo', `email` = 'bar@test.com'"format( 'INSERT INTO users (name, email) VALUES (?, ?) ON DUPLICATE KEY UPDATE ?', ['foo', 'bar@test.com', { name: 'foo', email: 'bar@test.com' }]);// => "INSERT INTO users (name, email) VALUES ('foo', 'bar@test.com') ON DUPLICATE KEY UPDATE `name` = 'foo', `email` = 'bar@test.com'"
When stringifyObjects is truthy, objects are always stringified:
format('UPDATE users SET ?', [{ name: 'foo' }], true);// => "UPDATE users SET '[object Object]'"
Maps in SET clauses
Maps are treated like plain objects, preserving insertion order. In SET or ON DUPLICATE KEY UPDATE contexts, they are expanded into key = value pairs:
format('UPDATE users SET ?', [ new Map([ ['name', 'foo'], ['email', 'bar@test.com'], ]),]);// => "UPDATE users SET `name` = 'foo', `email` = 'bar@test.com'"
Outside of SET or ON DUPLICATE KEY UPDATE, a Map is stringified as '[object Map]', the same security measure applied to objects:
format('SELECT * FROM users WHERE data = ?', [new Map([['id', 1]])]);// => "SELECT * FROM users WHERE data = '[object Map]'"
SQL mode
When the server runs with the ANSI_QUOTES SQL mode, set ansiQuotes so double-quoted text is read as an identifier, where a backslash is an ordinary character:
const sqlMode = { ansiQuotes: true };format('SELECT "dir\\" FROM t WHERE id = ?', [1], false, 'local', sqlMode);// => 'SELECT "dir\\" FROM t WHERE id = 1'
raw
Creates a raw SQL value that will not be escaped.
raw(sql: string): Raw
escape(raw('NOW()'), true);// => 'NOW()'
Inside an expanded object, raw values are preserved (discouraged):
The escaping methods in this library only work when the NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state for MySQL servers).
This library performs client-side escaping to generate SQL strings. The syntax for format may look similar to a prepared statement, but it is not — the escaping rules from this module are used to produce the resulting SQL string.
When using format, placeholders inside strings ('...' and "..."), backtick identifiers, and comments (#, /* */, and -- followed by whitespace) are left as they are. Executable comments (/*! */) and optimizer hints (/*+ */) are read as SQL, so their placeholders are replaced.
By default, double-quoted text is read as a string, where a backslash escapes the next character. If the server runs with the ANSI_QUOTES SQL mode, set ansiQuotes, or the placeholders after a double-quoted identifier that ends in a backslash can be skipped or misplaced.
When structured user input is provided as the value to escape, care should be taken to validate the shape of the input, as the resulting escaped string may contain more than a single value.
NaN and Infinity are left as-is. MySQL does not support these values, and trying to insert them will trigger MySQL errors.
The string provided to raw() will skip all escaping, so be careful when passing in unvalidated input.