pg-promise:在事务中的下一个查询中使用一个查询的结果 [英] pg-promise: use result of one query in next query within a transaction

查看:134
本文介绍了pg-promise:在事务中的下一个查询中使用一个查询的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是具有pg-promise的postgres的node.js,尝试按顺序进行2次插入操作。第一个插入的结果ID应在事务的下一个插入中使用。

I am node.js with pg-promise for postgres, trying to do a transaction with 2 inserts in sequence. The result id of the 1st insert should be used in the next insert in the transaction.

如果任何查询失败,将回滚。
在第一个 db的 .then()内嵌套第二个 db.none 。一个不会回滚第一个查询。因此,在这里使用事务。

Rollback if any of the query fails. Nesting 2nd db.none inside .then() of 1st db.one will NOT rollback 1st query. So using a transaction here.

我坚持使用第二个查询中的第一个查询的结果。
这就是我现在拥有的。

I am stuck at using the result of 1st query in 2nd. Here is what I have now.

db.tx(function (t) {
    return t.sequence([
        // generated using pgp.helpers.insert for singleData query
        t.one("INSERT INTO table(a, b) VALUES('a', 'b') RETURNING id"),
        t.none("INSERT INTO another_table(id, a_id) VALUES(1, <above_id>), (2, <above_id>)")
    ]);
})...

第二个查询是使用pgp.helpers.insert生成的,用于multiData查询。但是,要使用上一个查询的结果是不可行的。是不是!

2nd query is generated using pgp.helpers.insert for multiData query. But that's not feasible wanting to use the previous query's result. isn't it !

有没有办法获取 id < above_id> ; 从第1次插入开始?

Is there a way to get id i.e. <above_id> from the 1st INSERT ?

推荐答案

方法序列可以运行无限序列,这与您要实现的目标无关-标准/琐碎的交易:

Method sequence is there to run infinite sequences, which got nothing to do with what you are trying to achieve - a standard / trivial transaction:

db.tx(t => {
    return t.one('INSERT INTO table1(a, b) VALUES($1, $2) RETURNING id', [1, 2], x=>+x.id)
        .then(id => {
            return t.none('INSERT INTO table2(id, a_id) VALUES($1, $2)', [1, id]);
        });
})
    .then(data => {
        // success, data = null
    })
    .catch(error => {
        // error
    });

这篇关于pg-promise:在事务中的下一个查询中使用一个查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