DBIx-Custom / lib / DBIx / Custom / Transaction.pm /
Newer Older
106 lines | 2.153kb
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

            
71
DBIx::Custom::TransactionScope - Transaction scope
72

            
73
=head1 SYNOPSYS
74

            
75
    use DBIx::Custom::SQLite;
76
    
77
    # New
78
    my $dbi = DBIx::Custom::SQLite->new(user => 'taro', $password => 'kliej&@K',
79
                                        database => 'sample');
80
    
81
    # Connect memory database
82
    my $dbi->connect_memory;
83

            
84
=head1 ATTRIBUTES
85

            
86
=head2 dbi
87

            
88
=head1 METHODS
89

            
90
=head2 run
91

            
92
=head1 AUTHOR
93

            
94
Yuki Kimoto, C<< <kimoto.yuki at gmail.com> >>
95

            
96
Github L<http://github.com/yuki-kimoto>
97

            
98
I develope this module L<http://github.com/yuki-kimoto/DBIx-Custom>
99

            
100
=head1 Copyright & lisence
101

            
102
Copyright 2009 Yuki Kimoto, all rights reserved.
103

            
104
This program is free software; you can redistribute it and/or modify it
105
under the same terms as Perl itself.
106