当前位置: 首页 > 知识库问答 >
问题:

在 SQL Server 中断 tSQLt 回滚中同时使用XACT_ABORT和尝试捕获

勾俊
2023-03-14

我开始在我的生产代码中使用SQL Server的tSQLt单元测试。目前,我使用Erland Sommarskog的SQL Server错误处理模式。

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.SommarskogRollback') IS NOT NULL
  DROP PROCEDURE dbo.SommarskogRollback;
GO

CREATE PROCEDURE dbo.SommarskogRollback
AS
BEGIN; /*Stored Procedure*/

  SET XACT_ABORT, NOCOUNT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO

Erland Sommarskog建议我们始终设置XACT_ABORTON,因为只有这样SQL服务器才能以(大部分)一致的方式处理错误。

但是,这在使用tSQLt时产生了一个问题。tSQLt执行显式事务内部的所有测试。当测试完成时,整个事务回滚。这使得测试工件的清理完全没有痛苦。但是,当XACT _中止打开时,TRY块中抛出的任何错误都会立即导致事务失败。事务必须完全回滚。它不能提交,也不能回滚到保存点。事实上,在事务回滚之前,任何东西都不能写入该会话中的事务日志。然而,tSQLt不能正确地跟踪测试结果,除非测试结束时事务是打开的。tSQLt停止执行,并为注定失败的事务抛出回滚错误。失败的测试显示错误状态(而不是成功或失败),并且后续测试不会运行。

tSQL的创建者Sebastian Meine推荐了一种不同的错误处理模式。

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.MeineRollback') IS NOT NULL
  DROP PROCEDURE dbo.MeineRollback;
GO

CREATE PROCEDURE dbo.MeineRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* We declare the error variables here, populate them inside the CATCH 
   * block and then do our error handling after exiting the CATCH block
   */
  DECLARE @ErrorNumber      INT
         ,@MessageTemplate  NVARCHAR(4000)
         ,@ErrorMessage     NVARCHAR(4000)
         ,@ErrorProcedure   NVARCHAR(126)
         ,@ErrorLine        INT
         ,@ErrorSeverity    INT
         ,@ErrorState       INT
         ,@RaisErrorState   INT
         ,@ErrorLineFeed    NCHAR(1) = CHAR(10)
         ,@ErrorStatus      INT = 0
         ,@SavepointName    VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters and must be unique.  UNIQUEIDs are 36, four of which are dashes.*/

  BEGIN TRANSACTION; /*If a transaction is already in progress, this just increments the transaction count*/

  SAVE TRANSACTION @SavepointName;

  BEGIN TRY;

    RAISERROR('This is a test.  Had this been an actual error, Sebastian would have given you a meaningful error message.', 16, 1);

  END TRY
  BEGIN CATCH;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorStatus    = 1
          ,@ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1 
                               ELSE ERROR_STATE()
                             END;

  END CATCH;

  /*Rollback to savepoint if error occurred.  This does not affect the transaction count.*/
  IF @ErrorStatus <> 0
    ROLLBACK TRANSACTION @SavepointName;

  /*If this procedure executed inside a transaction, then the commit just subtracts one from the transaction count.*/
  COMMIT TRANSACTION;

  IF @ErrorStatus = 0
    RETURN 0;

  ELSE 
    BEGIN; /*Re-throw error*/

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

      RETURN -1;

    END;   /*Re-throw error*/

END  /*Stored Procedure*/
GO

