0.1.1 • Published 9 years ago
promise-pg v0.1.1
#promise-pg
Q promises wrapper for the node.js PostgreSQL client 'pg'.
Install
$ npm install promise-pg
Examples
Basic access
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 //if set to true, adds all the rows to the result object available on the rows property on the promise resolve value
}).promise.then(
function(result) { console.log(result); }, //rowCount etc
function(err) { throw err; },
function(user) {} //for each row
).finally(done);
}).done();
Transactions
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() {
//This code runs in a transaction and should return a promise object, that when resolved the transaction is committed
//But when rejected the transaction is rolled back.
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."); //This will happen
}, function(err) {
console.log("Bad - Rolled back Transaction I.", err);
}); //Not returning the connection to the pool yet
trans.finally(function() { //after this transaction
client.transaction(function() {
//This code runs in a transaction and should return a promise object, that when resolved the transaction is committed
//But when rejected the transaction is rolled back.
return Q.all([
{
text: INSERT,
values: ["Jake", "now()", "Oo"]
},
{
text: INSERT, //Bad, name is NOT NULL
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."); //Cannot commit due to bad name
}, function(err) {
console.log("Good - Rolled back Transaction II.", err.message);
}).finally(done).done();
});
}).done();
Contributing
We appreciate any contributions!
If you need help getting the package to run, please feel free to message me .