From a55e82fabc1a80031a8787425939ec62bd70d52d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=87=AF=20=E6=96=B9?= Date: Tue, 9 Aug 2016 17:17:34 +0800 Subject: [PATCH] feat: support query(sql, object) (#12) --- lib/operator.js | 14 +++++++++++++- test/operator.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/operator.js b/lib/operator.js index 7449313..e82fa19 100644 --- a/lib/operator.js +++ b/lib/operator.js @@ -28,7 +28,19 @@ proto.escapeId = function (value, forbidQualified) { }; proto.format = function (sql, values, stringifyObjects, timeZone) { - return SqlString.format(sql, values, stringifyObjects, timeZone); + // if values is object, not null, not Array; + if (!Array.isArray(values) && typeof values === 'object' && values !== null) { + // object not support replace column like ??; + return sql.replace(/\:(\w+)/g, function(txt, key) { + if (values.hasOwnProperty(key)) { + return SqlString.escape(values[key]); + } + // if values don't hasOwnProperty, return origin txt; + return txt; + }); + } else { + return SqlString.format(sql, values, stringifyObjects, timeZone); + } }; proto.query = function*(sql, values) { diff --git a/test/operator.test.js b/test/operator.test.js index 31ec999..0cef10e 100644 --- a/test/operator.test.js +++ b/test/operator.test.js @@ -30,6 +30,30 @@ describe('operator.test.js', function () { let op = new Operator(); assert.equal(op.format('SET ?? = ?', ['dt', op.literals.now], true), 'SET `dt` = now()'); }); + + it('should get literal string by string', function () { + let op = new Operator(); + assert.equal(op.format('SET name = ?', 'test'), 'SET name = \'test\''); + }); + + it('should get literal string by object', function () { + let op = new Operator(); + assert.equal(op.format('SET dt = :now and name = :name and age = :age', { + now: op.literals.now, + name: 'test' + }), 'SET dt = now() and name = \'test\' and age = :age'); + }); + + it('should get literal string by boundary', function () { + let op = new Operator(); + assert.equal(op.format('SET name = ?', null), 'SET name = ?'); + assert.equal(op.format('SET name = ?', undefined), 'SET name = ?'); + assert.equal(op.format('SET name = ?', 0), 'SET name = 0'); + assert.equal(op.format('SET name = ?', 1), 'SET name = 1'); + assert.equal(op.format('SET name = ?', 'foo'), 'SET name = \'foo\''); + assert.equal(op.format('SET name = ?', true), 'SET name = true'); + assert.equal(op.format('SET name = ?', false), 'SET name = false'); + }); }); describe('_query()', function () {