【发布时间】: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