[Catalyst] CDBI transactions

Brian Cooke mrkoffee at saltedsnail.com
Wed Jun 15 10:14:36 CEST 2005

I have a subroutine I've been using for a while to accomplish commit/ 
rollback in small scopes.  Since I haven't seen a plugin around for  
that, I thought I'd take the extra step of adapting it as a Catalyst  
plugin for those using CDBI-based models.  I've done this, and the  
plugin does seem to work as desired.  A few questions, though:

I seem to remember some talk--I think it was on the #catalyst daily  
summaries--of a plugin for transactions.  Is there a plugin or  
similar functionality I'm not seeing elsewhere?  Has someone already  
done the work on this?  I don't want to step on anyone's toes.

The code is pretty straightforward.  It's taken almost directly from  
the Class::DBI documentation (under TRANSACTIONS).  I'm especially  
interested in how best to identify the CDBI component, in order to  
localize AutoCommit and to call dbi_rollback.  Currently I'm just  
searching for components containing "CDBI" (they all share a common  
db_Main, right?), but that depends on the Model component having  
"CDBI" in its name.  Here it is:

sub transaction {
     my ( $c, $coderef ) = @_;
     my $cdbi = $c->component('CDBI');
     die "Couldn't find a CDBI component" unless defined $cdbi;

     # Turn off AutoCommit for this scope
     local $cdbi->db_Main->{AutoCommit};

     # Execute the code in $coderef and roll back upon error
     eval { $coderef->() };
     if ( my $error = [email protected] ) {
         eval { $cdbi->dbi_rollback };  # rollback might die too
         return 0;
     return 1;

This would be called from within an action like this:

$c->transaction ( sub {
     # Some statements that should be executed atomically
} ) or $c->log->error("Transaction failed: " . $c->error->[-1]);

Thoughts and suggestions welcome!


More information about the Catalyst mailing list