blib/lib/DBIx/TransactionManager/Distributed.pm

filter: Statementstmt 100% 102 / 102 Branchbran 75.0% 33 / 44 Conditioncond 66.6% 4 / 6 MC/DCmcdc 50.0% 2 / 4 Subroutinesub 100% 14 / 14 Podpod 100% 5 / 5 totaltotal 91.4% 160 / 175 SCAR 35.5
CC
34
Cov
91%
txn
17.0
release_dbh
6.2
register_dbh
5.0
CRAP 34.7
↑ Summary
1 package DBIx::TransactionManager::Distributed;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 2 ▶use Exporter qw(import export_to_level);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =head1 NAME
9
10 DBIx::TransactionManager::Distributed;
11
12 =head1 VERSION
13
14 0.01
15
16 =cut
17  
18 2 our $VERSION = "0.01";
19  
20 =head1 DESCRIPTION
21
22 Generic database handling utilities.
23
24 Currently provides a minimal database handle tracking facility, allowing code
25 to request a transaction against all active database handles.
26
27 =head1 SYNOPSIS
28
29 use DBIx::TransactionManager::Distributed qw(register_dbh release_dbh txn);
30 my $dbh1 = DBI->connect('dbi:Pg', '', '', { RaiseError => 1});
31 my $dbh2 = DBI->connect('dbi:Pg', '', '', { RaiseError => 1});
32 my $dbh3 = DBI->connect('dbi:Pg', '', '', { RaiseError => 1});
33
34 register_dbh(category1 => $dbh1);
35 register_dbh(category1 => $dbh2);
36 register_dbh(category2 => $dbh2);
37 register_dbh(category2 => $dbh3);
38
39 txn { $dbh1->do('update ta set name = "a"'); $dbh2->do('insert into tb values (1)') } 'category1';
40 txn { $dbh2->do('update tc set name = "b"'); $dbh3->do('insert into td values (2)') } 'category2';
41
42 release_dbh(category1 => $dbh1);
43 release_dbh(category1 => $dbh1);
44 release_dbh(category2 => $dbh2);
45 release_dbh(category3 => $dbh3);
46
47 =cut
48  
49 2 ▶use Scalar::Util qw(weaken refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
50 2 ▶use List::UtilsBy qw(extract_by);
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 2 our @EXPORT_OK = qw(register_dbh release_dbh dbh_is_registered txn register_cached_dbh);
53  
54 # List of all retained handles by category. Since we don't expect to update
55 # the list often, and the usual action is to iterate through them all in
56 # sequence, we're using an array rather than a hash.
57 # Each $dbh will be stored as a weakref: all calls to register_dbh should
58 # be matched with a release_dbh or global destruction, but we can recover
59 # (and complain) if that doesn't happen.
60 2 my %DBH;
61  
62 # Where we registered the dbh originally - top level key is category, second
63 # level is refaddr.
64 my %DBH_SOURCE;
65  
66 # Last PID we saw - used for invalidating stale DBH on fork
67 2 my $PID = $$;
68  
69 2 our $IN_TRANSACTION = 0;
70  
71 =head2 register_dbh
72
73 Records the given database handle as being active and available for running transactions against.
74
75 Expects a category (string value) and L<DBI::db> instance.
76
77 Returns the database handle.
78
79 Example:
80
81 sub _dbh {
82 my $dbh = DBI->connect('dbi:Pg', '', '', { RaiseError => 1});
83 return DBIx::TransactionManager::Distributaed::register_dbh(category => $dbh);
84 }
85
86 =cut
87  
88 sub register_dbh {
89 20 ▶    my ($category, $dbh) = @_;
Subroutine register_dbh: called CC=5 SCAR=16.1
Pod documented
90 20 ▶    die "too many parameters to register_dbh: @_" if @_ > 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 2 0 20 20
91 20     my $addr = refaddr $dbh;
92 20 ▶    if (dbh_is_registered($category, $dbh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (dbh_is_registered($category, $dbh)) 1 19 20
93 1         warn "already registered this database handle at " . $DBH_SOURCE{$category}{$addr};
94 1         return;
95     }
96 19     push @{$DBH{$category}}, $dbh;
97 19     weaken($DBH{$category}[-1]);
98 # filename:line (package::sub)
99 19     $DBH_SOURCE{$category}{$addr} = sprintf "%s:%d (%s::%s)", (caller 1)[1, 2, 0, 3];
100 # We may be connecting partway through a transaction - if so, we want to join this handle onto the list of
101 # active transactions
102 19 ▶    $dbh->begin_work if $IN_TRANSACTION && $dbh->{AutoCommit};
Branch: 1 branch
BranchTrueFalseTotal
if $DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"} 1 18 19
Condition100%3/3
$DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"}
!ll&&!rl&&r
1711
MC/DC100%2/2
$DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"}
$DBIx::TransactionManager::Distributed::IN_TRANSACTION $dbh->{"AutoCommit"}
Truth table100%3/3
A and B
A= $DBIx::TransactionManager::Distributed::IN_TRANSACTIONB= $dbh->{"AutoCommit"}
ABresult
0X0
100
111
103 19     $dbh;
104 }
105  
106 =head2 release_dbh
107
108 Marks the given database handle as no longer active - it will not be used for any further transaction requests
109 via L</txn>.
110
111 Returns the database handle.
112
113 Example:
114
115 sub DESTROY {
116 my $self = shift;
117 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
118 DBIx::TransactionManager::Distributaed::release_dbh($self->dbh)->disconnect;
119 }
120
121 =cut
122  
123 sub release_dbh {
124 5 ▶    my ($category, $dbh) = @_;
Subroutine release_dbh: called CC=6 SCAR=18.2
Pod documented
125 5 ▶    die "too many parameters to release_dbh: @_" if @_ > 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 2 0 5 5
126 # At destruction we may have an invalid handle
127 5 ▶    my $addr = refaddr $dbh or return $dbh;
Branch: 1 branch
BranchTrueFalseTotal
my $addr = builtin::refaddr($dbh) or return $dbh 0 5 5
128 5 ▶    unless (dbh_is_registered($category, $dbh)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (dbh_is_registered($category, $dbh)) 1 4 5
129 1         my @other_categories = grep exists $DBH_SOURCE{$_}{$addr}, sort keys %DBH_SOURCE;
130 1 ▶        warn "releasing unregistered dbh $dbh for category $category"
Branch: 1 branch
BranchTrueFalseTotal
@other_categories ? : 1 0 1
131             . (@other_categories ? " (but found it in these categories instead: " . join ', ', @other_categories, ')' : '');
132 # If we did find it elsewhere, make sure we do cleanup to reduce confusion
133 1         _remove_dbh_from_category($_ => $dbh) for @other_categories;
134     }
135 5     _remove_dbh_from_category($category => $dbh);
136 5     return $dbh;
137 }
138  
139 =head2 _remove_dbh_from_category
140
141 Helper function to reduce common code - removes the given C<$dbh> from a single category.
142
143 Used internally.
144
145 =cut
146  
147 sub _remove_dbh_from_category {
148 6 ▶    my ($category, $dbh) = @_;
Subroutine _remove_dbh_from_category: called CC=2 SCAR=7.1
149 6 ▶    my $addr = refaddr $dbh or return $dbh;
Branch: 1 branch
BranchTrueFalseTotal
my $addr = builtin::refaddr($dbh) or return $dbh 0 6 6
150 6     delete $DBH_SOURCE{$category}{$addr};
151 # avoiding grep here because these are weakrefs and we want them to stay that way.
152 # since they're weakrefs, some of these may be undef
153 6 ▶    extract_by { $addr == (defined($_) ? refaddr($_) : 0) } @{$DBH{$category}};
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 5 0 5
154 6     return $dbh;
155 }
156  
157 =head2 dbh_is_registered
158
159 Returns true if the provided database handle has been registered already.
160
161 Used when registering a handle acquired via L<DBI/connect_cached>.
162
163 register_dbh($category => $dbh) unless dbh_is_registered($category => $dbh);
164
165 =cut
166  
167 sub dbh_is_registered {
168 34 ▶    my ($category, $dbh) = @_;
Subroutine dbh_is_registered: called CC=3 SCAR=11.0
Pod documented
169 34 ▶    die "too many parameters to register_dbh: @_" if @_ > 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 2 0 34 34
170 34     _check_fork();
171 34     my $addr = refaddr $dbh;
172 34 ▶    return exists $DBH_SOURCE{$category}{$addr} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $DBH_SOURCE{$category}{$addr} ? : 10 24 34
173 }
174  
175 =head2 register_cached_dbh
176
177 Records the given database handle created via L<DBI/connect_cached> as being active and available for running transactions against.
178
179 Expects a category (string value) and L<DBI::db> instance.
180
181 Returns the database handle.
182
183 Example:
184
185 sub _dbh {
186 my $dbh = DBI->connect_cached('dbi:Pg', '', '', { RaiseError => 1});
187 return register_cached_dbh('category' => $dbh);
188 }
189
190 =cut
191  
192 sub register_cached_dbh {
193 1 ▶    my ($category, $dbh) = @_;
Subroutine register_cached_dbh: called CC=4 SCAR=15.6
Pod documented
194 1 ▶    register_dbh($category => $dbh) unless dbh_is_registered($category => $dbh);
Branch: 1 branch
BranchTrueFalseTotal
unless dbh_is_registered($category, $dbh) 0 1 1
195 1 ▶    $dbh->begin_work if $IN_TRANSACTION && $dbh->{AutoCommit};
Branch: 1 branch
BranchTrueFalseTotal
if $DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"} 0 1 1
Condition33%1/3
$DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"}
!ll&&!rl&&r
100
MC/DC0%0/2
$DBIx::TransactionManager::Distributed::IN_TRANSACTION and $dbh->{"AutoCommit"}
$DBIx::TransactionManager::Distributed::IN_TRANSACTION $dbh->{"AutoCommit"}
Truth table33%1/3
A and B
A= $DBIx::TransactionManager::Distributed::IN_TRANSACTIONB= $dbh->{"AutoCommit"}
ABresult
0X0
100
111
196 1     $dbh;
197 }
198  
199 =head2 txn
200
201 Runs the given coderef in a transaction.
202
203 Expects a coderef and one or more database handle categories.
204
205 Will call L<DBI/begin_work> for every known database handle in the given category,
206 run the code, then call L<DBI/commit> on success, or L<DBI/rollback> on failure.
207
208 Will raise an exception on failure, or return an empty list on success.
209
210 Example:
211
212 txn { dbh()->do('NOTIFY something') } 'category';
213
214 WARNING: This only applies transactions to known database handles. Anything else -
215 Redis, cache layers, files on disk - is out of scope. Transactions are a simple
216 L<DBI/begin_work> / L<DBI/commit> pair, there's no 2-phase commit or other
217 distributed transaction co-ordination happening here.
218
219 =cut
220  
221 sub txn(&;@) {
222 6 ▶    my ($code, @categories) = @_;
Subroutine txn: called CC=17 SCAR=28.3
Pod documented
223 6 ▶    die "Need a database category" unless @categories;
Branch: 1 branch
BranchTrueFalseTotal
unless @categories 0 6 6
224 6     _check_fork();
225 6     my $wantarray = wantarray;
226 6     for my $category (@categories) {
227 6 ▶        if (my $count = () = extract_by { !defined($_) } @{$DBH{$category}}) {
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if (my $count = () = &extract_by(sub { not defined $_; } , \@{$DBH{$category};})) 1 5 6
228 1             warn "Had $count database handles that were not released via release_dbh, probable candidates follow:\n";
229 1             my %addr = map { ; refaddr($_) => 1 } @{$DBH{$category}};
230 1             warn "unreleased dbh in $_\n" for sort delete @{$DBH_SOURCE{$category}}{grep !exists $addr{$_}, keys %{$DBH_SOURCE{$category}}};
231         }
232     }
233  
234 6     my @rslt;
235     eval {
236 6         for my $category (@categories) {
237 6 ▶            $_->{AutoCommit} && $_->begin_work for @{$DBH{$category}};
Branch: 1 branch
BranchTrueFalseTotal
$_->{"AutoCommit"} and $_->begin_work 9 0 9
238         }
239 6         local $IN_TRANSACTION = 1;
240 # We want to pass through list/scalar/void context to the coderef
241 6 ▶        if ($wantarray) {
Branch: 2 branches
BranchTrueFalseTotal
if ($wantarray) { } 1 5 6
elsif (defined $wantarray) { } 1 4 5
242 1             @rslt = $code->();
243         } elsif (defined $wantarray) {
244 1             $rslt[0] = $code->();
245         } else {
246 4             $code->();
247         }
248 5         _check_fork();
249 5         for my $category (@categories) {
250 # Note that we may hit exceptions here, and we want to raise them since it means the
251 # database activity did not complete as expected
252 5             $_->commit for grep defined, @{$DBH{$category}}; # might have closed database handle(s) in $code
253         }
254 5         1;
255 6 ▶    } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { foreach my $category (@categories) { $_->{"AutoCommit"} and $_->begin_work foreach (@{$DBH{$category};}); } ; local $DBIx::TransactionManager::Distributed::IN_TRANSACTION = 1; if ($wantarray) { @rslt = &$code(); } elsif (defined $wantarray) { $rslt[0] = &$code(); } else { &$code(); } ; _check_fork(); foreach my $category (@categories) { $_->commit foreach (grep defined($_), @{$DBH{$category};}); } ; 1 } } or do { my $err = $@; warn "Error in transaction: $err"; foreach my $category (@categories) { (eval { do { $_->rollback; 1 } } or warn "after $err also had failure in rollback for dbh in category ${category}: $@") foreach (grep defined($_), @{$DBH{$category};}); } ; die $err } 1 5 6
256 1         my $err = $@;
257 1         warn "Error in transaction: $err";
258 1         for my $category (@categories) {
259             eval {
260 2                 $_->rollback;
261 1                 1;
262 1 ▶            } or warn "after $err also had failure in rollback for dbh in category $category: $@" for grep defined, @{$DBH{$category}};
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $_->rollback; 1 } } or warn "after $err also had failure in rollback for dbh in category ${category}: $@" 1 1 2
263         }
264 1         die $err;
265     };
266 5 ▶    return $wantarray ? @rslt : $rslt[0];
Branch: 1 branch
BranchTrueFalseTotal
$wantarray ? : 1 4 5
267 }
268  
269 =head2 _check_fork
270
271 Test whether we have forked recently, and invalidate all our caches if we have.
272
273 Returns true if there has been a fork since last check, false otherwise.
274
275 =cut
276  
277 sub _check_fork {
278 48 ▶    return 0 if $PID == $$;
Subroutine _check_fork: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $PID == $$ 38 10 48
279 10     $PID = $$;
280 10     %DBH = ();
281 10     %DBH_SOURCE = ();
282 10     return 1;
283 }
284  
285 2 1;
286  
287 =head1 SEE ALSO
288
289 L<DBIx::TransactionManager>
290
291 L<DBIx::ScopedTransaction>
292
293 L<DBIx::Class::Storage::TxnScopeGuard>
294
295 These modules are also handling scope-based transaction. The main difference is this one operates across database handles with different categories.
↑ Summary