Search code examples
node.jspostgresqlpg-promise

Using .batch with list of parameters in pg-promise


I'm running nodejs and pg-promise, and would like to use the batch function for creating a transaction with a BEGIN and COMMIT surrounding the multiple UPDATEs.

This is my code:

db.tx(function (t) {
    return this.batch(function() {
        for (var i = 0; i < cars.length; i++) {
            return db.any('UPDATE ... ', [car_id, cars[i].votes]);
        }
    });
})

However, it seems not to be working as nothing happens. Isn't it possible to create my batch-list for input like that?


Solution

  • Method batch does not take a function as parameter, it takes an array of promises to resolve.

    And there are plenty of examples of how to use it (on StackOverflow also), starting from the official documentation: Transactions.

    For a set of updates you would simply create an array of update queries and then execute them using batch:

    db.tx(t => {
        const queries = cars.map(c => {
            return t.none('UPDATE ... ', [c.car_id, c.votes]);
        });
        return t.batch(queries);
    })
        .then(data => {
            // success
        })
        .catch(error => {
            // error
        });
    

    Extra

    Multiple updates of the same type can be executed as a single query, for a much better performance. See Performance Boost and method helpers.update.