node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Are there any examples using node-postgres with control flow lib?

Open alexhanh opened this issue 13 years ago • 14 comments

Desperately trying to find some examples that would use the async lib or something similar to avoid excessive nesting with series and parallel queries.

alexhanh avatar Nov 24 '13 19:11 alexhanh

Does this help? I'm doing something similar in my current project.

var pg = require('pg');
var async = require('async');

pg.connect('postgresql://user:pass@localhost:5432/test', function (err, client, done) {
  var queue = [];

  queue.push(client.query.bind(client, 'select generate_series(1,5)'));
  queue.push(client.query.bind(client, 'select generate_series(6,10)'));
  queue.push(client.query.bind(client, 'select generate_series(11,15)'));
  queue.push(client.query.bind(client, 'select generate_series(16,20)'));

  async.series(queue, function (err, results) {
    for (var i in results) {
      for (var j in results[i].rows) {
        console.log(results[i].rows[j]);
      }
    }
    done();
  });
});

Output will be:

{ generate_series: 1 }
{ generate_series: 2 }
{ generate_series: 3 }
{ generate_series: 4 }
{ generate_series: 5 }
{ generate_series: 6 }
{ generate_series: 7 }
{ generate_series: 8 }
{ generate_series: 9 }
{ generate_series: 10 }
{ generate_series: 11 }
{ generate_series: 12 }
{ generate_series: 13 }
{ generate_series: 14 }
{ generate_series: 15 }
{ generate_series: 16 }
{ generate_series: 17 }
{ generate_series: 18 }
{ generate_series: 19 }
{ generate_series: 20 }

benighted avatar Nov 25 '13 15:11 benighted

@benighted pretty much nailed it. Using pg with the async library is no different than using any other callback interface with the async library except you need to check out a client from the pool before you run queries on it. And then make sure you release the client back to the pool when your async operations have finished..

brianc avatar Nov 25 '13 15:11 brianc

Perfect! Would the above example work with async.parallel if we just changed the series call to parallel? The way I did it was:

function q(user_id, callback) {

  var q1 = function(callback) {
    pg.connect(conString, function(err, client, done) {
      if (err) return callback(err);

      client.query('...', [user_id], function(err, result) {
        done();
        if (err) return callback(err);
        callback(null, balance);
      });
    });    
  }

  var q2 = function(callback) {
    pg.connect(conString, function(err, client, done) {
      if (err) return callback(err);

      client.query('...', [user_id], function(err, result) {
        done();
        if (err) return callback(err);
        callback(null, balance);
      });
    });    
  }


  async.parallel([
    q1,
    q2
  ], function(err, results) {
    if (err) return callback(err);
    return callback(null, results[0].add(results[1]) );
  });
}

Also, are there any gotchas when using connection pooling, like we are here with pg.connect, when dealing with transactions and locks?

alexhanh avatar Nov 25 '13 15:11 alexhanh

Yes it will work the same with parallel, though obviously your queries may not complete in the order you specify.

Make sure that you commit or rollback your transaction before calling done(), since I do not know if pg protects you from returning the connection to the pool with an open transaction (which could be very, very bad). @brianc, can you confirm this?

benighted avatar Nov 25 '13 18:11 benighted

I may have just realized I should be using an abstraction on top of node-postgres. However, the offerings seems to be quite fragmented. Anyway I'd love to see an example with transactions using control flow!

alexhanh avatar Nov 25 '13 23:11 alexhanh

@alexhanh awesome questions!

@benighted I really appreciate your help on this one.

To be perfectly honest I find it extremely cumbersome to do transactions elegantly with node due to it's async nature and the very serial nature of transactions on a connection. Let me try to elaborate/ramble a bit...

First in your example @alexhanh you are checking out a client for each of your two queries. node-postgres will not guarantee you get the same client for both queries and since you're using async.parallel it's extremely likely you are not getting the same client for each query. When you have two independent queries this will work in your favor; however, if you're doing transactions and need the queries to be on the same client this is a very bad thing because you'll issue your being statement on one client and then the another client will receive the commit. That will cause errors, problems, consistency issues, all that fun stuff....

Let me start by saying the overhead in establishing a new connection to the backend PostgreSQL database is non-trivial. Couple that overhead with the fact that in a web environment you will eventually have an unbounded number of requests coming in and the PostgreSQL backend will absolutely not support an unbounded number of connections it's very bad to create a client manually in a web type of set-up. If you're doing backend scripts or special things like LISTEN/NOTIFY you'll need clients connected via the new pg.Client constructor, otherwise always try to use pg.connect(/*...*/) for acquiring clients....so you're on the right track. What you need to do is call pg.connect once and then kick off your async actions but maintain a reference to the client object returned to the callback of pg.connect if that makes sense?

Recently I've run into a few scenarios where I need good transaction helpers, and haven't found anything in the current offerings that really scratches my itch. Next time I hit this issue I'll set aside some time to roll a module up with what I think is a clear way to do things and share it here.

brianc avatar Nov 27 '13 05:11 brianc

@brianc, @benighted: Thank you guys for your elaborate answers.

