Skip to content

Commit

Permalink
feat: support query(sql, object) (ali-sdk#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
fangk authored and fengmk2 committed Aug 9, 2016
1 parent 7d5c71f commit a55e82f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/operator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions test/operator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit a55e82f

Please sign in to comment.