File Coverage

blib/lib/DBIx/TransactionManager/EndHook.pm
Criterion Covered Total %
statement 42 42 100.0
branch 4 4 100.0
condition 4 5 80.0
subroutine 12 12 100.0
pod 0 3 0.0
total 62 66 93.9


line stmt bran cond sub pod time code
1             package DBIx::TransactionManager::EndHook;
2 2     2   94031 use 5.008_001;
  2         7  
  2         77  
3 2     2   10 use strict;
  2         4  
  2         60  
4 2     2   9 use warnings;
  2         17  
  2         87  
5              
6             our $VERSION = '0.02';
7 2     2   943 use DBIx::TransactionManager;
  2         3755  
  2         45  
8              
9 2     2   12 use Try::Tiny;
  2         2  
  2         339  
10 2     2   12 use Carp;
  2         3  
  2         361  
11              
12             sub DBIx::TransactionManager::add_end_hook {
13 10     10 0 21180 my ($self, $sub) = @_;
14              
15 10 100       34 unless ( $self->in_transaction ) {
16 1         63 croak "only can call add_end_hook in transaction";
17             }
18              
19 9   100     111 my $arr = $self->{_end_hooks} ||= [];
20 9         37 push @$arr, $sub;
21             }
22              
23             my $orig_txn_commit = \&DBIx::TransactionManager::txn_commit;
24             my $orig_txn_rollback = \&DBIx::TransactionManager::txn_rollback;
25              
26             {
27 2     2   13 no warnings 'redefine';
  2         4  
  2         758  
28             *DBIx::TransactionManager::txn_commit = *txn_commit;
29             *DBIx::TransactionManager::txn_rollback = *txn_rollback;
30             }
31              
32             sub txn_commit {
33 6     6 0 7775 my $self = shift;
34 6         12 my $is_last_txn = @{ $self->active_transactions } == 1;
  6         22  
35              
36 6         48 my $ret = $orig_txn_commit->($self);
37              
38 5 100 66     151 if ( $is_last_txn && defined $self->{_end_hooks} ) {
39             try {
40 4     4   281 while ( my $end_hook = shift @{ $self->{_end_hooks} } ) {
  9         63  
41 6         17 $end_hook->();
42             }
43             }
44             catch {
45 1     1   22 $self->{_end_hooks} = [];
46 1         22 croak $_;
47 4         47 };
48             }
49              
50 4         70 $ret;
51             }
52              
53             sub txn_rollback {
54 4     4 0 5126 my $self = shift;
55 4         15 my $ret = $orig_txn_rollback->($self);
56 4         69 $self->{_end_hooks} = [];
57 4         16 $ret;
58             }
59              
60             1;
61             __END__