Skip to content

Commit

Permalink
Add mysql.raw() to generate pre-escaped values
Browse files Browse the repository at this point in the history
closes #877
closes #1821
  • Loading branch information
dougwilson committed Oct 2, 2017
1 parent 5d139b2 commit 55c20da
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes.md
Expand Up @@ -7,6 +7,7 @@ you spot any mistakes.
## HEAD

* Add new Amazon RDS ca-central-1 certificate CA to Amazon RDS SSL profile #1809
* Add `mysql.raw()` to generate pre-escaped values #877 #1821
* Fix "changedRows" to work on non-English servers #1819
* Fix typo in insecure auth error message
* Support `mysql_native_password` auth switch request for Azure #1396 #1729 #1730
Expand Down
13 changes: 13 additions & 0 deletions Readme.md
Expand Up @@ -737,6 +737,19 @@ var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TI
console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
```

To generate objects with a `toSqlString` method, the `mysql.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 `mysql.raw()` will skip all escaping
functions when used, so be careful when passing in unvalidated input.

```js
var CURRENT_TIMESTAMP = mysql.raw('CURRENT_TIMESTAMP()');
var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
console.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:

Expand Down
12 changes: 12 additions & 0 deletions index.js
Expand Up @@ -94,6 +94,18 @@ exports.format = function format(sql, values, stringifyObjects, timeZone) {
return SqlString.format(sql, values, stringifyObjects, timeZone);
};

/**
* Wrap raw SQL strings from escape overriding.
* @param {string} sql The raw SQL
* @return {object} Wrapped object
* @public
*/
exports.raw = function raw(sql) {
var SqlString = loadClass('SqlString');

return SqlString.raw(sql);
};

/**
* The type constants.
* @public
Expand Down
10 changes: 10 additions & 0 deletions test/unit/test-Mysql.js
Expand Up @@ -20,6 +20,16 @@ test('Mysql.format', {
}
});

test('Mysql.raw', {
'generate object format will not escape': function() {
var now = Mysql.raw('NOW()');
assert.equal(
Mysql.format('SELECT * FROM ?? WHERE ?? >= ?', ['table', 'property', now]),
'SELECT * FROM `table` WHERE `property` >= NOW()'
);
}
});

test('Mysql.Types', {
'exported object of types': function() {
assert.equal(typeof Mysql.Types, 'object');
Expand Down

0 comments on commit 55c20da

Please sign in to comment.