Thursday, 4 May 2017

pg-promise: use result of one query in next query within a transaction

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.

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.batch([
        // 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 !

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



via Maven

No comments:

Post a Comment