Add support for JSON data type

requires >= 9.2 of postgres
This commit is contained in:
bmc 2013-04-22 10:18:17 -05:00
parent 3997b38b44
commit 10e6d85266
4 changed files with 35 additions and 2 deletions

View File

@ -183,6 +183,7 @@ var init = function(register) {
register(1009, parseStringArray);
register(1186, parseInterval);
register(17, parseByteA);
register(114, JSON.parse.bind(JSON));
};
module.exports = {

View File

@ -55,7 +55,10 @@ var prepareValue = function(val) {
if(Array.isArray(val)) {
return arrayString(val);
}
return val === null ? null : val.toString();
if(!val || typeof val !== 'object') {
return val === null ? null : val.toString();
}
return JSON.stringify(val);
};
function dateToString(date) {

View File

@ -0,0 +1,30 @@
var helper = require(__dirname + '/test-helper');
var assert = require('assert');
//if you want binary support, pull request me!
if (helper.config.binary) {
return;
}
test('can read and write json', function() {
helper.pg.connect(helper.config, function(err, client, done) {
assert.ifError(err);
client.query('CREATE TEMP TABLE stuff(id SERIAL PRIMARY KEY, data JSON)');
var value ={name: 'Brian', age: 250, alive: true, now: new Date()};
client.query('INSERT INTO stuff (data) VALUES ($1)', [value]);
client.query('SELECT * FROM stuff', assert.success(function(result) {
assert.equal(result.rows.length, 1);
assert.equal(typeof result.rows[0].data, 'object');
var row = result.rows[0].data;
assert.strictEqual(row.name, value.name);
assert.strictEqual(row.age, value.age);
assert.strictEqual(row.alive, value.alive);
test('row should have "now" as a date', function() {
return false;
assert(row.now instanceof Date, 'row.now should be a date instance but is ' + typeof row.now);
});
assert.equal(JSON.stringify(row.now), JSON.stringify(value.now));
done();
helper.pg.end();
}));
});
});

View File

@ -6,7 +6,6 @@ var withQuery = function(text, resultLength, cb) {
var client = new Client(helper.args);
process.removeAllListeners('uncaughtException');
assert.emits(process, 'uncaughtException', function() {
console.log('got uncaught exception')
assert.equal(client.activeQuery, null, 'should remove active query even if error happens in callback');
client.query('SELECT * FROM blah', assert.success(function(result) {
assert.equal(result.rows.length, resultLength);