As I understand it, everyone pool.query()
will be worth the connection, and it will automatically be released when it ends. based on this comment github issue . But what about nested queries executed with pool.getConnection()
?
pool.getConnection(function(err, connection) {
connection.query('query_1', function (error, results, fields) {
connection.query('query_2', function (error, results, fields) {
connection.release();
if (error) throw error;
});
});
});
UPDATE
Here is my code using a transaction when executing nested queries.
const pool = require('../config/db');
function create(request, response) {
try {
pool.getConnection(function(err, con) {
if (err) {
con.release();
throw err;
}
con.beginTransaction(function(t_err) {
if (t_err) {
con.rollback(function() {
con.release();
throw t_err;
});
}
con.query(`insert record`, [data], function(i_err, result, fields){
if (i_err) {
con.rollback(function() {
con.release();
throw i_err;
});
}
const id = result.insertId;
con.query(`update query`, [data, id], function(u_err, result, fields)=> {
if (u_err) {
con.rollback(function() {
con.release();
throw u_err;
});
}
con.commit(function(c_err){
if (c_err) {
con.release();
throw c_err;
}
});
con.release();
if (err) throw err;
response.send({ msg: 'Successful' });
});
});
});
});
} catch (err) {
throw err;
}
}
I made a lot of protective mistakes and con.release()
, since at the moment I do not know how to properly release each active connection.
And I also assume that everyone con.query()
inside pool.getConnection()
will be worth the mix.
source
share