【问题标题】:Node - Mysql Transaction is not rolling back if one query fails节点 - 如果一个查询失败,Mysql 事务不会回滚
【发布时间】:2019-09-01 01:01:07
【问题描述】:

我正在尝试执行总共有三个查询的 node-mysql 事务。这三个都是“插入”查询。我故意写错了第三个查询来测试回滚,但是前两个查询的事务正在进入数据库而不会失败。

我知道类似的问题已经被问过好几次了,我几乎都试过了,但都没有成功

exports.registerNewUserTransaction = async (
  res,
  userToBeAdded,
  nameToBeAdded,
  emailToBeAdded)  => {
  const conn = await db.getConnection();
  await conn.beginTransaction();
  try {
    await this.insertOne('user', userToBeAdded);
    await this.insertOne('name', nameToBeAdded);
    await this.insertOne('email', emailToBeAdded);
    await conn.commit();
    res.status(200);
  } catch(err) {
    await conn.rollback();
    res.status(400);
  } finally {
    await conn.release();
  }
};

如您所见,我从池中获取连接对象,开始事务并一一执行查询。我的第三个查询的列名错误,因此事务应该回滚,但我看到前两个查询的条目。我真的很感激正确的方向。 节点版本:12.8.0 mysql(在 docker 中运行):8.0.15 mysql(npm 版本):2.17.1

【问题讨论】:

    标签: node.js node-mysql


    【解决方案1】:

    经过一番苦苦挣扎,终于想通了。答案如下:

    exports.registerNewUserTransaction = async (
      res,
      userToBeAdded,
      nameToBeAdded,
      emailToBeAdded)  => {
      const conn = await db.getConnection();
      // My first mistake was not to promisify connection query 
      conn.query = util.promisify(conn.query);
      await conn.beginTransaction();
      try {
        // My second mistake was not to use same connection
        await conn.query('INSERT INTO ...', userToBeAdded);
        await conn.query('INSERT INTO ...', nameToBeAdded);
        await conn.query('INSERT INTO ...', emailToBeAdded);
        await conn.commit();
        return res.status(200);
      } catch(err) {
        await conn.rollback();
        return res.status(400);
      } finally {
        await conn.release();
      }
    };
    

    希望这可能对某人有所帮助!

    【讨论】:

      【解决方案2】:

      这是我错过的重要部分。 conn.query = util.promisify(conn.query);

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多