diff --git a/lib/utils.js b/lib/utils.js index 44d83421..273decb8 100644 --- a/lib/utils.js +++ b/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(); }; diff --git a/test/integration/client/array-tests.js b/test/integration/client/array-tests.js index dde3e5dd..074665b6 100644 --- a/test/integration/client/array-tests.js +++ b/test/integration/client/array-tests.js @@ -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(); + })) + }) + })) })