Maaz Anzar
Maaz Anzar

Reputation: 141

Sequelize transaction does not rollback when exception throws

I want to implement transcation in sequelize. But After Applying transaction Code does not roll back currently inserted row. Can some assist me what i am doing wrong? Package.json version is "sequelize": "^4.39.0","sequelize-cli": "^3.2.0",

 let sequelize = model.sequelize;
    return sequelize.transaction().then(function (t) {
        return model.error_logs.create(
            error_logs, { transaction: t }).then(function (user) {
            error_logs.stack = 'For Checking Transcation'
            return models.error_logs.create(error_logs, { transaction: t }); <-- Here I am creating expection
        }).then(function () {
            t.commit();
        }).catch(function (err) {
            t.rollback();
        });
    });

Upvotes: 0

Views: 2966

Answers (1)

Anatoly
Anatoly

Reputation: 22803

You should await each operation in transaction before each other and before a transaction ends like this:

const transaction = await sequelize.transaction()
try {
  const newLog = await model.error_logs.create(error_logs, { transaction: transaction })
  error_logs.stack = 'For Checking Transcation'
  const anotherNewLog = await model.error_logs.create(error_logs, { transaction: transaction })
  await transaction.commit()
} catch (err) {
  await transaction.rollback()
}

Solution 2:

const transaction = await sequelize.transaction(async transaction => {
  const newLog = await model.error_logs.create(error_logs, { transaction: transaction })
  error_logs.stack = 'For Checking Transcation'
  const anotherNewLog = await model.error_logs.create(error_logs, { transaction: transaction })
})

Upvotes: 1

Related Questions