【问题标题】:Knex Transaction - Using Await - Not executing 2nd SQL StatementKnex 事务 - 使用等待 - 不执行第二个 SQL 语句
【发布时间】:2020-01-15 22:27:22
【问题描述】:

我在节点 js 10.x 中使用 knex 0.19.4。我有 2 个 SQL 语句 - 插入和更新必须作为事务发生。

// Using Var, so that below code has access to this variable
var sqlStageInsert = kx('stage').insert({
  officeid: 'OFF000',
  taskid: 'T002',
});


var sqlTaskPcUpdate = kx('task')
  .update({ pc: 100})
  .where('task.taskno', taskno)
  .limit(1);

第一次尝试 - 第二次 SQL sqlTaskPcUpdate 未执行

const sqlUpdateInsert = kx.transaction(function (trx) {
  sqlStageInsert.transacting(trx)
    .then(function () {
      console.log(sqlTaskPcUpdate.toString()); // This is outputing correct SQL
      return sqlTaskPcUpdate.transacting(trx);
    })
    .then(trx.commit)
    .catch(trx.rollback);
});
await sqlUpdateInsert;

第二次尝试 - 出现错误 Transaction query already complete。这是基于Commit/rollback a knex transaction using async/await

await kx.transaction(async (trx) => {
  try {
    await sqlStageInsert.transacting(trx);
    await sqlTaskPcUpdate.transacting(trx);
    trx.commit();
  } catch (error) {
    trx.rollback();
    throw error;
  }
});

【问题讨论】:

  • .transaction 看起来是基于回调的,而不是基于 Promise 的..?
  • 它看起来仍然是基于回调的?你确定 .transaction 返回一个 Promise 吗?
  • 是的,.transaction 返回 Promise

标签: mysql node.js transactions knex.js


【解决方案1】:

我建议您先尝试在 stage 表中插入数据,然后检索属于两个表的公共值,用于在更新 task 类中应用表(假设两个表都包含任何一个具有相同数据的公共列)。

请注意,根据 knexjs.org 网站,knex.transaction() 使用关于 PostgreSQL 的返回语句来插入/更新多个表以保持一致性,但是 MySQL 不支持事务,因此我是在下面的代码中使用返回值。

FYR,http://knexjs.org/#Transactions

请参考以下代码 sn-p 供您参考:

db.transaction(trx => {
  trx.insert({
    officeid: 'OFF000',
    taskid: 'T002'
  })
  .into('stage')
  .then(() => {
    return trx('stage').where({taskid}).then(resp => resp[0].taskno)
  })
  .then(stageTaskno => {
    return trx('task')
          .update({pc: 100})
          .where({stageTaskno})
          .limit(1)
          .then(resp => {
            resp.json(resp)
          })
  })
  .then(trx.commit)
  .catch(trx.rollback)
});

希望这有帮助,干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多