Skip to content

Commit a55e82f

Browse files
fangkfengmk2
authored andcommitted
feat: support query(sql, object) (#12)
1 parent 7d5c71f commit a55e82f

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/operator.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,19 @@ proto.escapeId = function (value, forbidQualified) {
2828
};
2929

3030
proto.format = function (sql, values, stringifyObjects, timeZone) {
31-
return SqlString.format(sql, values, stringifyObjects, timeZone);
31+
// if values is object, not null, not Array;
32+
if (!Array.isArray(values) && typeof values === 'object' && values !== null) {
33+
// object not support replace column like ??;
34+
return sql.replace(/\:(\w+)/g, function(txt, key) {
35+
if (values.hasOwnProperty(key)) {
36+
return SqlString.escape(values[key]);
37+
}
38+
// if values don't hasOwnProperty, return origin txt;
39+
return txt;
40+
});
41+
} else {
42+
return SqlString.format(sql, values, stringifyObjects, timeZone);
43+
}
3244
};
3345

3446
proto.query = function*(sql, values) {

test/operator.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,30 @@ describe('operator.test.js', function () {
3030
let op = new Operator();
3131
assert.equal(op.format('SET ?? = ?', ['dt', op.literals.now], true), 'SET `dt` = now()');
3232
});
33+
34+
it('should get literal string by string', function () {
35+
let op = new Operator();
36+
assert.equal(op.format('SET name = ?', 'test'), 'SET name = \'test\'');
37+
});
38+
39+
it('should get literal string by object', function () {
40+
let op = new Operator();
41+
assert.equal(op.format('SET dt = :now and name = :name and age = :age', {
42+
now: op.literals.now,
43+
name: 'test'
44+
}), 'SET dt = now() and name = \'test\' and age = :age');
45+
});
46+
47+
it('should get literal string by boundary', function () {
48+
let op = new Operator();
49+
assert.equal(op.format('SET name = ?', null), 'SET name = ?');
50+
assert.equal(op.format('SET name = ?', undefined), 'SET name = ?');
51+
assert.equal(op.format('SET name = ?', 0), 'SET name = 0');
52+
assert.equal(op.format('SET name = ?', 1), 'SET name = 1');
53+
assert.equal(op.format('SET name = ?', 'foo'), 'SET name = \'foo\'');
54+
assert.equal(op.format('SET name = ?', true), 'SET name = true');
55+
assert.equal(op.format('SET name = ?', false), 'SET name = false');
56+
});
3357
});
3458

3559
describe('_query()', function () {

0 commit comments

Comments
 (0)