Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-mysql - when to release connection back into pool

I'm using the node-mysql driver with connection pooling.

Releasing the connection back into the pool when there's only one query, is easy:

pool.getConnection(function(err, connection) {
  if (err) {
    throw err;
  }

  query = "SELECT * FROM user WHERE id = ?";
  connection.query(query, [id], function(err, users) {
    connection.release();

    if (err) {
      throw err;
    }

    // ...
  });
});

What if I need to use the connection a second time? I'd have to move the release() down a few lines. But what happens if the error is thrown? Is the connection never returned to the pool?

Do I have to use some control flow lib to have a "finally" moment in which I could release it?
Any better ideas?

like image 373
Philipp Kyeck Avatar asked Feb 12 '14 22:02

Philipp Kyeck


People also ask

When should I use connection pooling?

Connection pooling is great for scalability - if you have 100 threads/clients/end-users, each of which need to talk to the database, you don't want them all to have a dedicated connection open to the database (connections are expensive resources), but rather to share connections (via pooling).

What is the difference between connection and connection pool?

Instead of opening and closing connections for every request, connection pooling uses a cache of database connections that can be reused when future requests to the database are required. It lets your database scale effectively as the data stored there and the number of clients accessing it grow.

How do you release a pool connection?

You can disable Pooling by adding 'Pooling=false' to the connection string. In such case, a connection will be deleted from memory and free the session.

How does MySQL connection pooling work?

The MySQL Connection Pool operates on the client side to ensure that a MySQL client does not constantly connect to and disconnect from the MySQL server. It is designed to cache idle connections in the MySQL client for use by other users as they are needed.


1 Answers

One way this could be handled is promises. Since you're building a pool, you can construct your requests with something like q (or native promises, coming soon):

// assuming you have your local getConnection above or imported
exports.getConnection = function(queryParams) {
    var d = q.defer();
    local.getConnection(function(err, conn) {
        if(err) d.reject(err);
        d.resolve(conn);
    });
});

So, wrap few of your other calls into promises like that and then just compose your query:

db.getConnection()
.then(function(conn){
    makeRequest()
    .then(...)
    ...
.catch(function(err){
    // at the end you release the conn
});

Does it seem like something you're asking for?

like image 154
Zlatko Avatar answered Sep 28 '22 16:09

Zlatko