【问题标题】:Why does insert query results remain in database after transaction rollback? pg-promise为什么事务回滚后insert查询结果还保留在数据库中? pg-promise
【发布时间】:2018-10-05 06:32:36
【问题描述】:

我最近在我的一个项目中实现了 pg-promise,并试图了解交易的功能。我正在使用以下功能进行测试:

testFunction: (req, res, next) => {
    db.tx(async t =>{
         await db.any('insert into services (servicename, price, itemcode, servicedescription, active, subscriptionid) values ($1, $2, $3, $4, $5, $6) returning *;', ['babysitting', 25, '12321', 'taking care of children', true, 1])
         await db.any('insert into orangutans (name, age, sex) values ($1, $2, $3)', ['beau', 22, 'male'])
    })
    .then(data=>{
        res.json(data)
    })
    .catch(error=>{
        res.json(error)
    })
}

我根据 pg-promise 文档中的以下示例对这段代码进行了建模:

db.tx(async t => {
    await t.none('UPDATE users SET active = $1 WHERE id = $2', [true, 123]);
    await t.one('INSERT INTO audit(entity, id) VALUES($1, $2) RETURNING id', ['users', 123]);
})
    .then(data => {
        // success, COMMIT was executed
    })
    .catch(error => {
        // failure, ROLLBACK was executed
    });

第一个查询成功运行并将一条记录插入数据库。第二个查询失败,因为关系 'orangutans' 不存在。我希望第一个查询插入的记录作为事务回滚的一部分从数据库中删除。当我在执行此代码后检查数据库时,记录仍保留在数据库中。有人可以指出正确的方向以了解为什么没有删除记录吗?

【问题讨论】:

    标签: node.js pg-promise


    【解决方案1】:

    我一打开问题就看到了我的答案。我在'db'而不是't'上调用.any。我一做出这个改变,它就起作用了。

    【讨论】:

    • 是的,在事务中使用错误的连接上下文会导致一些混乱的结果。您必须始终使用事务提供的正确连接上下文。
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 2017-07-22
    • 2018-10-14
    • 1970-01-01
    • 2017-10-14
    • 2021-06-20
    • 1970-01-01
    • 2020-08-06
    相关资源
    最近更新 更多