如何循环多行 sql 查询并在 Knex Transactions 中使用它们?

How to loop through multi-line sql query and use them in Knex Transactions?

这里的 Node 和 Knex 新手来自 RoR 背景,我需要将特定函数转换为 Node.js

这是我的 RoR 代码:

  def self.save!
    update_queries = self.fetch.map{|currency, rate|
      "UPDATE currency_exchange_rates SET rate='#{rate}' WHERE currency='#{currency}'"
    }.join(';')

    ActiveRecord::Base.connection.execute(update_queries)
  end

到目前为止,这是我在 Nodejs 中的内容:

static save(new_rates){
      return new Promise(async (resolve, reject) => {
        var query = Object.keys(rate).map(key => 'UPDATE currency_exchange_rates SET rate=' + rate[key] + ' WHERE currency = "' + key + '"').join('; ');
    })
  }

输入数据如下所示:

新利率 =

'UPDATE currency_exchange_rates SET rate=32102793.12 WHERE currency= "IDR"; 

UPDATE currency_exchange_rates SET rate=0.7822 WHERE currency= "USDGBP"; 

UPDATE currency_exchange_rates SET rate=3189.756317 WHERE currency= "CAD"; 

UPDATE currency_exchange_rates SET rate=152.8 WHERE currency= "USDLKR"; 

UPDATE currency_exchange_rates SET rate=110.818 WHERE currency= "USDJPY"; 

UPDATE currency_exchange_rates SET rate=1.3103 WHERE currency= "USDAUD"'

我正在使用 Knex.js 连接到我的 pg 数据库。如何使用 knex 执行所有这些操作?我可以只传递 knex.raw() 中的所有查询吗? knex.transaction()怎么样?它们有什么区别?

提前致谢!

像这样的方法很有效:

let retVal = await knex.transaction(async (trx) => {
  for (let key of Object.keys(rate)) {
    let value = rate[key];
    await trx('currency_exchange_rates')
      .update({ rate: value }).where('currency', key);
  }
  return "woo done"; // this value is returned from transaction 
});

在处理事务时,通常您希望一个一个地创建和 运行 查询,以避免在通过事务的单个数据库连接 运行 连接它们之前对查询进行不必要的缓冲。

// [Sequential Update] Commit transaction after each successfully executed query
await knex.transaction(async trx => {
    return Promise.all(Object.keys(rate).map(key => trx('currency_exchange_rates')
            .update({ rate: rate[key] })
            .where({ currency: key })
    ));
});

// [Bulk Update] Commit transaction after all queries have been executed successfully
await knex.transaction(trx => {
    return Promise.all(Object.keys(rate).map(key => knex('currency_exchange_rates')
            .update({ rate: rate[key] })
            .where({ currency: key })
        ))
        .then(trx.commit)
        .catch(trx.rollback);
});