【问题标题】:Using .batch with list of parameters in pg-promise使用 .batch 和 pg-promise 中的参数列表
【发布时间】:2016-09-13 02:14:51
【问题描述】:

我正在运行 nodejs 和 pg-promise,并且想使用批处理函数来创建一个包含多个 UPDATE 的 BEGIN 和 COMMIT 的事务。

这是我的代码:

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

但是,它似乎没有工作,因为没有任何反应。难道不能为这样的输入创建我的批处理列表吗?

【问题讨论】:

  • 这样的例子无处不在,从官方文档开始:Transactions

标签: node.js postgresql pg-promise


【解决方案1】:

方法batch不接受函数作为参数,它需要一个promise数组来解析。

从官方文档开始:Transactions.

对于一组更新,您只需创建一个更新查询数组,然后使用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
    });

额外

同一类型的多个更新可以作为单个查询执行,以获得更好的性能。请参阅Performance Boost 和方法helpers.update

【讨论】:

  • 很抱歉,但在使用正确的方法时遇到了困难。谢谢。
  • @MichaelNielsen 我已经添加了关于多次更新的进一步研究,以防有一天你到达那里;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 2020-04-18
  • 2017-04-03
  • 1970-01-01
相关资源
最近更新 更多