@brianc: That makes perfect sense. I came to a similar conclusion that transactions and (deeply) chained queries where quite cumbersome todo, resulting in a callback soup or otherwise code with a lot of overhead. I come from a Ruby background, and I think it has the most elegant of doing transactions (http://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html for example). But that is the obvious benefit of synchronous platforms.

Based on your description, the way transactions should work is by checking out a connection from the pool for the duration of the transaction and return it once it's completed or rolled back. If the pool is empty, then wait until a connection comes available or timeout.

  • It seems Bookshelf.js is the only package that supports transactions with pooling. But I found the syntax to be quite unreadable http://bookshelfjs.org/#Bookshelf-transaction.
  • Sequalize.js just added experimental transaction support (https://github.com/sequelize/sequelize/tree/features/transactions) but note that it'll ignore the pool and open a new connection per transaction (https://github.com/sequelize/sequelize/pull/1062#issuecomment-29250879).
  • I think patio (http://c2fo.github.io/patio) feels the most right. It lets you choose the abstraction level (ORM, Datasets or plain SQL) and doesn't force you todo things in a certain way. Transactions are quite readable as well http://c2fo.github.io/patio/patio_Database.html#transaction. However, I'm not sure about its support for pooling with transactions.
  • prego (https://github.com/sergeych/node-prego) looks promising, but is in beta. It says it duplicates the connection object when transacting, thus I'd imagine it doesn't support pooling (https://github.com/sergeych/node-prego/wiki/Transactions).
  • node-orm supports transactions, but is broken with pooling (see https://github.com/dresende/node-orm-transaction/issues/2 and https://github.com/dresende/node-orm2/issues/284).

alexhanh avatar Nov 27 '13 10:11 alexhanh

Great discussion all. Let me add my two cents... as i did my time fighting through these same issues as i came up the learning curve on writing apps (and specifically database apps) in node.

First of all, the package that i use to manage transactions and pooling on top of node-postgres is node-any-db (https://github.com/grncdr/node-any-db). it works great, and plays well with node-postgres. I also use gesundheit (https://github.com/BetSmartMedia/gesundheit) by the same author (@grncdr) on top of it for query building, but you don't need to if it doesn't suit you. Been very happy with these.

In terms of node control flow libraries: there are many approaches, and many opinions on this. But after having written lots of code using first plain node callbacks, and then using async (https://github.com/caolan/async), i found streamline (https://github.com/Sage/streamlinejs) and never looked back. Streamline rocks! i can't say enough good things about it. It removes tons of boilerplate code (our codebase shrunk by probably 1/3), centralizes error handling, and creates a much more readable and maintainable codebase. Look at the sample before and after code at the top of the Streamline readme to get a sense for how it works. Definitely worth giving it a spin.

spollack avatar Nov 27 '13 16:11 spollack

Tust to add to what @spollack has said, any-db provides connection pools & transactions objects (that work well together) for postgres, mysql, and sqlite3.

@brianc said:

Recently I've run into a few scenarios where I need good transaction helpers, and haven't found anything in the current offerings that really scratches my itch.

I'm curious if you've looked at any-db's Transaction API recently, and in particular since support for nested transactions was added. I'm very interested in any criticisms/suggestions you may have!

On the subject of control flow: I find the natural thing to do (especially in a web app scenario) is to start a transaction at the beginning of a request and use it for most/all queries in the request:

var pool = anyDB.createPool(...);
function transactionMiddleware (req, res, next) {
  req.tx = pool.begin();
  next();
  var end = res.end;
  res.end = function () {
    // auto-commit transaction if it's still open at the end of the request
    if (req.tx.state() != 'closed') {
      var args = [].slice.call(arguments);
      req.tx.commit(function (err) {
        if (err) end.call(res, err)
        else end.apply(res, args);
      })
    } else {
      end.apply(res, arguments);
    }
  }
}

Then in your web-app, req.tx provides the same API as a postgres client. E.g. your database queries would be things like req.tx.query('INSERT ...', function (err) {...}) and so on.

This is simple to implement and leverages the power of the database server to manage concurrent updates etc. However it doesn't allow for parallel queries (since a transaction can only be used by the connection that started it). So for parallel queries, you will want to query directly against the pool: pool.query('SELECT ...', function (err, result) {...}). This only makes sense when you are performing read queries that don't rely on writes that occurred in your request transaction, which is actually pretty common.

Anyways, that's the way I do it, YMMV :smile:

grncdr avatar Nov 28 '13 17:11 grncdr

node-any-db is great for transactions and pooling! I use it heavily. The nested transactions functionality look cool. I haven't tried them yet, but I do need them.

My only criticism is the recent repo changes make finding the documentation very difficult. I think having separate repos for each supported database is fine, but the separation of docs and transactions into separate repos makes it hard to find the more detailed documentation. I also think separating out pieces of core (i.e. transactions) makes it harder to find the right code to contribute to.

Even so, it is by far the best Node.js module for transactions and connection pooling in my opinion.

rpedela avatar Jan 03 '14 16:01 rpedela

on this topic of node control flow: i just published a blog post explaining why we chose node + streamline for our platform, here: http://bit.ly/KtMIYS I've had enough one-off conversations explaining it that i figured it was time to write it down!

spollack avatar Jan 07 '14 19:01 spollack

Nice!

brianc avatar Jan 07 '14 19:01 brianc

thanks @brianc !

spollack avatar Jan 07 '14 19:01 spollack

If you are willing to try out unstable version of node (0.11.x), you can try harmony generators.

var result = yield query(sql);
console.log(result);

It does not get any more sync-like than that. I am using co-pg which is based on node-postgres.

serkanserttop avatar Aug 02 '14 01:08 serkanserttop