当抛出新错误时,sequelize回滚不起作用



我正试图将三个表更新为一个事务。如果其中一个表没有更新,我想回滚它。我尝试手动在MySQL数据库中执行查询,结果很好。但在代码中,它不能正常工作,并且不能回滚。

这是代码,

return sequelize.transaction({
autocommit: false
}, function(t) {
return models.VaccinationCenter.update({
email
}, {
where: {
id: vacId
}
}, {
transaction: t
}).then(function(VaccinationCenter) {
//console.log('---------------VaccinationCenter--------------------------------',VaccinationCenter)
if (VaccinationCenter[0] === 0) {
throw new Error();
//console.log('VaccinationCenter--------------error')
} else {
return models.Person.update({
email
}, {
where: {
email: prevEmail
}
}, {
transaction: t
})
.then(function(Person) {
//console.log('---------------Person--------------------------------',Person);
if (Person[0] === 0) {
//console.log('Person--------------error');
throw new Error();
} else {
return models.User.update({
email
}, {
where: {
email: prevEmail
}
}, {
transaction: t
})
.then(function(User) {
if (User[0] === 0) {
//console.log('User--------------error');
throw new Error();
} else {
callback({
statusCode: Constants.errorStatus.SUCCESS,
body: {
isValidemail: true
}
});
}
//console.log('---------------User--------------------------------',User)
});
}
});
}
});
}).then(result => {
callback({
statusCode: Constants.errorStatus.SUCCESS,
body: {
isValidemail: true
}
});
}).catch(error => {
callback({
statusCode: Constants.errorStatus.BAD_REQUEST,
body: {
isValidEmail: false
}
});
});

这是运行此代码时的控制台。

Executing (f4d0d13f-d72e-4cb7-bd1b-c26e6ceddaca): START TRANSACTION;
Executing (f4d0d13f-d72e-4cb7-bd1b-c26e6ceddaca): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (f4d0d13f-d72e-4cb7-bd1b-c26e6ceddaca): SET autocommit = 0;
Executing (default): UPDATE `VaccinationCenters` SET `email`='devakadabare1+12@gmail.com',`updatedAt`='2020-03-03 10:06:14' WHERE `id` = 60
Executing (default): UPDATE `People` SET `email`='devakadabare1+12@gmail.com',`updatedAt`='2020-03-03 10:06:14' WHERE `email` = 'devakadabare1+11@gmail.com'
Executing (f4d0d13f-d72e-4cb7-bd1b-c26e6ceddaca): ROLLBACK;

使用托管事务时,不应手动提交或回滚事务。如果所有查询都成功了,但您仍然想回滚事务(例如,由于验证失败(,则应该抛出一个错误来断开并拒绝链。例如:

return sequelize.transaction(function (t) {
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(function (user) {
// Woops, the query was successful but we still want to roll back!
throw new Error();
});
});

有关更多详细信息,请查看文档

最新更新