Add txn_scope_guard method/object
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / TxnScopeGuard.pm
CommitLineData
1bc193ac 1package DBIx::Class::Storage::TxnScopeGuard;
2
3use strict;
4use warnings;
5
6sub new {
7 my ($class, $storage) = @_;
8
9 $storage->txn_begin;
10 bless [ 0, $storage ], ref $class || $class;
11}
12
13sub commit {
14 my $self = shift;
15
16 $self->[1]->txn_commit;
17 $self->[0] = 1;
18}
19
20sub DESTROY {
21 my ($dismiss, $storage) = @{$_[0]};
22
23 $storage->txn_rollback unless $dismiss;
24}
25
261;
27
28__END__
29
30=head1 NAME
31
32DBIx::Class::Storage::TxnScopeGuard
33
34=head1 SYNOPSIS
35
36 sub foo {
37 my ($self, $schema) = @_;
38
39 my $guard = $schema->txn_scope_guard;
40
41 # Multiple database operations here
42
43 $guard->commit;
44 }
45
46=head1 DESCRIPTION
47
48An object that behaves much like L<Scope::Guard>, but hardcoded to do the
49right thing with transactions in DBIx::Class.
50
51=head1 METHODS
52
53=head2 new
54
55Creating an instance of this class will start a new transaction. Expects a
56L<DBIx::Class::Storage> object as its only argument.
57
58=head2 commit
59
60Commit the transaction, and stop guarding the scope. If this method is not
61called (i.e. an exception is thrown) and this object goes out of scope then
62the transaction is rolled back.
63
64=cut
65
66=head1 SEE ALSO
67
68L<DBIx::Class::Schema/txn_scope_guard>.
69
70=head1 AUTHOR
71
72Ash Berlin, 2008.
73
74Insipred by L<Scope::Guard> by chocolateboy.
75
76This module is free software. It may be used, redistributed and/or modified
77under the same terms as Perl itself.
78
79=cut