声明错误变量,开始事务,设置保存点,然后在 TRY 块内执行过程代码。如果 TRY 块引发错误 ,则执行将传递到 CATCH 块,后者填充错误变量。然后执行从 TRY 捕获块中传递出来。出错时,事务将回滚到过程开始时设置的存储点。然后事务提交。由于 SQL Server 处理嵌套事务的方式,当在另一个事务中执行时,此 COMMIT 只是从事务计数器中减去一个。(嵌套事务在 SQL 服务器中实际上并不存在。

塞巴斯蒂安创造了一个非常整洁的图案。执行链中的每个过程都会清理自己的事务。不幸的是,这种模式有一个大问题:注定的交易。注定失败的事务会打破这种模式,因为它们无法回滚到保存点或提交。它们只能完全回滚。当然,这意味着在使用TRY-CATCH块时不能将XACT_ABORT设置为ON(并且应该始终使用TRY-CATCH块)。即使关闭了XACT_ ABORT,许多错误(如编译错误)仍会导致事务失败。此外,保存点不适用于分布式事务。

我如何解决这个问题?我需要一个错误处理模式,它可以在tSQL测试框架内工作,并在生产中提供一致、正确的错误处理。我可以在运行时检查环境并相应地调整行为。(请参阅下面的示例。)然而,我不喜欢这样。对我来说,这感觉就像是一种黑客攻击。它要求开发环境配置一致。更糟糕的是,我不测试我的实际生产代码。有人有出色的解决方案吗?

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.ModifiedRollback') IS NOT NULL
  DROP PROCEDURE dbo.ModifiedRollback;
GO

CREATE PROCEDURE dbo.ModifiedRollback
AS
BEGIN; /*Stored Procedure*/

  SET NOCOUNT ON;

  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    BEGIN TRANSACTION;

      RAISERROR('This is just a test.  Had this been an actual error, we would have given you some cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

  END TRY
  BEGIN CATCH;

    IF @@TRANCOUNT > 0  AND  RIGHT(@@SERVERNAME,9) <> '\LOCALDEV'
      ROLLBACK TRANSACTION;

    THROW;

  END CATCH;

END;   /*Stored Procedure*/
GO

编辑:经过进一步的测试,我发现我修改后的回滚也不起作用。当过程引发错误时,它将退出而不回滚或提交。tSQLt 会引发错误,因为过程退出时@@TRANCOUNT与过程启动时的计数不匹配。经过一些尝试和错误,我找到了一个在我的测试中有效的解决方法。它结合了两种错误处理方法 - 使错误处理更加复杂,并且某些代码路径无法测试。我很想找到一个更好的解决方案。

USE TempDB;

SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID('dbo.TestedRollback') IS NOT NULL
  DROP PROCEDURE dbo.TestedRollback;
GO

CREATE PROCEDURE dbo.TestedRollback
AS
BEGIN /*Stored Procedure*/

  SET NOCOUNT ON;

  /* Due to the way tSQLt uses transactions and the way SQL Server handles errors, we declare our error-handling 
   * variables here, populate them inside the CATCH block and then do our error-handling after exiting 
   */
  DECLARE @ErrorStatus       BIT
         ,@ErrorNumber       INT
         ,@MessageTemplate   NVARCHAR(4000)
         ,@ErrorMessage      NVARCHAR(4000)
         ,@ErrorProcedure    NVARCHAR(126)
         ,@ErrorLine         INT
         ,@ErrorSeverity     INT
         ,@ErrorState        INT
         ,@RaisErrorState    INT
         ,@ErrorLineFeed     NCHAR(1) = CHAR(10)
         ,@FALSE             BIT = CAST(0 AS BIT)
         ,@TRUE              BIT = CAST(1 AS BIT)
         ,@tSQLtEnvironment  BIT
         ,@SavepointName     VARCHAR(32) = REPLACE( (CAST(NEWID() AS VARCHAR(36))), '-', '');
         /*Savepoint names are 32 characters long and must be unique.  UNIQUEIDs are 36, four of which are dashes*/

  /* The tSQLt Unit Testing Framework we use in our local development environments must maintain open transactions during testing.  So,
   * we don't roll back transactions during testing.  Also, doomed transactions can't stay open, so we SET XACT_ABORT OFF while testing.
   */
  IF RIGHT(@@SERVERNAME, 9) = '\LOCALDEV'
    SET @tSQLtEnvironment = @TRUE

  ELSE
    SET @tSQLtEnvironment = @FALSE;


  IF @tSQLtEnvironment = @TRUE
    SET XACT_ABORT OFF;

  ELSE
    SET XACT_ABORT ON;

  BEGIN TRY;

    SET ROWCOUNT 0; /*The ROWCOUNT setting can be updated outside the procedure and changes its behavior.  This sets it to the default.*/

    SET @ErrorStatus = @FALSE;

    BEGIN TRANSACTION;

      /*We need a save point to roll back to in the tSQLt Environment.*/
      IF @tSQLtEnvironment = @TRUE
        SAVE TRANSACTION @SavepointName;

      RAISERROR('Cryptic gobbledygook.', 16, 1);

    COMMIT TRANSACTION;

    RETURN 0;

  END TRY
  BEGIN CATCH;

    SET @ErrorStatus = @TRUE;

    /* Build a message string with placeholders for the original error information
     * Note:  "%d" & "%s" are placeholders (substitution parameters) which capture
     *        the values from the argument list of the original error message.
     */
    SET @MessageTemplate = N': Error %d, Severity %d, State %d, ' + @ErrorLineFeed
                         + N'Procedure %s, Line %d, '             + @ErrorLineFeed
                         + N', Message: %s';

    SELECT @ErrorMessage   = ERROR_MESSAGE()
          ,@ErrorNumber    = ERROR_NUMBER()
          ,@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-')
          ,@ErrorLine      = ERROR_LINE()
          ,@ErrorSeverity  = ERROR_SEVERITY()
          ,@ErrorState     = ERROR_STATE()
          ,@RaisErrorState = CASE ERROR_STATE()
                               WHEN 0 /*RAISERROR Can't generate errors with State = 0*/
                                 THEN 1 
                               ELSE ERROR_STATE()
                             END;
  END CATCH;

  /* Due to the way the tSQLt test framework uses transactions, we use two different error-handling schemes:
   * one for unit-testing and the other for our main Test/Staging/Production environments.  In those environments
   * we roll back transactions in the CATCH block in the event of an error.  In unit-testing, on the other hand, 
   * we begin a transaction and set a save point.  If an error occurs we roll back to the save point and then 
   * commit the transaction.  Since tSQLt executes all test in a single explicit transaction, starting a 
   * transaction at the beginning of this stored procedure just adds one to @@TRANCOUNT.  Committing the 
   * transaction subtracts one from @@TRANCOUNT.  Rolling back to a save point does not affect @@TRANCOUNT.
   */
  IF @ErrorStatus = @TRUE
    BEGIN; /*Error Handling*/

      IF @tSQLtEnvironment = @TRUE
        BEGIN; /*tSQLt Error Handling*/
          ROLLBACK TRANSACTION @SavepointName; /*Rolls back to save point but does not affect @@TRANCOUNT*/

          COMMIT TRANSACTION; /*Subtracts one from @@TRANCOUNT*/
        END;   /*tSQLt Error Handling*/

      ELSE IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;

      /*Rethrow the error.  The msg_str parameter will contain the original error information*/
      RAISERROR( @MessageTemplate  /*msg_str parameter as message format template*/
                ,@ErrorSeverity    /*severity parameter*/
                ,@RaisErrorState   /*state parameter*/
                ,@ErrorNumber      /*argument: original error number*/
                ,@ErrorSeverity    /*argument: original error severity*/
                ,@ErrorState       /*argument: original error state*/
                ,@ErrorProcedure   /*argument: original error procedure name*/
                ,@ErrorLine        /*argument: original error line number*/
                ,@ErrorMessage     /*argument: original error message*/
                );

    END;   /*Error Handling*/

END  /*Stored Procedure*/
GO

共有1个答案

贺刚毅
2023-03-14

我正在测试一个补丁来修改框架过程tSQLt。Private_RunTest。基本上,在主CATCH块中,它试图做一个命名的回滚(对我来说是1448行),我替换了

    ROLLBACK TRAN @TranName;

    IF XACT_STATE() = 1 -- transaction is active
        ROLLBACK TRAN @TranName; -- execute original code
    ELSE IF XACT_STATE() = -1 -- transaction is doomed; cannot be partially rolled back
        ROLLBACK;   -- fully roll back

    IF (@@TRANCOUNT = 0)
        BEGIN TRAN; -- restart transaction to fulfill expectations below

初步测试看起来不错。敬请关注。(在我对这个提议的编辑更有信心之后,我会提交给git。)

 类似资料:
  • 我的sp中有一个try catch块,try中只有一个insert语句。捕捉检查错误代码,如果是pk违规,如果是则做更新。但是有时我会得到“当前事务不能被提交,不能支持写入日志文件的操作。回滚事务。 在批处理结束时检测到不可提交的事务。事务被回滚了“,所以我添加了xact_abort,但后来我不断得到”EXECUTE之后的事务计数表明 BEGIN 和 COMMIT 语句的数量不匹配“,我发现了这一

  • 我有一个返回< code>List的方法。现在我想知道如何正确放置< code>try/catch块。如果我将< code>return语句放在< code>try中,我会得到错误 并非所有代码路径都返回值 如果我放置在之后(就像我目前所做的那样),即使在之后,它也会返回。那么最好的方法应该是什么? 方法如下:

  • 问题内容: Python中是否有某种方法可以捕获事件而不将所有代码放入-语句中? 如果用户按下 +,我想干净地退出而没有任何痕迹 。 问题答案: 是的,您可以使用模块signal安装中断处理程序,并使用threading.Event永远等待:

  • 根据 的联机丛书文档,我得到的印象是,如果 T-SQL 语句引发运行时错误,则整个事务将终止并回滚: 当 SET XACT_ABORT 处于打开状态时,如果 Transact-SQL 语句引发运行时错误,则整个事务将终止并回滚。 在 SQL 服务器 2008 R2 中对此进行测试: 给出输出: 我还认为如果出现错误,<code>将XACT_ABORT设置为ON</code>会终止批处理: SET

  • 问题内容: 有时候,我看到 而有时 有什么区别? 问题答案: 通过捕获,它包含了子类化的东西。通常,您不应该这样做,除非可能是在您要记录的线程的最高“捕获所有”级别,或者绝对要处理可能出错的所有内容。这将是一个框架型应用程序(例如应用程序服务器或一个测试框架),它可以运行未知代码,不应受到影响比较典型的 事情 是去错代码,尽可能多地。

  • 我有shell文件(deploy.sh)执行以下命令: 当其中一个命令发生错误时,我想停止bash的执行。 shell中的哪个命令可以做到这一点?