如何测试 DBI 驱动程序状态是否在事务内?
我有几个方法只应在我的 DBI 驱动程序类的情况下执行当前正在进行事务以确保数据完整性。我想写这样的东西:
sub m{
my ($self , $dbh ) = @_ ;
unless( $dbh->isInTransaction()){
die "Use this only within a transaction\n" ;
}
etc ...
}
感谢您的帮助。
J。
I've got a couple of methods that should be executed only in the case my DBI driver class is currently into a transaction to ensure data integrity. I'm looking to write something like this:
sub m{
my ($self , $dbh ) = @_ ;
unless( $dbh->isInTransaction()){
die "Use this only within a transaction\n" ;
}
etc ...
}
From the docs for begin_work, I understand that begin_work will set AutoCommit
to off during the time of the transaction and will set it back to 'on' on commit or rollback, but I wonder if testing for the AutoCommit
attribute value is a safe way to implement isInTransaction
.
Thanks for your help.
J.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果启用 AutoCommit 并使用 $dbh->begin_work 启动事务,您可以测试是否处于事务中:
如果禁用 AutoCommit,DBI 没有多大帮助:您只能检查连接到该事务的活动语句数据库句柄:
我从来没有必要检查是否有一个事务处于活动状态——令我惊讶的是,它不支持它。您可能应该在有关 DBI 的包装器中自己跟踪事务(或将方法注入 DBI)。扩展 BegunWork 以在禁用 AutoCommit 的情况下发挥作用,看起来像是一个核心 DBI 修复。
If you enable AutoCommit and start transactions with $dbh->begin_work, you can test to see if you're in a transaction:
If you disable AutoCommit, DBI doesn't help much: you can only check for active statements connected to the database handle:
I've never had to check if there was a transaction active--it surprises me there's no support for it. You should probably track transactions yourself in a wrapper about DBI (or inject methods into DBI). Extending BegunWork to be useful with AutoCommit disabled looks like a core DBI fix.
如果您正在编写自己的包装器类,则可以包装
begin_work
和其他事务方法,以便可以维护自己的状态。否则,您将依赖于可能发生变化的未记录的功能或假设,特别是当您必须切换到另一个驱动程序时。If you are writing your own wrapper class, you can wrap
begin_work
and the other transaction methods so you can maintain your own state. Otherwise, you're depending on undocumented features or assumptions that may change, especially if you have to switch to another driver.您的代码独立于数据库吗?如果是这样,请仔细阅读有关 AutoCommit 的部分,因为数据库之间存在一些重要差异,具体取决于它们处理事务的方式。但是,如果您已经知道数据库按照您需要的方式处理事务,那么 AutoCommit 应该没问题。
Is your code database-independent? If so carefully read the section on
AutoCommit
because there are some important differences between databases depending on how they handle transactions. But if you already know your database deals with transactions in the way you need, thenAutoCommit
should be fine.