Merge pull request #278 from adunstan/master
Allow passing a JS array instead of an array literal where SQL expects an array
This commit is contained in:
commit
c6d5f43473
31
lib/utils.js
31
lib/utils.js
@ -13,6 +13,34 @@ if(typeof events.EventEmitter.prototype.once !== 'function') {
|
||||
};
|
||||
}
|
||||
|
||||
// convert a JS array to a postgres array literal
|
||||
// uses comma separator so won't work for types like box that use
|
||||
// a different array separator.
|
||||
function arrayString(val) {
|
||||
var result = '{';
|
||||
for (var i = 0 ; i < val.length; i++) {
|
||||
if (i > 0) {
|
||||
result = result + ',';
|
||||
}
|
||||
if (val[i] instanceof Date) {
|
||||
result = result + JSON.stringify(val[i]);
|
||||
}
|
||||
else if(typeof val[i] === 'undefined') {
|
||||
result = result + 'NULL';
|
||||
}
|
||||
else if (Array.isArray(val[i])) {
|
||||
result = result + arrayString(val[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result +
|
||||
(val[i] === null ? 'NULL' : JSON.stringify(val[i]));
|
||||
}
|
||||
}
|
||||
result = result + '}';
|
||||
return result;
|
||||
}
|
||||
|
||||
//converts values from javascript types
|
||||
//to their 'raw' counterparts for use as a postgres parameter
|
||||
//note: you can override this function to provide your own conversion mechanism
|
||||
@ -24,6 +52,9 @@ var prepareValue = function(val) {
|
||||
if(typeof val === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
if (Array.isArray(val)) {
|
||||
return arrayString(val);
|
||||
}
|
||||
return val === null ? null : val.toString();
|
||||
};
|
||||
|
||||
|
@ -122,6 +122,22 @@ test('parsing array results', function() {
|
||||
}))
|
||||
})
|
||||
|
||||
test('JS array parameter', function(){
|
||||
client.query("SELECT $1::integer[] as names", [[[1,100],[2,100],[3,100]]], assert.success(function(result) {
|
||||
var names = result.rows[0].names;
|
||||
assert.lengthIs(names, 3);
|
||||
assert.equal(names[0][0], 1);
|
||||
assert.equal(names[0][1], 100);
|
||||
|
||||
assert.equal(names[1][0], 2);
|
||||
assert.equal(names[1][1], 100);
|
||||
|
||||
assert.equal(names[2][0], 3);
|
||||
assert.equal(names[2][1], 100);
|
||||
pg.end();
|
||||
}))
|
||||
})
|
||||
|
||||
}))
|
||||
})
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user