Skip to content

Commit

Permalink
Add .toSqlString() escapeId overriding
Browse files Browse the repository at this point in the history
closes #57
closes #58
  • Loading branch information
dovidgef authored and dougwilson committed Mar 7, 2022
1 parent cd52855 commit 2ccc17a
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
5 changes: 5 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
unreleased
==========

* Add `.toSqlString()` escapeId overriding

2.3.3 / 2022-03-06
==================

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
```
**Please note that this last character sequence is experimental and syntax might change**

To skip escaping one or more of the columns names that you pass to `SqlString.escapeId()`
you may use `SqlString.raw()` similarly to how it is used with `SqlString.escape()`.
See above for more details.

When you pass an Object to `.escape()` or `.format()`, `.escapeId()` is used to avoid SQL injection in object keys.

### Formatting queries
Expand Down
2 changes: 2 additions & 0 deletions lib/SqlString.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ SqlString.escapeId = function escapeId(val, forbidQualified) {
}

return sql;
} else if (typeof val.toSqlString === 'function') {
return String(val.toSqlString());
} else if (forbidQualified) {
return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';
} else {
Expand Down
8 changes: 8 additions & 0 deletions test/unit/test-SqlString.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ test('SqlString.escapeId', {

'nested arrays are flattened': function() {
assert.equal(SqlString.escapeId(['a', ['b', ['t.c']]]), '`a`, `b`, `t`.`c`');
},

'raw not escaped': function () {
assert.equal(SqlString.escapeId(SqlString.raw('*')), '*');
},

'raw within array not escaped': function () {
assert.equal(SqlString.escapeId(['a', SqlString.raw('*'), 'b']), '`a`, *, `b`');
}
});

Expand Down

0 comments on commit 2ccc17a

Please sign in to comment.