blib/lib/DBIx/Class/DeleteAction.pm

filter: Statementstmt 94.6% 88 / 93 Branchbran 71.2% 47 / 66 Conditioncond 86.6% 13 / 15 MC/DCmcdc 77.7% 7 / 9 Subroutinesub 100% 6 / 6 Podpod 100% 1 / 1 totaltotal 85.2% 162 / 190 CC 43 SCAR 38.0
CC
43
Cov
85%
delete
50.7
_delete_action_identifier
2.0
BEGIN
1.0
CRAP 44.5
↑ Summary
1 # ============================================================================
2 package DBIx::Class::DeleteAction;
3 # ============================================================================
4 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 9 ▶use base qw(DBIx::Class);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 9 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 our $AUTHORITY = 'cpan:MAROS';
11 9 our $VERSION = version->new("1.05");
12  
13 =encoding utf8
14  
15 =head1 NAME
16  
17 DBIx::Class::DeleteAction - Define delete triggers
18  
19 =head1 SYNOPSIS
20  
21 # Actor DBIC class
22 package Your::Schema::Actor;
23 use strict;
24 use warnings;
25
26 use base 'DBIx::Class';
27  
28 __PACKAGE__->load_components("DeleteAction","PK","Core");
29
30 __PACKAGE__->table("actor");
31 __PACKAGE__->add_columns(qw/id name/);
32 __PACKAGE__->set_primary_key('id');
33
34 __PACKAGE__->has_many(
35 'actorroles' => 'MyDB::Schema::ActorRole',
36 { 'foreign.actor' => 'self.id' },
37 { delete_action => 'delete' }
38 );
39
40 # Actor Role DBIC class
41 package Your::Schema::ActorRole;
42 use strict;
43 use warnings;
44
45 use base 'DBIx::Class';
46
47 __PACKAGE__->load_components("DeleteAction","PK","Core");
48
49 __PACKAGE__->table("actor_role");
50 __PACKAGE__->add_columns(qw/id name actor production/);
51 __PACKAGE__->set_primary_key('id');
52
53 __PACKAGE__->belongs_to(
54 'actor' => 'MyDB::Schema::Actor',
55 { 'foreign.id' => 'self.actor' },
56 { delete_action =>
57 sub {
58 my ($self,$params) = @_;
59 # Do something special
60 }
61 }
62 );
63
64 __PACKAGE__->belongs_to(
65 'production' => 'MyDB::Schema::Production',
66 { 'foreign.id' => 'self.production' },
67 { delete_action => 'deny' }
68 );
69
70 # Somewhere else
71 $schema->txn_do(sub {
72 $actor->delete();
73 });
74 # Deletes all related actorroles only if they don't have a production
75 # Finally deletes the actor itself (Always use transactions!!!)
76
77 $schema->txn_do(sub {
78 $actor_role->delete();
79 });
80 # Calls custom subroutine on actor
81 # Denies deletion if a production is related
82  
83 =head1 DESCRIPTION
84  
85 With this DBIx::Class component you can specify actions that should be
86 triggered on a row delete. A delete action is specified by adding the
87 'delete_action' key to the optional attribute HASH reference when specifing
88 a new relation (see L<DBIx::Class::Relationship>).
89  
90 The following delete actions are supported:
91  
92 =over
93  
94 =item * null
95  
96 Set all columns in related rows pointing to this record to NULL. Only works
97 on 'has_many' relationships.
98  
99 =item * delete OR cascade
100  
101 Delete all related records one by one. This can trigger further delete
102 actions.
103  
104 =item * deleteall
105  
106 Delete all related records in a single step. This does not trigger further
107 delete actions.
108  
109 Only works on 'has_many' relationships.
110  
111 =item * deny
112  
113 Deny deletion if this record is being referenced from other rows.
114  
115 =item * CODE reference
116  
117 Executes the code referece on delete. The current L<DBIx::Class::Row> object
118 and the name of the relation are passed to the code reference.
119  
120 =item * STRING
121  
122 Execute a method with the given name. The method will be called on the current
123 L<DBIx::Class::Row> object and will be passed the name of the relation.
124  
125 =item * ignore
126  
127 Do nothing
128  
129 =back
130  
131 =head2 Custom delete handlers
132  
133 If you set the C<delete_action> to execute a method or a code reference the
134 method will be called with the following parameters:
135  
136 =over
137  
138 =item * $self
139  
140 The L<DBIx::Class::Row> object the delete action has been called upon.
141  
142 =item * HASHREF
143  
144 A hashref of named parameters
145  
146 =over
147  
148 =item * relationship
149  
150 The name of the relationship that is currently being processed.
151  
152 =item * related
153  
154 The related object(s) for the given object and relationship.
155  
156 Depending on the type of the relationship this can either be a
157 L<DBIx::Class::Row> or a L<DBIx::Class::ResultSet> object.
158  
159 =item * seen
160  
161 An arraryref with object identifiers which have already been processed.
162 If you want to call another L<delete> method from your code you MUST
163 pass on this variable so that we can ensure that each object/row is handled
164 only once.
165  
166 =item * Extra values
167  
168 Any other values that you pass to 'delete'.
169  
170 =back
171  
172 =back
173  
174 =head2 delete
175  
176 $object->delete();
177 OR
178 $object->delete(HASHREF);
179  
180 This method overdrives the L<DBIx::Class::Row> delete method. You can
181 add arbitrary data as HASHREF which will be passed to your custom
182 delete handles.
183  
184 Make sure that you ALWAYS call C<delete> always inside a TRANSACTION
185 block.
186  
187 If you call another C<delete> from within a custom delete handler always pass
188 on the C<seen> parameter.
189  
190 =cut
191  
192 36 ▶sub _delete_action_identifier {
Subroutine _delete_action_identifier: called CC=2 SCAR=6.9
193 36 my $self = shift;
194 36 my @primary = $self->primary_columns;
195 36 ▶ return ref($self) . join '|',map { $self->get_column($_) || '' } @primary;
Condition100%2/2
$self->get_column($_) || ''
l!l
351
MC/DC100%1/1
$self->get_column($_) || ''
$self->get_column($_)
Truth table100%2/2
A
A= $self->get_column($_)
Aresult
11
00
196 }
197  
198 33 ▶sub delete {
Subroutine delete: called CC=42 SCAR=39.3
Pod documented
199 33 my ($self,$params) = @_;
200  
201 33 ▶ $params ||= {};
Condition100%2/2
$params ||= {}
l!l
1518
MC/DC100%1/1
$params ||= {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
202 33 ▶ $params->{seen} ||= [];
Condition100%2/2
$params->{"seen"} ||= []
l!l
1419
MC/DC100%1/1
$params->{"seen"} ||= []
$params->{"seen"}
Truth table100%2/2
A
A= $params->{"seen"}
Aresult
11
00
203
204 # Ignore Class deletes. DBIx::Class::Relationship::CascadeActions
205 # does too so why should I bother?
206 33 ▶ return $self->next::method($params)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self and $self->isa("DBIx::Class::Row") 0 33 33
Condition33%1/3
ref $self and $self->isa("DBIx::Class::Row")
!ll&&!rl&&r
0033
MC/DC0%0/2
ref $self and $self->isa("DBIx::Class::Row")
ref $self $self->isa("DBIx::Class::Row")
Truth table33%1/3
A and B
A= ref $selfB= $self->isa("DBIx::Class::Row")
ABresult
0X0
100
111
207 unless ref $self && $self->isa('DBIx::Class::Row');
208  
209 33 my $debug = $self->result_source->storage->debug();
210
211 33 my $identifier = $self->_delete_action_identifier;
212
213 # Check for identifier
214 33 ▶ return if (grep { $identifier eq $_ } @{$params->{seen}});
Branch: 1 branch
BranchTrueFalseTotal
if grep {$identifier eq $_;} @{$$params{"seen"};} 7 26 33
215
216 26 push @{$params->{seen}},$identifier;
217  
218 # Check if item is in the database before we proceed
219 26 ▶ $self->throw_exception( "Not in database" )
Branch: 1 branch
BranchTrueFalseTotal
unless $self->in_storage 1 25 26
220 unless $self->in_storage;
221
222 25 my $source = $self->result_source;
223  
224 # Loop all relations
225 25 RELATIONSHIP: foreach my $relationship ($source->relationships) {
226 40 my $relationship_info = $source->relationship_info($relationship);
227
228 # Ignore relation with no 'delete_action' key set
229 next RELATIONSHIP
230 40 ▶ unless $relationship_info->{attrs}{delete_action};
Branch: 1 branch
BranchTrueFalseTotal
unless $relationship_info->{"attrs"}{"delete_action"} 1 39 40
231
232 # Unset DBIC key cascade_delete attribute, so that we do not
233 # work twice
234 39 $relationship_info->{attrs}{cascade_delete} = 0;
235
236 # Get delete action parameter value
237 39 my $delete_action = $relationship_info->{attrs}{delete_action};
238  
239 next RELATIONSHIP
240 39 ▶ if $delete_action eq 'ignore';
Branch: 1 branch
BranchTrueFalseTotal
if $delete_action eq "ignore" 3 36 39
241
242 36 my $related;
243 # Only get relations with data
244 36 ▶ if ($relationship_info->{attrs}{accessor} eq 'multi') {
Branch: 1 branch
BranchTrueFalseTotal
if ($relationship_info->{'attrs'}{'accessor'} eq 'multi') { } 20 16 36
245 20 $related = $self->search_related($relationship);
246 next RELATIONSHIP
247 20 ▶ unless $related;
Branch: 1 branch
BranchTrueFalseTotal
unless $related 0 20 20
248 } else {
249 CONDITIONS:
250 16 foreach my $condition (values %{$relationship_info->{cond}}) {
251 16 ▶ if ($condition =~ m/^self\.(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($condition =~ /^self\.(.+)/) 16 0 16
252 16 my $column = $1;
253 next RELATIONSHIP
254 16 ▶ unless $self->get_column($column);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get_column($column) 2 14 16
255 # unless ($self->has_column_loaded($column)) {
256 # warn("LOAD $column");
257 # $self = $self->get_from_storage();
258 # next RELATIONSHIP
259 # unless $self->get_column($column);
260 # last CONDITIONS;
261 # }
262 }
263 }
264  
265 14 $related = $self->$relationship;
266 next RELATIONSHIP
267 14 ▶ unless $related;
Branch: 1 branch
BranchTrueFalseTotal
unless $related 0 14 14
268 }
269  
270 # This would be much nicer with 5.10s given/when/default
271 # Action: NULL
272 34 ▶ if ($delete_action eq 'null') {
Branch: 3 branches
BranchTrueFalseTotal
if ($delete_action eq 'null') { } 4 30 34
elsif ($delete_action eq 'delete' or $delete_action eq 'cascade') { } 16 14 30
elsif ($delete_action eq 'deleteall') { } 6 8 14
273 4 ▶ warn('DeleteAction: NULL '.$self.'->'.$relationship) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 4 4
274 4 ▶ if ($related->isa('DBIx::Class::ResultSet')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related->isa('DBIx::Class::ResultSet')) { } 4 0 4
275 4 my $update = {};
276 4 foreach my $key (keys %{$relationship_info->{cond}} ) {
277 next RELATIONSHIP
278 4 ▶ unless $key =~ /^foreign\.(.+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /^foreign\.(.+)$/ 0 4 4
279 4 $update->{$1} = undef;
280 }
281 4 $related->update($update);
282 } else {
283 0 warn("Delete action 'null' does not work with ".$relationship_info->{attrs}{accessor}." relations");
284 }
285 # Action: DELETE
286 ▶ } elsif ($delete_action eq 'delete' || $delete_action eq 'cascade') {
Condition100%3/3
$delete_action eq "delete" or $delete_action eq "cascade"
l!l&&r!l&&!r
15114
MC/DC100%2/2
$delete_action eq "delete" or $delete_action eq "cascade"
$delete_action eq "delete" $delete_action eq "cascade"
Truth table100%3/3
A or B
A= $delete_action eq "delete"B= $delete_action eq "cascade"
ABresult
1X1
011
000
287 16 ▶ warn('DeleteAction: DELETE '.$self.'->'.$relationship) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 16 16
288 16 ▶ if ($related->isa('DBIx::Class::ResultSet')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related->isa('DBIx::Class::ResultSet')) { } 7 9 16
289 7 ▶ while (my $item = $related->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = $related->next) 5 7 12
290 5 $item->delete($params);
291 }
292 } else {
293 9 $related->delete($params);
294 }
295 # Action: DELETEALL
296 } elsif ($delete_action eq 'deleteall') {
297 6 ▶ warn('DeleteAction: DELETEALL '.$self.'->'.$relationship) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 6 6
298 6 ▶ if ($related->isa('DBIx::Class::ResultSet')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related->isa('DBIx::Class::ResultSet')) { } 6 0 6
299 6 $related->delete();
300 } else {
301 0 warn("Delete action 'null' does not work with ".$relationship_info->{attrs}{accessor}." relations");
302 }
303 } else {
304 8 ▶ if ($related->isa('DBIx::Class::ResultSet')
Branch: 1 branch
BranchTrueFalseTotal
if ($related->isa("DBIx::Class::ResultSet") and $related->count == 0) 1 7 8
Condition100%3/3
$related->isa("DBIx::Class::ResultSet") and $related->count == 0
!ll&&!rl&&r
521
MC/DC100%2/2
$related->isa("DBIx::Class::ResultSet") and $related->count == 0
$related->isa("DBIx::Class::ResultSet") $related->count == 0
Truth table100%3/3
A and B
A= $related->isa("DBIx::Class::ResultSet")B= $related->count == 0
ABresult
0X0
100
111
305 && $related->count == 0) {
306 1 next RELATIONSHIP;
307 }
308
309 # Action: DENY
310 7 ▶ if ($delete_action eq 'deny') {
Branch: 3 branches
BranchTrueFalseTotal
if ($delete_action eq 'deny') { } 3 4 7
elsif (ref $delete_action eq 'CODE') { } 0 4 4
elsif ($self->can($delete_action)) { } 3 1 4
311 3 ▶ warn('DeleteAction: DENY '.$self.'->'.$relationship) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 3 3
312 3 ▶ if ($related->isa('DBIx::Class::ResultSet')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related->isa('DBIx::Class::ResultSet')) { } 2 1 3
313 2 ▶ while (my $item = $related->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = $related->next) 2 0 2
314 2 my $compare_identifier = $item->_delete_action_identifier;
315 2 ▶ next if grep {$compare_identifier eq $_} @{$params->{seen}};
Branch: 1 branch
BranchTrueFalseTotal
if grep {$compare_identifier eq $_;} @{$$params{"seen"};} 0 2 2
316 2 $self->throw_exception("Can't delete the object because it is still referenced from other records");
317 }
318 } else {
319 1 my $compare_identifier = $related->_delete_action_identifier;
320 1 ▶ unless (grep {$compare_identifier eq $_} @{$params->{seen}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$compare_identifier eq $_;} @{$$params{"seen"};}) 1 0 1
321 1 $self->throw_exception("Can't delete the object because it is still referenced from other records");
322 }
323 }
324 # Action: CODE
325 } elsif (ref $delete_action eq 'CODE') {
326 0 ▶ warn('DeleteAction: CODE '.$self.'->'.$relationship) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
327 $delete_action->($self,{
328 relationship => $relationship,
329 related => $related,
330 0 %{$params},
331 });
332 # Action: METHOD
333 } elsif ($self->can($delete_action)) {
334 3 ▶ warn('DeleteAction: METHOD '.$self.'->'.$relationship.':'.$delete_action) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 3 3
335 $self->$delete_action({
336 relationship => $relationship,
337 related => $related,
338 3 %{$params},
339 });
340 # Fallback
341 } else {
342 1 $self->throw_exception("Invalid delete action '$delete_action'")
343 }
344 }
345 }
346  
347 19 ▶ warn('DeleteAction: FINISH '.$self) if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 19 19
348  
349 # Run delete
350 19 return $self->next::method($params);
351 }
352  
353 =head1 EXAMPLE
354  
355 =head2 Tree example
356  
357 This example shows a very simple tree schema, where each node points to its
358 parent node. Once you delete an item from the tree, all child nodes will be
359 appended to the parent node of the deleted node.
360  
361 package MyApp::Treenode;
362 use strict;
363 use warnings;
364
365 use parent qw(DBIx::Class);
366
367 __PACKAGE__->load_components(
368 "+DBIx::Class::DeleteAction",
369 "PK",
370 "Core",
371 );
372
373 __PACKAGE__->table("treenode");
374 __PACKAGE__->add_columns(qw/id name parent/);
375 __PACKAGE__->set_primary_key("id");
376
377 # Do not delete parent node
378 __PACKAGE__->might_have(
379 'parent' => 'MyApp::Treenode',
380 { "foreign.id" => "self.parent" },
381 { delete_action => 'ignore' },
382 );
383
384 # Update all child nodes
385 __PACKAGE__->has_many(
386 'children' => 'MyApp::Treenode',
387 { "foreign.parent" => "self.id" },
388 { delete_action => sub {
389 my ($self,$params) = @_;
390 $params->{related}->update({
391 parent => $self->get_column('parent'),
392 });
393 } },
394 );
395  
396 =head2 Debugging
397  
398 Use C<DBIC_TRACE=1> or set C<__PACKAGE__->storage->debug(1);> to see what
399 is exactly going on.
400  
401 =head1 CAVEATS
402  
403 Note that the C<delete> method in L<DBIx::Class::ResultSet> will not run
404 DeleteAction triggers. See C<delete_all> if you need triggers to run.
405  
406 Any database-level cascade, restrict or trigger will be performed AFTER
407 DBIx-Class-DeleteAction based triggers.
408  
409 Always use transactions, or else you might end up with inconsistent data.
410  
411 =head1 SUPPORT
412  
413 Please report any bugs or feature requests to
414 L<bug-dbix-class-deleteaction@rt.cpan.org>, or through the web interface at
415 L<http://rt.cpan.org/Public/Bug/Report.html?Queue=DBIx::Class::DeleteAction>.
416 I will be notified, and then you'll automatically be notified of progress on
417 your report as I make changes.
418  
419 =head1 AUTHOR
420  
421 Maroš Kollár
422 CPAN ID: MAROS
423 maros [at] k-1.com
424 L<http://www.revdev.at>
425  
426 =head1 ACKNOWLEDGEMENTS
427  
428 This module was written for Revdev L<http://www.revdev.at>, a nice litte
429 software company I run with Koki and Domm (L<http://search.cpan.org/~domm/>).
430  
431 =head1 COPYRIGHT
432  
433 DBIx::Class::DeleteAction is Copyright (c) 2008-9 Maroš Kollár
434 - L<http://www.revdev.at>
435  
436 This program is free software; you can redistribute it and/or modify it under
437 the same terms as Perl itself.
438  
439 The full text of the license can be found in the
440 LICENSE file included with this module.
441  
442 =cut
443  
444 9 "Delete me .... NAAAT";
↑ Summary