DBIx-Custom / lib / DBIx / Custom / Transaction.pm /
Newer Older
96 lines | 1.809kb
remove run_transaction().
yuki-kimoto authored on 2010-01-30
1
package DBIx::Custom::Transaction;
2

            
3
use strict;
4
use warnings;
5

            
6
use base 'Object::Simple';
7
use Carp 'croak';
8

            
9
__PACKAGE__->attr('dbi');
10

            
11
sub run {
12
    my ($self, $transaction) = @_;
13
    
14
    # DBIx::Custom object
15
    my $dbi = $self->dbi;
16
    
17
    # Shorcut
18
    return unless $dbi;
19
    
20
    # Check auto commit
21
    croak("AutoCommit must be true before transaction start")
22
      unless $dbi->_auto_commit;
23
    
24
    # Auto commit off
25
    $dbi->_auto_commit(0);
26
    
27
    # Run transaction
28
    eval {$transaction->()};
29
    
30
    # Tranzaction error
31
    my $transaction_error = $@;
32
    
33
    # Tranzaction is failed.
34
    if ($transaction_error) {
35
        # Rollback
36
        eval{$dbi->dbh->rollback};
37
        
38
        # Rollback error
39
        my $rollback_error = $@;
40
        
41
        # Auto commit on
42
        $dbi->_auto_commit(1);
43
        
44
        if ($rollback_error) {
45
            # Rollback is failed
46
            croak("${transaction_error}Rollback is failed : $rollback_error");
47
        }
48
        else {
49
            # Rollback is success
50
            croak("${transaction_error}Rollback is success");
51
        }
52
    }
53
    # Tranzaction is success
54
    else {
55
        # Commit
56
        eval{$dbi->dbh->commit};
57
        my $commit_error = $@;
58
        
59
        # Auto commit on
60
        $dbi->_auto_commit(1);
61
        
62
        # Commit is failed
63
        croak($commit_error) if $commit_error;
64
    }
65
}
66

            
67
1;
68

            
69
=head1 NAME
70

            
rename DBIx::Custom::SQLite ...
yuki-kimoto authored on 2010-01-30
71
DBIx::Custom::Transaction - Transaction
remove run_transaction().
yuki-kimoto authored on 2010-01-30
72

            
73
=head1 SYNOPSYS
74
    
rename DBIx::Custom::SQLite ...
yuki-kimoto authored on 2010-01-30
75
    use DBIx::Custom::Transaction
76
    my $txn = DBIx::Custom::Transaction->new(dbi => DBIx::Custom->new);
77
    $txn->run(sub { ... });
remove run_transaction().
yuki-kimoto authored on 2010-01-30
78
    
79
=head1 ATTRIBUTES
80

            
81
=head2 dbi
82

            
rename DBIx::Custom::SQLite ...
yuki-kimoto authored on 2010-01-30
83
    $self = $txn->dbi($dbi);
84
    $dbi  = $txn->dbi;
85
    
remove run_transaction().
yuki-kimoto authored on 2010-01-30
86
=head1 METHODS
87

            
88
=head2 run
rename DBIx::Custom::SQLite ...
yuki-kimoto authored on 2010-01-30
89
    
90
    $txn->run(
91
        sub {
92
            # Transaction
93
        }
94
    );
remove run_transaction().
yuki-kimoto authored on 2010-01-30
95

            
rename DBIx::Custom::SQLite ...
yuki-kimoto authored on 2010-01-30
96
=cut