Add single() ro RSC
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / TxnScopeGuard.pm
CommitLineData
6936e902 1package DBIx::Class::Storage::TxnScopeGuard;
1bc193ac 2
3use strict;
4use warnings;
e8fcf76f 5use Carp ();
1bc193ac 6
7sub new {
8 my ($class, $storage) = @_;
9
10 $storage->txn_begin;
11 bless [ 0, $storage ], ref $class || $class;
12}
13
14sub commit {
15 my $self = shift;
16
17 $self->[1]->txn_commit;
18 $self->[0] = 1;
19}
20
21sub DESTROY {
22 my ($dismiss, $storage) = @{$_[0]};
23
3b7f3eac 24 return if $dismiss;
25
26 my $exception = $@;
a211cb63 27 Carp::cluck("A DBIx::Class::Storage::TxnScopeGuard went out of scope without explicit commit or an error - bad")
d7ded411 28 unless $exception;
29
30 my $rollback_exception;
a778f387 31 {
32 local $@;
33 eval { $storage->txn_rollback };
d7ded411 34 $rollback_exception = $@;
35 }
36 if ($rollback_exception && $rollback_exception !~ /DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION/) {
37 $storage->throw_exception(
38 "Transaction aborted: ${exception} "
a778f387 39 . "Rollback failed: ${rollback_exception}"
d7ded411 40 );
3b7f3eac 41 }
1bc193ac 42}
43
441;
45
46__END__
47
48=head1 NAME
49
6936e902 50DBIx::Class::Storage::TxnScopeGuard - Scope-based transaction handling
1bc193ac 51
52=head1 SYNOPSIS
53
54 sub foo {
55 my ($self, $schema) = @_;
56
57 my $guard = $schema->txn_scope_guard;
58
59 # Multiple database operations here
60
61 $guard->commit;
62 }
63
64=head1 DESCRIPTION
65
66An object that behaves much like L<Scope::Guard>, but hardcoded to do the
67right thing with transactions in DBIx::Class.
68
69=head1 METHODS
70
71=head2 new
72
6936e902 73Creating an instance of this class will start a new transaction (by
74implicitly calling L<DBIx::Class::Storage/txn_begin>. Expects a
1bc193ac 75L<DBIx::Class::Storage> object as its only argument.
76
77=head2 commit
78
79Commit the transaction, and stop guarding the scope. If this method is not
6936e902 80called and this object goes out of scope (i.e. an exception is thrown) then
81the transaction is rolled back, via L<DBIx::Class::Storage/txn_rollback>
1bc193ac 82
83=cut
84
85=head1 SEE ALSO
86
87L<DBIx::Class::Schema/txn_scope_guard>.
88
89=head1 AUTHOR
90
91Ash Berlin, 2008.
92
93Insipred by L<Scope::Guard> by chocolateboy.
94
95This module is free software. It may be used, redistributed and/or modified
96under the same terms as Perl itself.
97
98=cut