gpt4 book ai didi

mysql - 抛出新错误时, Sequelize 回滚不起作用

转载 作者:行者123 更新时间:2023-12-03 22:25:59 24 4
gpt4 key购买 nike

我正在尝试将三个表作为事务更新。如果其中一张表没有更新,我想回滚它。我在 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();
});
});

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

关于mysql - 抛出新错误时, Sequelize 回滚不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60504960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com