Skip to content

Commit d3a64c2

Browse files
committed
feat: Add ability to use SqlString.raw() within the SqlString.escapeId() method
1 parent b580866 commit d3a64c2

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
183183
```
184184
**Please note that this last character sequence is experimental and syntax might change**
185185

186+
To skip escaping one or more of the columns names that you pass to `SqlString.escapeId()`
187+
you may use `SqlString.raw()` similarly to how it is used with `SqlString.escape()`.
188+
See above for more details.
189+
186190
When you pass an Object to `.escape()` or `.format()`, `.escapeId()` is used to avoid SQL injection in object keys.
187191

188192
### Formatting queries

lib/SqlString.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,19 @@ SqlString.escapeId = function escapeId(val, forbidQualified) {
2020
var sql = '';
2121

2222
for (var i = 0; i < val.length; i++) {
23-
sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified);
23+
sql += (i === 0 ? '' : ', ');
24+
if (typeof val[i].toSqlString === 'function') {
25+
sql += String(val[i].toSqlString());
26+
} else {
27+
sql += SqlString.escapeId(val[i], forbidQualified);
28+
}
2429
}
2530

2631
return sql;
2732
} else if (forbidQualified) {
2833
return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';
34+
} else if (typeof val.toSqlString === 'function') {
35+
return String(val.toSqlString());
2936
} else {
3037
return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`';
3138
}

test/unit/test-SqlString.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,15 @@ test('SqlString.escapeId', {
4545

4646
'nested arrays are flattened': function() {
4747
assert.equal(SqlString.escapeId(['a', ['b', ['t.c']]]), '`a`, `b`, `t`.`c`');
48-
}
48+
},
49+
50+
'raw not escaped': function () {
51+
assert.equal(SqlString.escapeId(SqlString.raw('*')), '*');
52+
},
53+
54+
'raw within array not escaped': function () {
55+
assert.equal(SqlString.escapeId(['firstColumnName', SqlString.raw('*'), 'secondColumnName']), '`firstColumnName`, *, `secondColumnName`');
56+
},
4957
});
5058

5159
test('SqlString.escape', {

0 commit comments

Comments
 (0)