mysql Seqelize事务回滚不起作用

6tdlim6h  于 2023-02-28  发布在  Mysql
关注(0)|答案(1)|浏览(149)

我使用Sequelize作为MySQL数据库的ORM。在下面的代码中,即使调用了回滚,它也不工作。
它应该回滚表'numberseqs'中的值,但即使执行了代码的catch部分,它也会继续增加。也就是说,我确认回滚已经执行。

async create(req, res) {
        const t = await SEQUELIZE.transaction()
        let lastGenerated = 0
        try
        {
            const numberSeqData = await numberSeq.findOne({ where: { document: 'project' } }, { transaction: t})
            if (numberSeqData)
            {
                lastGenerated = numberSeqData.lastGenerated + 1
                await numberSeq.update({ lastGenerated }, { where: { document: 'project' }},
                { transaction: t}
                )
            }
            else
            {
                throw new Error('NumberSeq not found')
            }
            const projectNew = await project.create({ 
                ProjectNumber : `PRJ-${lastGenerated}`,
                Name: req.body.name,
                Stage: req.body.stage,
                StartDate: req.body.startDate,
                EndDate: req.body.endDate,
                Description: req.body.description,
                IsActive: req.body.isActive,
            },{ transaction: t})
            await t.commit()
            res.status(200).send(projectNew)
        }
        catch(err)
        {
            await t.rollback()
            res.status(400).send(err)
        }
    }```

I tried setting up the transaction isolation level, but it didn't helped.
eiee3dmh

eiee3dmh1#

您在findOneupdate中错误的位置指示了事务ttransaction选项应该位于where选项的旁边:

const numberSeqData = await numberSeq.findOne({
  where: { document: 'project' },
  transaction: t
})
if (numberSeqData)
{
  lastGenerated = numberSeqData.lastGenerated + 1
  await numberSeq.update({ lastGenerated }, {
    where: { document: 'project' },
    transaction: t
  })
}

相关问题