pg-promise:在事务中的下一个查询中使用一个查询的结果

时间:2022-07-01 19:37:51

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.

我是节点。带有pg-promise的postgres,尝试以2个插入顺序执行事务。第一个insert的结果id应该在事务的下一个insert中使用。

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.

如果任何查询失败,则回滚。嵌套2 db。里面没有,然后()1 db。第一个查询不会回滚。使用一个事务。

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>)")
    ]);
})...

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 !

第二个查询是使用pgp.helper生成的。插入multiData查询。但是要使用前一个查询的结果是不可行的。不是吗!

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

有没有一种方法可以从第一次插入中获得id ?

1 个解决方案

#1


3  

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
    });

#1


3  

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
    });