Gathering detailed insights and metrics for sqlstring
Gathering detailed insights and metrics for sqlstring
Gathering detailed insights and metrics for sqlstring
Gathering detailed insights and metrics for sqlstring
npm install sqlstring
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (100%)
Total Downloads
690,233,893
Last Day
696,151
Last Week
3,865,331
Last Month
16,727,819
Last Year
200,266,876
MIT License
410 Stars
167 Commits
78 Forks
15 Watchers
3 Branches
10 Contributors
Updated on Apr 05, 2025
Minified
Minified + Gzipped
Latest Version
2.3.3
Package Id
sqlstring@2.3.3
Unpacked Size
16.85 kB
Size
6.22 kB
File Count
6
NPM Version
8.1.2
Node Version
16.13.1
Cumulative downloads
Total Downloads
Last Day
44.8%
696,151
Compared to previous day
Last Week
4.3%
3,865,331
Compared to previous week
Last Month
-10.7%
16,727,819
Compared to previous month
Last Year
28.1%
200,266,876
Compared to previous year
7
Simple SQL escape and format for MySQL
1$ npm install sqlstring
1var SqlString = require('sqlstring');
Caution These methods of escaping values only works when the NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state for MySQL servers).
In order to avoid SQL Injection attacks, you should always escape any user
provided data before using it inside a SQL query. You can do so using the
SqlString.escape()
method:
1var userId = 'some user provided value'; 2var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId); 3console.log(sql); // SELECT * FROM users WHERE id = 'some user provided value'
Alternatively, you can use ?
characters as placeholders for values you would
like to have escaped like this:
1var userId = 1; 2var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]); 3console.log(sql); // SELECT * FROM users WHERE id = 1
Multiple placeholders are mapped to values in the same order as passed. For example,
in the following query foo
equals a
, bar
equals b
, baz
equals c
, and
id
will be userId
:
1var userId = 1; 2var sql = SqlString.format('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', 3 ['a', 'b', 'c', userId]); 4console.log(sql); // UPDATE users SET foo = 'a', bar = 'b', baz = 'c' WHERE id = 1
This looks similar to prepared statements in MySQL, however it really just uses
the same SqlString.escape()
method internally.
Caution This also differs from prepared statements in that all ?
are
replaced, even those contained in comments and strings.
Different value types are escaped differently, here is how:
true
/ false
'YYYY-mm-dd HH:ii:ss'
stringsX'0fa5'
['a', 'b']
turns into 'a', 'b'
[['a', 'b'], ['c', 'd']]
turns into ('a', 'b'), ('c', 'd')
toSqlString
method will have .toSqlString()
called
and the returned value is used as the raw SQL.key = 'val'
pairs for each enumerable property on
the object. If the property's value is a function, it is skipped; if the
property's value is an object, toString() is called on it and the returned
value is used.undefined
/ null
are converted to NULL
NaN
/ Infinity
are left as-is. MySQL does not support these, and trying
to insert them as values will trigger MySQL errors until they implement
support.You may have noticed that this escaping allows you to do neat things like this:
1var post = {id: 1, title: 'Hello MySQL'};
2var sql = SqlString.format('INSERT INTO posts SET ?', post);
3console.log(sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
And the toSqlString
method allows you to form complex queries with functions:
1var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; 2var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); 3console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
To generate objects with a toSqlString
method, the SqlString.raw()
method can
be used. This creates an object that will be left un-touched when using in a ?
placeholder, useful for using functions as dynamic values:
Caution The string provided to SqlString.raw()
will skip all escaping
functions when used, so be careful when passing in unvalidated input.
1var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); 2var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); 3console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
If you feel the need to escape queries by yourself, you can also use the escaping function directly:
1var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL'); 2console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL'
If you can't trust an SQL identifier (database / table / column name) because it is
provided by a user, you should escape it with SqlString.escapeId(identifier)
like this:
1var sorter = 'date'; 2var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter); 3console.log(sql); // SELECT * FROM posts ORDER BY `date`
It also supports adding qualified identifiers. It will escape both parts.
1var sorter = 'date'; 2var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter); 3console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date`
If you do not want to treat .
as qualified identifiers, you can set the second
argument to true
in order to keep the string as a literal identifier:
1var sorter = 'date.2'; 2var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter, true); 3console.log(sql); // SELECT * FROM posts ORDER BY `date.2`
Alternatively, you can use ??
characters as placeholders for identifiers you would
like to have escaped like this:
1var userId = 1; 2var columns = ['username', 'email']; 3var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]); 4console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
Please note that this last character sequence is experimental and syntax might change
When you pass an Object to .escape()
or .format()
, .escapeId()
is used to avoid SQL injection in object keys.
You can use SqlString.format
to prepare a query with multiple insertion points,
utilizing the proper escaping for ids and values. A simple example of this follows:
1var userId = 1; 2var inserts = ['users', 'id', userId]; 3var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts); 4console.log(sql); // SELECT * FROM `users` WHERE `id` = 1
Following this you then have a valid, escaped query that you can then send to the database safely.
This is useful if you are looking to prepare the query before actually sending it to the database.
You also have the option (but are not required) to pass in stringifyObject
and timeZone
,
allowing you provide a custom means of turning objects into strings, as well as a
location-specific/timezone-aware Date
.
This can be further combined with the SqlString.raw()
helper to generate SQL
that includes MySQL functions as dynamic vales:
1var userId = 1; 2var data = { email: 'foobar@example.com', modified: SqlString.raw('NOW()') }; 3var sql = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]); 4console.log(sql); // UPDATE `users` SET `email` = 'foobar@example.com', `modified` = NOW() WHERE `id` = 1
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no SAST tool detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-05-05
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More