Skip to content

Commit 44b1542

Browse files
committed
allow passing JS array as a parameter instead of an array literal where SQL expects an array
1 parent d046ffc commit 44b1542

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/utils.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,31 @@ if(typeof events.EventEmitter.prototype.once !== 'function') {
1313
};
1414
}
1515

16+
// convert a JS array to a postgres array literal
17+
// uses comma separator so won't work for types like box that use
18+
// a different array separator.
19+
function arrayString(val) {
20+
var result = '{'
21+
for (var i = 0 ; i < val.length; i++) {
22+
if (i > 0)
23+
result = result + ',';
24+
if (val[i] instanceof Date) {
25+
result = result + JSON.stringify(val[i]);
26+
}
27+
else if(typeof val[i] === 'undefined') {
28+
result = result + 'NULL';
29+
}
30+
else if (Array.isArray(val[i])) {
31+
result = result + arrayString(val[i]);
32+
}
33+
else
34+
result = result +
35+
(val[i] === null ? 'NULL' : JSON.stringify(val[i]));
36+
}
37+
result = result + '}';
38+
return result;
39+
}
40+
1641
//converts values from javascript types
1742
//to their 'raw' counterparts for use as a postgres parameter
1843
//note: you can override this function to provide your own conversion mechanism
@@ -24,6 +49,9 @@ var prepareValue = function(val) {
2449
if(typeof val === 'undefined') {
2550
return null;
2651
}
52+
if (Array.isArray(val)) {
53+
return arrayString(val);
54+
}
2755
return val === null ? null : val.toString();
2856
};
2957

test/integration/client/array-tests.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,22 @@ test('parsing array results', function() {
122122
}))
123123
})
124124

125+
test('JS array parameter', function(){
126+
client.query("SELECT $1::integer[] as names", [[[1,100],[2,100],[3,100]]], assert.success(function(result) {
127+
var names = result.rows[0].names;
128+
assert.lengthIs(names, 3);
129+
assert.equal(names[0][0], 1);
130+
assert.equal(names[0][1], 100);
131+
132+
assert.equal(names[1][0], 2);
133+
assert.equal(names[1][1], 100);
134+
135+
assert.equal(names[2][0], 3);
136+
assert.equal(names[2][1], 100);
137+
pg.end();
138+
}))
139+
})
140+
125141
}))
126142
})
127143

0 commit comments

Comments
 (0)