Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if the DBI driver state is within a transaction?

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.

like image 466
jeje Avatar asked Sep 05 '25 16:09

jeje


1 Answers

If you enable AutoCommit and start transactions with $dbh->begin_work, you can test to see if you're in a transaction:

if ($dbh->{BegunWork}) {

If you disable AutoCommit, DBI doesn't help much: you can only check for active statements connected to the database handle:

if ($dbh->{ActiveKids}) {

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.

like image 127
Ken Fox Avatar answered Sep 09 '25 16:09

Ken Fox