diff --git a/lib/SqlString.js b/lib/SqlString.js index 5bfa2e7..0ee25ed 100644 --- a/lib/SqlString.js +++ b/lib/SqlString.js @@ -23,6 +23,10 @@ SqlString.escapeId = function escapeId(val, forbidQualified) { return sql; } + if (val instanceof Escaped) { + return String(val); + } + if (forbidQualified) { return '`' + String(val).replace(/`/g, '``') + '`'; } @@ -39,7 +43,9 @@ SqlString.escape = function escape(val, stringifyObjects, timeZone) { case 'boolean': return (val) ? 'true' : 'false'; case 'number': return val + ''; case 'object': - if (val instanceof Date) { + if (val instanceof Escaped) { + return String(val); + } else if (val instanceof Date) { return SqlString.dateToString(val, timeZone || 'local'); } else if (Array.isArray(val)) { return SqlString.arrayToList(val, timeZone); @@ -56,6 +62,10 @@ SqlString.escape = function escape(val, stringifyObjects, timeZone) { } }; +SqlString.escaped = function escaped(val) { + return new Escaped(val); +}; + SqlString.arrayToList = function arrayToList(array, timeZone) { var sql = ''; @@ -218,3 +228,9 @@ function convertTimezone(tz) { } return false; } + +function Escaped(val) { + this.toString = function toString() { + return String(val); + }; +} diff --git a/test/unit/test-SqlString.js b/test/unit/test-SqlString.js index ae85233..746921b 100644 --- a/test/unit/test-SqlString.js +++ b/test/unit/test-SqlString.js @@ -45,6 +45,10 @@ test('SqlString.escapeId', { 'nested arrays are flattened': function() { assert.equal(SqlString.escapeId(['a', ['b', ['t.c']]]), '`a`, `b`, `t`.`c`'); + }, + + 'instances of Escaped are not quoted': function() { + assert.equal(SqlString.escapeId(SqlString.escaped('@a := 42')), '@a := 42'); } }); @@ -118,6 +122,10 @@ test('SqlString.escape', { assert.equal(SqlString.escape('Super'), "'Super'"); }, + 'instances of Escaped get not escaped': function() { + assert.equal(SqlString.escape({a: SqlString.escaped('@a')}), '`a` = @a'); + }, + '\0 gets escaped': function() { assert.equal(SqlString.escape('Sup\0er'), "'Sup\\0er'"); assert.equal(SqlString.escape('Super\0'), "'Super\\0'");