Following this tutorial I have promisified the mysql library which allows me to use .then
instead of the callback functions.
Here is my setup for the mysql pool:
var mysql = require('mysql')
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'matt',
password: 'password',
database: 'my_database'
})
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
pool.query = util.promisify(pool.query)
module.exports = pool
This setup has made my life so much easier until a point now where I do not know how to handle rollback transaction.
I am running queries like this:
pool.query('InsertQuery').then(rows=>{
return pool.query(`Select LocationID from Locations where LocationName = '${location[i]}'`)
})
.then(rows=>{
locationID =rows[0].LocationID
return pool.query(`Select StageID from Stages where StageName = '${stage[i]}'`)
})
.then('anotherInsert')....
.catch(err=>{
console.log(err)
})
The catch block at the end is working perfectly as the execution breaks whenever there is an error at any of the stage. But I want to be able to rollback transactions and not have a single query run if there are any issues with any of the queries. Is there a way to achieve this?