From 79c5faf547039674f0df4f796bd00b58a3456a3b Mon Sep 17 00:00:00 2001 From: Brian Carlson Date: Fri, 21 Jan 2011 16:53:24 -0600 Subject: [PATCH] first pass at array type conversion --- lib/query.js | 28 ++++++++++++++++++++++ test/integration/client/array-tests.js | 33 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 test/integration/client/array-tests.js diff --git a/lib/query.js b/lib/query.js index 5f4f35f..e303df5 100644 --- a/lib/query.js +++ b/lib/query.js @@ -223,5 +223,33 @@ var dataTypeParsers = { 1184: dateParser }; +Query.registerParser = function(typeOid, parseFunction) { + dataTypeParsers[typeOid] = parseFunction; +}; + + +//parses integer arrays +Query.registerParser(1007, function(val) { + return JSON.parse(val.replace("{","[").replace("}","]")); +}); + +//parses string arrays +//this only works in happy cases +//does not yet support strings with , or { or } +Query.registerParser(1009, function(val) { + if (!val) return null; + if (val[0] !== '{' || val[val.length-1] !== '}') + throw "Not postgresql array! (" + arrStr + ")"; + + var x = val.substring(1, val.length - 1); + x = x.match(/(NULL|[^,]+|"((?:.|\n|\r)*?)(?!\\)"|\{((?:.|\n|\r)*?(?!\\)\}) (,|$))/mg); + if (x === null) throw "Not postgre array"; + return x.map(function (el) { + if (el === 'NULL') return null; + if (el[0] === '{') return arguments.callee(el); + if (el[0] === '\"') return el.substring(1, el.length - 1).replace('\\\"', '\"'); + return el; + }); +}); module.exports = Query; diff --git a/test/integration/client/array-tests.js b/test/integration/client/array-tests.js new file mode 100644 index 0000000..c45882d --- /dev/null +++ b/test/integration/client/array-tests.js @@ -0,0 +1,33 @@ +var helper = require(__dirname + "/test-helper"); +var pg = helper.pg; +var conString = helper.connectionString(); + +test('parsing array results', function() { + pg.connect(conString, assert.calls(function(err, client) { + assert.isNull(err); + client.query("CREATE TEMP TABLE why(names text[], numbors integer[])"); + client.query('INSERT INTO why(names, numbors) VALUES(\'{"aaron", "brian","a b c" }\', \'{1, 2, 3}\')').on('error', console.log); + test('numbers', function() { + // client.connection.on('message', console.log) + client.query('SELECT numbors FROM why', assert.success(function(result) { + assert.length(result.rows[0].numbors, 3); + assert.equal(result.rows[0].numbors[0], 1); + assert.equal(result.rows[0].numbors[1], 2); + assert.equal(result.rows[0].numbors[2], 3); + })) + }) + + test('parses string arrays', function() { + client.query('SELECT names FROM why', assert.success(function(result) { + var names = result.rows[0].names; + assert.length(names, 3); + assert.equal(names[0], 'aaron'); + assert.equal(names[1], 'brian'); + assert.equal(names[2], "a b c"); + pg.end(); + })) + }) + })) +}) + +