What is pg-hstore?
The pg-hstore npm package is a node.js library for serializing and deserializing JSON data to hstore format for use with PostgreSQL. Hstore is a key-value store within PostgreSQL that allows for the storage of sets of key-value pairs within a single PostgreSQL value.
What are pg-hstore's main functionalities?
Serialize JSON to hstore format
This feature allows you to convert a JSON object into an hstore string format that can be stored in a PostgreSQL database.
const hstore = require('pg-hstore')();
const obj = { key1: 'value1', key2: 'value2' };
hstore.stringify(obj, function(err, hstoreValue) {
console.log(hstoreValue); // Output: '"key1"=>"value1", "key2"=>"value2"'
});
Deserialize hstore format to JSON
This feature allows you to convert an hstore string from a PostgreSQL database back into a JSON object.
const hstore = require('pg-hstore')();
const hstoreValue = '"key1"=>"value1", "key2"=>"value2"';
hstore.parse(hstoreValue, function(err, result) {
console.log(result); // Output: { key1: 'value1', key2: 'value2' }
});
Other packages similar to pg-hstore
sequelize
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It supports many features including transactions, relations, and migrations. Unlike pg-hstore, which is focused specifically on hstore serialization and deserialization, Sequelize provides a full ORM solution with broader database interaction capabilities.
pg-promise
pg-promise is a PostgreSQL interface for Node.js that provides a flexible and powerful way to interact with PostgreSQL databases. It supports query building, transactions, and connection management. While pg-promise does not specifically focus on hstore, it can be used in conjunction with pg-hstore to handle hstore data types.
pg-hstore
A node package for serializing and deserializing JSON data to hstore format
Install pg-hstore
$ npm install pg-hstore
Usage
stringify
var hstore = require('pg-hstore')();
var source = { foo: "oof", bar: "rab", baz: "zab" };
hstore.stringify(source, function(result) {
...
...
});
parse
var hstore = require('pg-hstore')();
var source = '"foo"=>"oof", "bar"=>"rab", "baz"=>"zab"';
hstore.parse(source, function(result) {
...
...
});