我的项目中使用托管交易,我有一个需求需要在出现失败情况时回滚到保存点,并最终提交事务。
例如,我想要创建一个 Event
并尝试运行一个action
。如果action
失败,我想回滚任何在此期间发生的数据库活动,但保留 Event
记录并随后使用结果更新它。
const transaction = await sequelize.transaction();
const event = await Event.create({ ... }, { transaction });
// I want to mark the savepoint here
try {
const action = await runAction(transaction);
event.status = 'success';
event.action_id = action.id;
} catch (err) {
// This is where I want to rollback any changes since the savepoint
event.status = 'failure';
event.failure_message = err.message;
}
await event.save({ transaction });
await transaction.commit();
据我的理解,我应该能够通过创建一个新的事务来实现这一点,有效地标记保存点:
const transaction = await sequelize.transaction();
const event = await Event.create({ ... }, { transaction });
const savepoint = await sequelize.transaction({ transaction });
try {
const action = await runAction(savepoint);
...
} catch (err) {
await savepoint.rollback();
...
}
await event.save({ transaction });
await transaction.commit();
然而这并不起作用,而且在“runAction”中使用事务的所有操作仍然被提交。有没有办法实现这一点?