Q promises wrapper for the node.js PostgreSQL client 'pg'.
Basic Usage.
var pg = require("promise-pg");
pg.connect("postgres://example:1234@localhost:5432/example").spread(function(client, done) {
var query = client.query({
text: "select * from users",
buffer: true
}).promise.then(
function(result) { console.log(result); },
function(err) { throw err; },
function(user) {}
).finally(done);
}).done();
When using transactions you only need to specify a function that will be executed when the connection is within the
transaction, your function returns a promise objects, if it is resolved the transaction is commited, if it is rejected
the transaction is rolled back.
var pg = require("promise-pg");
var Q = require("q");
pg.connect("postgres://example:1234@localhost:5432/example").spread(function(client, done) {
var INSERT = "INSERT INTO users(name, t_birth, country) VALUES ($1, $2, $3);";
console.log("Transaction I:")
var trans = client.transaction(function() {
return Q.all([
{
text: INSERT,
values: ["Jake1", "now()", "Oo"]
},
{
text: INSERT,
values: ["Cake2", null, "Küche"]
},
{
text: INSERT,
values: ["Mike3", "now()", null]
}
].map(function(q) {
return client.query(q).promise;
}));
}).then(function() {
console.log("Good - Committed Transaction I.");
}, function(err) {
console.log("Bad - Rolled back Transaction I.", err);
});
trans.finally(function() {
client.transaction(function() {
return Q.all([
{
text: INSERT,
values: ["Jake", "now()", "Oo"]
},
{
text: INSERT,
values: [null, null, "Küche"]
},
{
text: INSERT,
values: ["Mike", "now()", null]
}
].map(function(q) {
return client.query(q).promise;
}));
}).then(function() {
console.log("Bad - Committed Transaction II.");
}, function(err) {
console.log("Good - Rolled back Transaction II.", err.message);
}).finally(done).done();
});
}).done();
If you need help getting the package to run, please feel free to message me .