使用 NodeJS 和 Postgres 的事务链中的可选 INSERT 语句

Optional INSERT statement in transaction chain using NodeJS and Postgres

我正在使用 NodeJS/Postgres 构建一个简单的 Web 应用程序,它需要在数据库中进行 3 次插入。

为了控制语句链,我正在使用 pg-transaction

我的问题是我必须总是 运行 第 2 个插入,但我有条件 运行 第三个。

也许我的代码可以以更好的方式构建(欢迎提出建议)。

这是一个伪代码:

function(req, res) {
  var tx = new Transaction(client);
  tx.on('error', die);
  tx.begin();
  
  tx.query('INSERT_1 VALUES(...) RETURNING id', paramValues, function(err, result) {
    if (err) {
      tx.rollback();
      res.send("Something was wrong!");
      return;
    }
    
    var paramValues2 = result.rows[0].id;
    tx.query('INSERT_2 VALUES(...)', paramValues2, function(err2, result2) {
      if (err) {
        tx.rollback();
        res.send("Something was wrong!");
        return;
      }
      
      // HERE'S THE PROBLEM (I don't want to always run this last statement)
      // If I don't run it, I will miss tx.commit()
      if (req.body.value != null) {
        tx.query('INSERT_3 VALUES(...)', paramValues3, function(err3, result3) {
          if (err) {
            tx.rollback();
            res.send("Something was wrong!");
            return;
          }
        
          tx.commit();
          res.send("Everything fine!");
        });
      }
    });
  });
}

在每次查询后重复三次相同的内容 if (err) {} 看起来很难看。

尝试检查我找到的一些选项 Sequelize,但找不到解决此问题的方法。

欢迎提出任何建议!

谢谢!

手动事务管理是一条危险的道路,请尽量远离它! ;)

pg-promise:

的帮助下,这是正确的做法
function(req, res) {
    db.tx(t => { // automatic BEGIN
            return t.one('INSERT_1 VALUES(...) RETURNING id', paramValues)
                .then(data => {
                    var q = t.none('INSERT_2 VALUES(...)', data.id);
                    if (req.body.value != null) {
                        return q.then(()=> t.none('INSERT_3 VALUES(...)', data.id));
                    }
                    return q;
                });
        })
        .then(data => {
            res.send("Everything's fine!"); // automatic COMMIT was executed
        })
        .catch(error => {
            res.send("Something is wrong!"); // automatic ROLLBACK was executed
        });
}

或者,如果您更喜欢 ES7 语法:

function (req, res) {
    db.tx(async t => { // automatic BEGIN
            let data = await t.one('INSERT_1 VALUES(...) RETURNING id', paramValues);
            let q = await t.none('INSERT_2 VALUES(...)', data.id);
            if (req.body.value != null) {
                return await t.none('INSERT_3 VALUES(...)', data.id);
            }
            return q;
        })
        .then(data => {
            res.send("Everything's fine!"); // automatic COMMIT was executed
        })
        .catch(error => {
            res.send("Something is wrong!"); // automatic ROLLBACK was executed
        });
}

更新

在示例中用 ES7 async/await 替换了 ES6 生成器,因为 pg-promise 从版本 9.0.0

开始停止支持 ES6 生成器