Skip to content

Commit c6d5f43

Browse files
committed
Merge pull request brianc#278 from adunstan/master
Allow passing a JS array instead of an array literal where SQL expects an array
2 parents bc71000 + c5b88db commit c6d5f43

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

lib/utils.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,34 @@ 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+
}
25+
if (val[i] instanceof Date) {
26+
result = result + JSON.stringify(val[i]);
27+
}
28+
else if(typeof val[i] === 'undefined') {
29+
result = result + 'NULL';
30+
}
31+
else if (Array.isArray(val[i])) {
32+
result = result + arrayString(val[i]);
33+
}
34+
else
35+
{
36+
result = result +
37+
(val[i] === null ? 'NULL' : JSON.stringify(val[i]));
38+
}
39+
}
40+
result = result + '}';
41+
return result;
42+
}
43+
1644
//converts values from javascript types
1745
//to their 'raw' counterparts for use as a postgres parameter
1846
//note: you can override this function to provide your own conversion mechanism
@@ -24,6 +52,9 @@ var prepareValue = function(val) {
2452
if(typeof val === 'undefined') {
2553
return null;
2654
}
55+
if (Array.isArray(val)) {
56+
return arrayString(val);
57+
}
2758
return val === null ? null : val.toString();
2859
};
2960

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)