Skip to content

Instantly share code, notes, and snippets.

@whitelynx
Created June 21, 2013 17:26
Show Gist options
  • Save whitelynx/5832817 to your computer and use it in GitHub Desktop.
Save whitelynx/5832817 to your computer and use it in GitHub Desktop.
Example of possible usage for hstore type conversion.
var util = require('util');
var _ = require('lodash');
var pg = require('pg');
/**
* Convert a JavaScript object to the PostgreSQL `hstore` format.
*
* @param object e.g. {a:1, b:2, c:3}
* @return e.g. 'a=>1,b=>2,c=>3'
*/
function hstore(object)
{
return _.map(object,
function(value, key)
{
return util.format('"%s"=>"%s"', key, value);
}).join(',');
} // end hstore
pg.connect({},
function(err, client, done)
{
if(err)
{
console.error('Error connecting to PostgreSQL: %s', err.stack || err.toString());
process.exit(1);
} // end if
client.query(
{
text: "SELECT keyValuePairs -> 'some' AS someValue FROM (VALUES ($1::hstore)) AS sub (keyValuePairs)",
values: [hstore({some: 'properties', "go here": 33})],
},
function(err, result)
{
if(err)
{
console.error('Error running query: %s', err.stack || err.toString());
console.log(util.inspect(err, {colors: true}));
process.exit(1);
} // end if
console.log(util.inspect(result.rows, {colors: true}));
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment