2
I am writing backend code using javascript, Node and npm 'mysql' and 'request' modules. I tried to write a module to make a pooling of SQL database connections by different API calls in various files of my project. My mysqlLib.js module:
var mysql = require('mysql');
var pool = mysql.createPool({
host : settings.host_DB,
user : settings.user_DB,
password : settings.senha_DB,
database : settings.DB
});
module.exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
conn.release();
});
};
When finishing this module I decided to test with a Tester.js file
var mysql = require('./lib/mysqlLib.js');
var request = require('request');
mysql.getConnection(function(err, conn) {
conn.query(query1, function(err) {
conn.query(query2, function(err) {
request.get(url1, function(err, httpResponse, body){
conn.query(query3);
});
});
});
});
In fact, the code accomplished what I wanted it to do: Every time I need to make changes to my database through some middleware in the API I wrote to any of my files, use the mysqlLib.js getConnection method to pull a connection from my pool and at the end of the use release it back into the pool. What’s bothering me is that I noticed something that should be leading this little program to an error and it’s not... You see, the function 'Conn.query(query, callback)' is asynchronous, that is to say it does not interrupt the flow of code. Thus, I thought that by performing the first invocation of 'Conn.query' in Tester.js, this function would be run asynchronously allowing the callback of getConnection to come to an end. Shouldn’t that mean the program would finish callback and release() the connection that was pulled? I thought I could call the first Conn.query but once callback reached its end and the connection was released I could not accomplish the other nested queries at first for lack of it but they are all being executed without error! I wonder what may possibly be happening, why the connection is released only after the termination of all the nested callbacks in the callback of getConnection?
I have little experience in Ode.js, but I’ll take a guess: it may be that function
conn.release()
has a check to avoid closing connections that are being used in queries, so the code stops in therelease
and only continues when the callback ofconn.query()
returns.– Dinei