- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我开始在生产代码中使用 SQL Server 的 tSQLt 单元测试。目前,我使用 Erland Sommarskog's 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 建议我们始终 SET XACT_ABORT ON,因为只有这样 SQL Server 才能以(大部分)一致的方式处理错误。
不过,这在使用 tSQLt 时会产生问题。 tSQLt 在显式事务中执行所有测试。当测试完成时,整个事务回滚。这使得清理测试工件完全无痛。然而,在 XACT_ABORT ON 的情况下,在 TRY block 内抛出的任何错误都会立即终止该事务。事务必须完全回滚。它无法提交,也无法回滚到保存点。事实上,在事务回滚之前,没有任何内容可以写入该 session 内的事务日志。但是,tSQLt 无法正确跟踪测试结果,除非在测试结束时事务处于打开状态。 tSQLt 停止执行并为注定 事务抛出回滚错误。失败的测试显示错误状态(而不是成功或失败),后续测试不会运行。
tSQLt 的创建者 Sebastian Meine 推荐了一个不同的 error handling pattern .
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 block 中执行过程代码。如果 TRY block 抛出错误,执行将转到 CATCH block ,该 block 填充错误变量。然后执行传递出 TRY CATCH block 。出错时,事务回滚到过程开始时设置的保存点。然后事务提交。由于 SQL Server 处理嵌套事务的方式,当在另一个事务中执行时,此 COMMIT 只是从事务计数器中减去一个。 (SQL Server 中确实不存在嵌套事务。)
塞巴斯蒂安创造了一个非常整洁的图案。执行链中的每个过程都会清理自己的事务。不幸的是,这种模式有一个大问题:注定的交易。注定失败的事务打破了这种模式,因为它们无法回滚到保存点或提交。他们只能完全回滚。当然,这意味着您不能在使用 TRY-CATCH block 时将 XACT_ABORT 设置为 ON(并且您应该始终使用 TRY-CATCH block 。)即使 XACT_ABORT 为 OFF,许多错误(例如编译错误)仍然会导致事务失败.此外,保存点不适用于分布式事务。
我该如何解决这个问题?我需要一个错误处理模式,它可以在 tSQLt 测试框架内工作,并且还可以在生产中提供一致、正确的错误处理。我可以在运行时检查环境并相应地调整行为。 (参见下面的示例。)但是我不喜欢那样。这对我来说就像一个黑客。它要求开发环境的配置一致。更糟糕的是,我不测试我的实际生产代码。有没有人有绝妙的解决方案?
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
最佳答案
我正在测试修改框架过程 tSQLt.Private_RunTest 的修复程序。基本上,在主要的 CATCH block 中,它正在尝试进行命名回滚(对我来说是第 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。)
关于sql-server - 在 SQL Server 中一起使用 XACT_ABORT 和 TRY CATCH 中断 tSQLt 回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647317/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!