felixge/node-mysql — pull request #762 by calibr (2014-03-16 22:12:51+00:00)
Title: lazy getting connections from pool

Hello, sorry for my English, it's my first pool request.
In some projects there are required to use One mysql connection per HTTP request, but in some cases such requests don't need a mysql connection, for example if response is cached or auth failed, etc.

- When use connections pool, need to extra call Pool.getConnection to obtain connection, it's complicates code.
- If request connection from pool for every http connection - size of pool grows up very fast in projects with large amount of http requests.

I write class that proxy calls to mysql connection, and get it from pool only if user really need it.
It works like a Connection object( but for pooled connections ) when it lazily connects on user request.

Simple example:

```javascript

var pool = mysql.createPool({...});
var conn = pool.getLazyConnection();
conn.query("SELECT fields FROM data", function(){
// do something
conn.release();
});

```
More complex example for express:

```javascript

var pool = mysql.createPool({...});

app.use(function( req, res, next ){
req.mysql = pool.getLazyConnection();
res.on("finish", function _onfinish(){
res.removeListener("finish", _onfinish);
// if connection not obtained from pool, the "release" call do nothing
req.mysql.release();
});
next();
});

app.get("/:field", function(req, res){
// condition which defines use mysql or not
if( req.params.field == 1 ){
req.mysql.query("SELECT field FROM data", function( err, data ){
res.send("QUERY");
});
}
else{
res.send("OK");
}
});

```

This approach to get connections is similar to JAVA class [LazyConnectionDataSourceProxy](http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.html)