简体   繁体   English

节点 mssql 事务顺序请求

[英]node mssql transaction sequential requests

I am using mssql package within an azure function...trying to perform sequential writes to a database within a single transaction.我在 azure 函数中使用 mssql 包......试图在单个事务中对数据库执行顺序写入。 The aim is that the transactions are to roll back if there is an error in either one.目的是如果任一事务出现错误,则事务将回滚。 This looks to be working with the below code but I can't figure out how to send back whether the transaction is successful/rolled back (and ultimately communicate this to the client).这看起来适用于以下代码,但我无法弄清楚如何发回事务是否成功/回滚(并最终将其传达给客户端)。 I have looked at the transaction documentation for mssql but they only have examples for a SINGLE request.我查看了 mssql 的事务文档,但他们只有单个请求的示例。 Not multiple requests.不是多个请求。 What is the best way to do this?做这个的最好方式是什么?

In the below code, Request2 is the request that is supposed to fail due to a misspelling of the table name.在下面的代码中,Request2 是应该由于表名拼写错误而失败的请求。 As I said, it seems that the rolling back is occurring because NEITHER writes are occurring.正如我所说,似乎回滚正在发生,因为没有发生写入。 Also, the 'error committing transaction' is getting logged in the console... but I can't get this error out into the azure function to then respond to the client correctly.此外,“错误提交事务”正在控制台中记录......但我无法将此错误输出到 azure 函数中,然后正确响应客户端。 I just want to be able to pick up an error in the trasaction.commit() stage and then send this back, but it seems the context.res is being run straight away.我只是希望能够在 trasaction.commit() 阶段发现错误,然后将其发回,但似乎 context.res 正在立即运行。 How do I fix this?我该如何解决? I obviously don't understand the async properties properly.我显然没有正确理解异步属性。 Does anyone have a good example of how to run sequential queries in a transaction with node mssql?有没有人有一个很好的例子来说明如何使用节点 mssql 在事务中运行顺序查询? I can't find any good examples online.我在网上找不到任何好的例子。

const runQuery = async () => {
var errors = [];


let pool = await sql.connect(sqlConfig);

const transaction = new sql.Transaction(pool);

transaction.begin(async (err) => {
  let rolledBack = false;

  transaction.on("rollback", (aborted) => {
    console.log("rolledback");
    rolledBack = true;
  });
  const request = new sql.Request(transaction);
  request.query(
    "insert into categories (category) values ('Test ')",
    async (err, result) => {
      if (err) {
        console.log("error 1");
        errors.push(err);
        // return "error in req1";
        if (!rolledBack) {
          console.log("rollback 1 below");
          await transaction.rollback((err) => {
            console.log("rolling back 1");
          });
        }
      }

      const request2 = new sql.Request(transaction);

      request2.query(
        "insert into adjustment values ('AAA', 0)",
        async (err, result) => {
          if (err) {
            console.log("error 2");
            errors.push(err);
            if (!rolledBack) {
              console.log("rollback 2 below");
              await transaction.rollback((err) => {
                console.log("rolling back");
                // console.log(err);
              });
            }
          }

          transaction.commit((err) => {
            if (err) {
              console.log("error in committing transaction");
              return "error";
              // console.log(err);
            } else {
              return "success";
            }
          });
        }
      );
    }
  );
});

}; };

const queryResult = await runQuery(); const queryResult = await runQuery();

context.res = { body: queryResult, }; context.res = { body: queryResult, }; }; };

After you handled the error returned by the commit(), your function should return error code and message.在处理了 commit() 返回的错误后,您的函数应返回错误代码和消息。 Then you can fill the response as below,然后你可以填写下面的回复,

 context.res = { status: queryResult.responseCode, body : queryResult.mesg};

For instance, the runQuery() function could return 400 as responseCode and "Something went wrong, details of error" as mesg .例如, runQuery() 函数可以将 400 作为responseCode返回,并将“出现问题,错误详细信息”作为mesg You could also log your errors such that you can find log and trace messages in the Application Insights blade for your function app.您还可以记录您的错误,以便您可以在Application Insights找到函数应用的日志和跟踪消息。 So that you can easily debug what went on inside your code.这样您就可以轻松调试代码中发生的事情。 See this documentation to log errors.请参阅此文档以记录错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM