I want to start a transaction inside a pool connection. I found this code example in another StackOverflow question (link):
pool.getConnection(function(err, connection) {
connection.beginTransaction(function(err) {
if (err) { //Transaction Error (Rollback and release connection)
connection.rollback(function() {
connection.release();
//Failure
});
} else {
connection.query('INSERT INTO X SET ?', [X], function(err, results) {
if (err) { //Query Error (Rollback and release connection)
connection.rollback(function() {
connection.release();
//Failure
});
} else {
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
connection.release();
//Failure
});
} else {
connection.release();
//Success
}
});
}
});
}
});
});
However I'm unsure about some specific lines in this example.
My first issue is in line 4 with the first connection.rollback(...)
. If beginTransaction()
throws an error, why would you put a rollback here? If it couldn't start a transaction then there's nothing to rollback to, is there? Or is this just a security measure to close any potentially open transactions that may exist even though an error was thrown?
My second issue is with the rollback inside the commit. If the commit fails for whatever reason, wouldn't the rollback fail here as well? In what scenario could the commit fail but the following rollback succeed? Is there any reason other than network failure for the commit to fail?