File Coverage

lib/DB/Transaction.pm
Criterion Covered Total %
statement 29 29 100.0
branch 15 16 93.7
condition 5 5 100.0
subroutine 4 4 100.0
pod 1 1 100.0
total 54 55 98.1


line stmt bran cond sub pod time code
1 1     1   22499 use strict;
  1         2  
  1         24  
2 1     1   5 use warnings;
  1         1  
  1         34  
3             package DB::Transaction;
4 1     1   4 use base qw(Exporter);
  1         5  
  1         356  
5              
6             our $VERSION = 0.001001; # 0.001.0
7              
8             our @EXPORT_OK = qw(run_in_transaction);
9              
10             my %on_error_options = (
11             rollback => undef,
12             continue => undef,
13             );
14              
15             my %transactions_deep;
16             sub run_in_transaction (&;@) {
17 13     13 1 7831 my $code = shift;
18 13         36 my (%args) = @_;
19              
20 13         22 my $db_handle = $args{db_handle};
21 13   100     49 my $on_error = $args{on_error} || 'rollback';
22              
23 13 100       36 die "Don't know how to handle error action '$on_error'\n"
24             if ! exists $on_error_options{$on_error};
25              
26 12         27 local $db_handle->{AutoCommit} = 0;
27 12         20 local $db_handle->{RaiseError} = 1;
28              
29 12         33 $transactions_deep{"$db_handle"}++;
30 12         15 my $error;
31             eval {
32 12         25 $code->();
33 7 100       3890 $db_handle->commit if $transactions_deep{"$db_handle"} <= 1;
34 12 100       16 ;1 } || do {
  7         74  
35 5 50       79 $error = defined $@ ? $@ : 'an error was encountered in your transaction';
36 5 100       32 $db_handle->rollback if $on_error eq 'rollback';
37             };
38 12 100       66 $@ = $error if defined $error;
39 12         26 $transactions_deep{"$db_handle"}--;
40 12 100       44 delete $transactions_deep{"$db_handle"} if $transactions_deep{"$db_handle"} < 1;
41              
42 12 100 100     62 die $error if defined $error && $on_error eq 'rollback';
43              
44 9         44 return ! defined $error;
45             }
46              
47             1;
48              
49             __END__