简体   繁体   English

使用 Node.js 中的 mssql 模块,事务未按预期回滚

[英]Transaction not rolling back as expected using the mssql module in Node.js

I actually found the answer to this question already, and just want to document my finding.我实际上已经找到了这个问题的答案,并且只想记录我的发现。

Here's what causes the problem:以下是导致问题的原因:

let transaction = new sql.Transaction(pool);
await transaction.begin();
await pool.request (transaction).query (" *** SOME SQL *** ");
await transaction.rollback();

The transaction won't roll back at all.事务根本不会回滚。

To fix the problem, I ended up using new sql.Request (transaction) instead of pool.request (transaction) .为了解决这个问题,我最终使用了new sql.Request (transaction)而不是pool.request (transaction) The codes will look like the following:代码将如下所示:

let transaction = new sql.Transaction(pool);
await transaction.begin();
await new sql.Request (transaction).query (" *** SOME SQL *** ");
await transaction.rollback();

I did not dig deeper to find out the actual mechanism of how the connection pool works, but it appears that unlike the sql.Request class constructor, the pool.request method does not take a transaction parameter (someone who has the knowledge please tell us if this is true).我没有深入了解连接池如何工作的实际机制,但似乎与sql.Request class 构造函数不同, pool.request方法不带事务参数(有知识的人请告诉我们如果这是真的)。

UPDATE更新

I went back and check the mssql module's source codes and found that there is a request method in the Transaction class, so another solution is to do:我回去查看了mssql模块的源码,发现Transaction class中有一个请求方法,所以另一种解决方法是:

let transaction = new sql.Transaction(pool);
await transaction.begin();
await transaction.request().query (" *** SOME SQL *** ");
await transaction.rollback();

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

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