DBIx/Class/Valiant/Result.pm

filter: Statementstmt 83.4% 623 / 747 Branchbran 64.3% 247 / 384 Conditioncond 57.1% 32 / 56 MC/DCmcdc 38.7% 12 / 31 Subroutinesub 86.5% 45 / 52 Podpod 23.3% 7 / 30 totaltotal 74.3% 966 / 1300 CC 236 SCAR 37.6
CC
236
Cov
76%
set_from_params_recursively
245.3
build_related_if_empty
90.0
set_multi_related_from_params
59.1
CRAP 43.1
« Valiant/Validator/Each.pm ↑ Summary Valiant/Validator/Collection.pm »
1 package DBIx::Class::Valiant::Result;
2  
3 7 ▶use base 'DBIx::Class';
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 7 ▶use Role::Tiny::With;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Valiant::Util 'debug';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use namespace::autoclean -also => ['debug'];
Subroutine BEGIN: called CC=1 SCAR=0.0
13 7 ▶use DBIx::Class::Valiant::Util::Exception::TooManyRows;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 7 ▶use DBIx::Class::Valiant::Util::Exception::BadParameterFK;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 7 ▶use DBIx::Class::Valiant::Util::Exception::BadParameters;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 7 with 'DBIx::Class::Valiant::Validates';
18 7 with 'Valiant::Filterable';
19  
20 7 ▶use DBIx::Class::Candy::Exports;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 7 export_methods ['filters', 'validates', 'filters_with', 'validates_with', 'accept_nested_for', 'auto_validation'];
22  
23 7 __PACKAGE__->mk_classdata( _m2m_metadata => {} );
24 7 __PACKAGE__->mk_classdata( auto_validation => 1 );
25 7 __PACKAGE__->mk_classdata( _nested => [] );
26 7 __PACKAGE__->mk_classdata( _src_info => '' );
27  
28 sub many_to_many {
29 4 ▶ my $class = shift;
Subroutine many_to_many: called CC=4 SCAR=16.3
Pod undocumented
30 4 my ($meth_name, $link, $far_side) = @_;
31 4 my $store = $class->_m2m_metadata;
32 warn("You are overwritting another relationship's metadata")
33 4 ▶ if exists $store->{$meth_name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $store->{$meth_name} 0 4 4
34
35 4 ▶ my $attrs = {
Branch: 1 branch
BranchTrueFalseTotal
@_ > 3 ? : 0 4 4
36 accessor => $meth_name,
37 relation => $link, #"link" table or immediate relation
38 foreign_relation => $far_side, #'far' table or foreign relation
39 (@_ > 3 ? (attrs => $_[3]) : ()), #only store if exist
40 rs_method => "${meth_name}_rs", #for completeness..
41 add_method => "add_to_${meth_name}",
42 set_method => "set_${meth_name}",
43 remove_method => "remove_from_${meth_name}",
44 };
45  
46 4 my $pk_meth = qq[
47 package $class;
48  
49 sub ${meth_name}_pks {
50 my \$self = shift;
51 my \@pks = \$self->related_resultset("${link}")->related_resultset("${far_side}")->result_source->primary_columns;
52 return map {
53 my \$row = \$_;
54 +{ map { \$_ => \$row->\$_ } \@pks };
55 } \$self->\$meth_name->all;
56 }
57 ];
58  
59 4 ▶ eval $pk_meth;
Subroutine roles_pks: not called CC=1 SCAR=4.9
Pod undocumented
60 4 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
61
62 #inheritable data workaround
63 4 $class->_m2m_metadata({ $meth_name => $attrs, %$store});
64 4 $class->next::method(@_);
65 }
66  
67 ▶sub BUILDARGS { } # The filter role wants this (for now)
Subroutine BUILDARGS: called CC=1 SCAR=0.0
Pod undocumented
68  
69 sub new { # also support for the filter role
70 141 ▶ my ($class, $attrs) = @_;
Subroutine new: called CC=3 SCAR=11.0
Pod undocumented
71 141 my @columns = $class->columns;
72 141 my %columns = ();
73 141 foreach my $column (@columns) { #strip $attrs on non column stuff
74 491 ▶ if(exists($attrs->{$column})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $attrs->{$column}) 214 277 491
75 214 $columns{$column} = $attrs->{$column};
76 }
77 }
78 141 my %filtered = (%$attrs, %{$class->_process_filters(\%columns)});
79 141 my $self = $class->next::method(\%filtered);
80 141 return $self;
81 }
82  
83 sub accept_nested_for {
84 562 ▶ my $class = blessed($_[0]) ? ref(shift) : shift;
Subroutine accept_nested_for: called CC=10 SCAR=23.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[0]) ? : 0 562 562
85 562 my %default_config = (
86 allow_destroy => 0,
87 reject_if => 0,
88 limit => 0,
89 update_only => 0,
90 );
91  
92 562 my @existing = @{$class->_nested};
93 562 ▶ my %m2m_names = map { $_=>1 } keys %{ $class->_m2m_metadata ||+{} };
Branch: 1 branch
BranchTrueFalseTotal
$class->_m2m_metadata or {} 0 562 562
94  
95 562 my $changed = 0;
96 562 ▶ while(my $attribute = shift) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $attribute = shift()) 50 562 612
97 50 ▶ my $config = (ref($_[0])||'') eq 'HASH' ? shift : +{};
Branch: 1 branch
BranchTrueFalseTotal
(ref $_[0] || '') eq 'HASH' ? : 32 18 50
Condition100%2/2
ref $_[0] || ''
l!l
3218
MC/DC100%1/1
ref $_[0] || ''
ref $_[0]
Truth table100%2/2
A
A= ref $_[0]
Aresult
11
00
98 50 push @existing, $attribute;
99 50 push @existing, +{ %default_config, %$config };
100 50 $changed = 1;
101  
102 ## Handed m2m, ugg
103 50 ▶ if($m2m_names{$attribute}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m2m_names{$attribute}) 3 47 50
104 # treat it like a set
105 3 $class->validates($attribute => (result_set=>+{validations=>1} ));
106 3 next;
107 }
108  
109 ## Add validation
110 47 my $rel_data = $class->relationship_info($attribute);
111  
112 47 ▶ die "'$attribute' does not seem to be a relationship. There's a typo in your source or you've placed your 'accept_nested_for' statement before the relationship it's associated with (has_many, belongs_to, etc)." unless $rel_data;
Branch: 1 branch
BranchTrueFalseTotal
unless $rel_data 0 47 47
113  
114 47 my $rel_type = $rel_data->{attrs}{accessor};
115 47 ▶ if($rel_type eq 'single') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel_type eq 'single') { } 37 10 47
116 37 $class->validates($attribute => (result=>+{validations=>1} ));
117 } else {
118 10 $class->validates($attribute => (result_set=>+{validations=>1} ));
119 }
120 }
121 562 ▶ $class->_nested(\@existing) if $changed;
Branch: 1 branch
BranchTrueFalseTotal
if $changed 50 512 562
122
123 562 return @existing;
124 }
125  
126 sub insert {
127 101 ▶ my ($self, @args) = @_;
Subroutine insert: called CC=15 SCAR=31.7
Pod undocumented
128 101 ▶ my %args = %{ $self->{__VALIANT_CREATE_ARGS} ||+{} };
Branch: 1 branch
BranchTrueFalseTotal
$self->{"__VALIANT_CREATE_ARGS"} or {} 90 11 101
129 101 ▶ my $context = $args{context}||[];
Condition100%2/2
$args{'context'} || []
l!l
1190
MC/DC100%1/1
$args{'context'} || []
$args{'context'}
Truth table100%2/2
A
A= $args{'context'}
Aresult
11
00
130 101 ▶ my @context = ref($context)||'' eq 'ARRAY' ? @$context : ($context);
Branch: 1 branch
BranchTrueFalseTotal
ref $context || !1 ? : 99 2 101
Condition100%2/2
ref $context or
l!l
992
MC/DC100%1/1
ref $context or
ref $context
Truth table100%2/2
A
A= ref $context
Aresult
11
00
131 101 ▶ push @context, 'create' unless grep { $_ eq 'create' } @context;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq "create";} @context 101 0 101
132  
133 # Add in any extra or new contexts passed as ->insert({__context=>...})
134 101 ▶ if( (ref($args[0])||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $args[0] || "") eq "HASH") 0 101 101
Condition50%1/2
ref $args[0] || ''
l!l
0101
MC/DC0%0/1
ref $args[0] || ''
ref $args[0]
Truth table50%1/2
A
A= ref $args[0]
Aresult
11
00
135 0 ▶ my $ctx = delete($args[0]->{__context})||[];
Condition0%0/2
delete $args[0]{'__context'} || []
l!l
00
MC/DC0%0/1
delete $args[0]{'__context'} || []
delete $args[0]{'__context'}
Truth table0%0/2
A
A= delete $args[0]{'__context'}
Aresult
11
00
136 0 ▶ my @ctx = ref($ctx)||'' eq 'ARRAY' ? @$ctx : ($ctx);
Branch: 1 branch
BranchTrueFalseTotal
ref $ctx || !1 ? : 0 0 0
Condition0%0/2
ref $ctx or
l!l
00
MC/DC0%0/1
ref $ctx or
ref $ctx
Truth table0%0/2
A
A= ref $ctx
Aresult
11
00
137 0 ▶ push @context, @ctx unless grep { $_ eq 'update' } @context; ## ?? IS this a bug? Why update
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq "update";} @context 0 0 0
138 }
139  
140 101 $args{context} = \@context;
141  
142 101 debug 2, "About to run validations for @{[$self]} on insert";
143 101 ▶ $self->validate(%args) if $self->auto_validation;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_validation 100 1 101
144  
145 101 ▶ if($self->errors->size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->errors->size) { } 19 82 101
146 19 debug 2, "Skipping insert for @{[$self]} because its invalid";
147 19 return $self;
148 } else {
149 82 debug 2, "proceeding to insert @{[$self]} because its valid";
150 }
151  
152 82 ▶ if($self->{__valiant_donot_insert}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"__valiant_donot_insert"}) 0 82 82
153 0 debug 2, "Skipping insert for @{[$self]} because its probably and _add";
154 0 return $self;
155 }
156 82 my $ret = $self->next::method(@args);
157 # TODO could probably do the merge errors from related here
158 82 return $ret;
159 }
160  
161 sub _nested_info_for_related {
162 72 ▶ my ($self, $related) = @_;
Subroutine _nested_info_for_related: called CC=2 SCAR=7.0
163 72 my %nested = $self->result_class->accept_nested_for;
164 72 ▶ my %info = %{ $nested{$related}||+{} };
Branch: 1 branch
BranchTrueFalseTotal
$nested{$related} or {} 0 72 72
165 72 return %info;
166 }
167  
168 sub _related_allow_destroy {
169 35 ▶ my ($self, $related) = @_;
Subroutine _related_allow_destroy: called CC=4 SCAR=14.0
170 35 my %info = $self->_nested_info_for_related($related);
171 35 ▶ if(my $proto = $info{allow_destroy}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $proto = $info{"allow_destroy"}) 22 13 35
172 22 ▶ my $allow_or_not = (ref($proto)||'' eq 'CODE') ? $proto->($self) : $proto;
Branch: 1 branch
BranchTrueFalseTotal
ref $proto || !1 ? : 0 22 22
Condition50%1/2
ref $proto or
l!l
022
MC/DC0%0/1
ref $proto or
ref $proto
Truth table50%1/2
A
A= ref $proto
Aresult
11
00
173 22 return $allow_or_not;
174 }
175 13 return 0;
176 }
177  
178 sub _related_limit {
179 37 ▶ my ($self, $related) = @_;
Subroutine _related_limit: called CC=4 SCAR=14.0
180 37 my %info = $self->_nested_info_for_related($related);
181 37 ▶ if(my $limit_proto = $info{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $limit_proto = $info{"limit"}) 2 35 37
182 2 ▶ my $limit = (ref($limit_proto)||'' eq 'CODE') ? $limit_proto->($self) : $limit_proto;
Branch: 1 branch
BranchTrueFalseTotal
ref $limit_proto || !1 ? : 0 2 2
Condition50%1/2
ref $limit_proto or
l!l
02
MC/DC0%0/1
ref $limit_proto or
ref $limit_proto
Truth table50%1/2
A
A= ref $limit_proto
Aresult
11
00
183 2 return 1, $limit;
184 }
185 35 return 0, undef;
186 }
187  
188 sub update {
189 93 ▶ my ($self, $upd) = @_;
Subroutine update: called CC=21 SCAR=31.4
Pod undocumented
190 93 ▶ my $context = delete($upd->{__context})||[];
Condition100%2/2
delete $upd->{'__context'} || []
l!l
885
MC/DC100%1/1
delete $upd->{'__context'} || []
delete $upd->{'__context'}
Truth table100%2/2
A
A= delete $upd->{'__context'}
Aresult
11
00
191 93 ▶ my @context = ref($context)||'' eq 'ARRAY' ? @$context : ($context);
Branch: 1 branch
BranchTrueFalseTotal
ref $context || !1 ? : 90 3 93
Condition100%2/2
ref $context or
l!l
903
MC/DC100%1/1
ref $context or
ref $context
Truth table100%2/2
A
A= ref $context
Aresult
11
00
192 93 ▶ push @context, 'update' unless grep { $_ eq 'update' } @context;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq "update";} @context 93 0 93
193  
194 93 my %related = ();
195 93 my %nested = $self->result_class->accept_nested_for;
196  
197 93 foreach my $associated(keys %nested) {
198 $related{$associated} = delete($upd->{$associated})
199 113 ▶ if exists($upd->{$associated});
Branch: 1 branch
BranchTrueFalseTotal
if exists $upd->{$associated} 37 76 113
200 }
201  
202 # Remove any relationed keys we didn't find with the allows nested
203 93 my @rel_names = $self->result_source->relationships();
204 93 ▶ my @m2m_names = keys %{ $self->result_class->_m2m_metadata ||+{} };
Branch: 1 branch
BranchTrueFalseTotal
$self->result_class->_m2m_metadata or {} 0 93 93
205 93 debug 1, "Found related for @{[ ref $self ]} of @{[ join ',', @rel_names ]}";
206  
207 93 my %found = map { $_ => delete($upd->{$_}) } @rel_names, @m2m_names; # backcompat with old perl
208  
209 93 ▶ if(grep { defined $_ } values %found) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {defined $_;} values %found) 0 93 93
210 0 my $related = join(', ', grep { $found{$_} } keys %found);
211 0 die "You are trying to create a relationship ($related) without setting 'accept_nested_for'";
212 }
213  
214 93 ▶ my %validate_args = (context => \@context) if @context;
Branch: 1 branch
BranchTrueFalseTotal
if @context 93 0 93
215  
216 93 ▶ $self->set_inflated_columns($upd) if $upd;
Branch: 1 branch
BranchTrueFalseTotal
if $upd 93 0 93
217  
218 93 foreach my $related(keys %related) {
219  
220 37 ▶ if(my $cb = $nested{$related}->{reject_if}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $nested{$related}{"reject_if"}) 0 37 37
221 0 ▶ next if $cb->($self, $related{$related});
Branch: 1 branch
BranchTrueFalseTotal
if &$cb($self, $related{$related}) 0 0 0
222 }
223  
224 37 my ($has_limit, $limit) = $self->_related_limit($related);
225 37 ▶ if($has_limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_limit) 2 35 37
226 2 my $num = scalar @{$related{$related}};
227 2 ▶ DBIx::Class::Valiant::Util::Exception::TooManyRows
Branch: 1 branch
BranchTrueFalseTotal
if $num > $limit 0 2 2
228 ->throw(
229 limit=>$limit,
230 attempted=>$num,
231 related=>$related,
232 me=>$self->result_source->name,
233 ) if $num > $limit;
234 }
235  
236 37 debug 2, "Setting related '$related' for @{[ ref $self ]} ";
237  
238 #$self->update_or_create_related($related, $related{$related});
239 37 $self->{_valiant_nested_info} = $nested{$related};
240 37 $self->set_related_from_params($related, $related{$related});
241  
242 35 delete $self->{_valiant_nested_info};
243 }
244  
245 91 debug 2, "About to run validations for @{[$self]} on update";
246 91 ▶ $self->validate(%validate_args) if $self->auto_validation;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_validation 91 0 91
247  
248  
249 91 ▶ if($self->has_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_errors) 32 59 91
250 32 debug 2, "Validation errors found, skipping mutate for @{[ ref $self ]} ";
251 32 return $self;
252 }
253 59 debug 2, "No validation issues found, proceeding to mutate @{[ ref $self ]} ";
254  
255 # wrap it all in a transaction to undo if issues.
256 59 my $txn_guard = $self->result_source->schema->txn_scope_guard;
257  
258 59 foreach my $related(keys %nested) {
259 57 ▶ if(my $cb = $nested{$related}->{reject_if}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $nested{$related}{"reject_if"}) 9 48 57
260 9 ▶ next if $cb->($self, $related{$related});
Branch: 1 branch
BranchTrueFalseTotal
if &$cb($self, $related{$related}) 0 9 9
261 }
262 57 debug 3, "mutating related $related for @{[ ref $self ]} ";
263 57 $self->_mutate_related($related);
264 }
265  
266 59 my $result = $self->next::method();
267 59 $txn_guard->commit;
268  
269 59 return $result;
270 }
271  
272 sub register_column {
273 200 ▶ my $class = shift;
Subroutine register_column: called CC=3 SCAR=11.3
Pod undocumented
274 200 my ($column, $info) = @_;
275  
276 200 ▶ if(my $validates = delete($info->{validates})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $validates = delete $info->{"validates"}) 1 199 200
277 1 debug 1, "Found validation info inside column '$column' definition";
278 1 $class->validates($column, @$validates);
279 }
280  
281 200 ▶ if(my $filters = delete($info->{filters})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filters = delete $info->{"filters"}) 0 200 200
282 0 debug 1, "Found filter info inside column '$column' definition";
283 0 $class->filters($column, @$filters);
284 }
285  
286 200 $class->next::method(@_);
287 }
288  
289 # Gotta jump thru these hoops because of the way the Catalyst
290 # DBIC model messes with the result namespace but not the schema
291 # namespace
292  
293 sub namespace {
294 32 ▶ my $self = shift;
Subroutine namespace: called CC=2 SCAR=6.9
Pod undocumented
295 32 ▶ my $class = ref($self) ? ref($self) : $self;
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 22 10 32
296 32 my ($ns) = ($class =~m/^(.+)::.+$/);
297 32 return $ns;
298 }
299  
300 # Trouble here is you can only inject one attribute per model. Will be an
301 # issue if you have more than one confirmation validation on the model. Should be an easy
302 # fix, we just need to track incoming attributes so 'new' knows how to init
303 # all of them
304  
305 sub inject_attribute {
306 4 ▶ my ($class, $attribute_to_inject) = @_;
Subroutine inject_attribute: called CC=2 SCAR=6.9
Pod undocumented
307 4 my $injection = "
308 package $class;
309  
310 __PACKAGE__->mk_group_accessors(simple => '$attribute_to_inject');
311  
312 sub new {
313 my (\$class, \$args) = \@_;
314 my \$val = delete \$args->{$attribute_to_inject};
315 my \$new = \$class->next::method(\$args);
316 \$new->$attribute_to_inject(\$val);
317 return \$new;
318 }
319 ";
320  
321 4 ▶ eval $injection;
Subroutine new: called CC=1 SCAR=0.0
Pod documented
322 4 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
323 }
324  
325 sub is_attribute_changed {
326 0 ▶ my ($self, $attr) = @_;
Subroutine is_attribute_changed: not called CC=1 SCAR=6.9
Pod undocumented
327 0 return $self->is_column_changed($attr);
328 }
329  
330 # We override here because we really want the uninflated values for the columns.
331 # Otherwise if we try to inflate first we can get an error since the value has not
332 # been validated and may not inflate. We see this very commonly on date type columns
333 # when the developer is using the DateTime inflation components.
334  
335 sub read_attribute_for_validation {
336 2812 ▶ my ($self, $attribute) = @_;
Subroutine read_attribute_for_validation: called CC=9 SCAR=22.3
Pod undocumented
337 2812 ▶ return unless defined $attribute;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $attribute 0 2812 2812
338 2812 ▶ return $self->get_column($attribute) if $self->result_source->has_column($attribute);
Branch: 1 branch
BranchTrueFalseTotal
if $self->result_source->has_column($attribute) 2059 753 2812
339  
340 753 ▶ if($self->has_relationship($attribute)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_relationship($attribute)) 566 187 753
341 566 my $rel_data = $self->relationship_info($attribute);
342 566 my $rel_type = $rel_data->{attrs}{accessor};
343 566 ▶ if($rel_type eq 'single') {
Branch: 2 branches
BranchTrueFalseTotal
if ($rel_type eq 'single') { } 368 198 566
elsif ($rel_type eq 'multi') { } 198 0 198
344 368 return $self->$attribute;
345 #return $self->related_resultset($attribute)->single;
346 } elsif($rel_type eq 'multi') {
347 198 return $self->related_resultset($attribute);
348 } else {
349 0 die "Cannot read_attribute_for_validation for '$attribute' of rel_type '$rel_type' in @{[ref $self]}";
350 }
351 }
352  
353 187 debug 1, "Failing back to accessor for 'read_attribute_for_validation' for object @{[ ref $self ]} attribute $attribute";
354 187 ▶ debug 2, "Failing back @{[ $self->can($attribute) ? 'succeeds':'failed' ]}";
Branch: 1 branch
BranchTrueFalseTotal
$self->can($attribute) ? : 93 94 187
355  
356 187 ▶ return $self->$attribute if $self->can($attribute);
Branch: 1 branch
BranchTrueFalseTotal
if $self->can($attribute) 93 94 187
357 94 my %columns = $self->get_columns;
358 94 ▶ return $columns{$attribute} if exists($columns{$attribute});
Branch: 1 branch
BranchTrueFalseTotal
if exists $columns{$attribute} 0 94 94
359 }
360  
361 sub read_attribute_for_html {
362 0 ▶ my ($self, $attribute) = @_;
Subroutine read_attribute_for_html: not called CC=3 SCAR=24.8
Pod undocumented
363  
364 0 ▶ return $self->is_marked_for_deletion if $attribute eq '_delete';
Branch: 1 branch
BranchTrueFalseTotal
if $attribute eq "_delete" 0 0 0
365 0 ▶ return 1 if $attribute eq '_add';
Branch: 1 branch
BranchTrueFalseTotal
if $attribute eq "_add" 0 0 0
366 0 return $self->read_attribute_for_validation($attribute);
367 }
368  
369 # Provide basic uniqueness checking for columns. This is basically a dumb DB lookup.
370 # Its probably fine for light work but you'll need something more performant when your
371 # table gets big.
372  
373 sub is_unique {
374 106 ▶ my ($self, $attribute_name, $value) = @_;
Subroutine is_unique: called CC=4 SCAR=13.9
Pod undocumented
375 # Don't do this check unless the user is actually trying to change the
376 # value (otherwise it will fail all the time).
377 106 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) 62 44 106
378 62 ▶ return 1 unless $self->is_column_changed($attribute_name);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_column_changed($attribute_name) 47 15 62
379 }
380 59 my $found = $self->result_source->resultset->single({$attribute_name=>$value});
381 59 ▶ return $found ? 0:1;
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 4 55 59
382 }
383  
384 sub mark_for_deletion {
385 14 ▶ my ($self) = @_;
Subroutine mark_for_deletion: called CC=2 SCAR=7.1
Pod undocumented
386 14 ▶ return unless $self->{__valiant_allow_destroy};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"__valiant_allow_destroy"} 0 14 14
387 14 $self->{__valiant_kiss_of_death} = 1;
388 }
389  
390 sub unmark_for_deletion {
391 0 ▶ my ($self) = @_;
Subroutine unmark_for_deletion: not called CC=1 SCAR=6.9
Pod undocumented
392 0 $self->{__valiant_kiss_of_death} = 0;
393 }
394  
395 sub is_marked_for_deletion {
396 415 ▶ my ($self) = @_;
Subroutine is_marked_for_deletion: called CC=2 SCAR=6.9
Pod documented
397 415 ▶ return $self->{__valiant_kiss_of_death} ? 1:0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'__valiant_kiss_of_death'} ? : 63 352 415
398 }
399  
400 sub delete_if_in_storage {
401 7 ▶ my ($self) = @_;
Subroutine delete_if_in_storage: called CC=2 SCAR=7.2
Pod undocumented
402 7 ▶ $self->delete if $self->in_storage; #TODO some sort of relationship handling...
Branch: 1 branch
BranchTrueFalseTotal
if $self->in_storage 7 0 7
403 }
404  
405 ####
406  
407 sub build_related {
408 0 ▶ my ($self, $related, $attrs) = @_;
Subroutine build_related: not called CC=6 SCAR=37.4
Pod documented
409 0 debug 2, "Building related entity '$related' for @{[ ref $self ]}";
410  
411 0 ▶ my $related_obj = $attrs ? $self->find_or_new_related($related, $attrs) : $self->new_related($related, +{});
Branch: 1 branch
BranchTrueFalseTotal
$attrs ? : 0 0 0
412 0 ▶ return if $related_obj->in_storage; #I think we can skip if its found
Branch: 1 branch
BranchTrueFalseTotal
if $related_obj->in_storage 0 0 0
413  
414 # TODO do this dance need to go into other places???
415 # TODO do I need some set_from_related or something here to get everthing into _relationship_data ???
416 0 my $relinfo = $self->relationship_info($related);
417 0 ▶ if ($relinfo->{attrs}{accessor} eq 'single') {
Branch: 2 branches
BranchTrueFalseTotal
if ($relinfo->{'attrs'}{'accessor'} eq 'single') { } 0 0 0
elsif ($relinfo->{'attrs'}{'accessor'} eq 'filter') { } 0 0 0
418 0 $self->{_relationship_data}{$related} = $related_obj;
419 }
420 elsif ($relinfo->{attrs}{accessor} eq 'filter') {
421 0 $self->{_inflated_column}{$related} = $related_obj;
422 }
423  
424 0 ▶ my @current_cache = @{ $self->related_resultset($related)->get_cache ||[] };
Branch: 1 branch
BranchTrueFalseTotal
$self->related_resultset($related)->get_cache or [] 0 0 0
425 0 $self->related_resultset($related)->set_cache([@current_cache, $related_obj]);
426  
427 0 return $related_obj;
428 }
429  
430 sub build_related_if_empty {
431 0 ▶ my ($self, $related, $attrs) = @_;
Subroutine build_related_if_empty: not called CC=9 SCAR=45.0
Pod documented
432 0 debug 2, "Build related entity '$related' for @{[ ref $self ]} if empty";
433  
434 0 my $rel_data = $self->relationship_info($related);
435 0 ▶ unless($rel_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rel_data) 0 0 0
436 0 ▶ if(my $rel_data = $self->_m2m_metadata->{$related}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rel_data = $self->_m2m_metadata->{$related}) 0 0 0
437 0 my $relation = $rel_data->{relation};
438 0 my $foreign_relation = $rel_data->{foreign_relation};
439  
440 0 ▶ return if @{ $self->related_resultset($relation)->get_cache ||[] };
Branch: 2 branches
BranchTrueFalseTotal
if @{$self->related_resultset($relation)->get_cache or [];} 0 0 0
$self->related_resultset($relation)->get_cache or [] 0 0 0
441 0 my $obj = $self->build_related_if_empty($relation, $attrs);
442 0 ▶ return if @{ $obj->related_resultset($foreign_relation)->get_cache ||[] };
Branch: 2 branches
BranchTrueFalseTotal
if @{$obj->related_resultset($foreign_relation)->get_cache or [];} 0 0 0
$obj->related_resultset($foreign_relation)->get_cache or [] 0 0 0
443 0 return $obj->build_related_if_empty($foreign_relation);
444 }
445 }
446  
447 0 ▶ return if @{ $self->related_resultset($related)->get_cache ||[] };
Branch: 2 branches
BranchTrueFalseTotal
if @{$self->related_resultset($related)->get_cache or [];} 0 0 0
$self->related_resultset($related)->get_cache or [] 0 0 0
448 0 return $self->build_related($related, $attrs);
449 }
450  
451 # When this param is an array we only use the last value, this is to support
452 # how checkboxes in HTML work (unchecked submits no value).
453 sub _param_is_delete {
454 0 ▶ my ($value_proto) = shift;
Subroutine _param_is_delete: not called CC=3 SCAR=24.8
455 0 ▶ my $value = ref($value_proto) ? $value_proto->[-1] : $value_proto;
Branch: 1 branch
BranchTrueFalseTotal
ref $value_proto ? : 0 0 0
456 0 ▶ return $value ? 1:0;
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 0 0 0
457 }
458  
459 sub set_columns_recursively {
460 1 ▶ my ($self, $params) = @_;
Subroutine set_columns_recursively: called CC=1 SCAR=0.0
Pod undocumented
461 1 $self->set_from_params_recursively(%$params);
462 1 return $self;
463 }
464  
465 sub set_from_params_recursively {
466 129 ▶ my ($self, %params) = @_;
Subroutine set_from_params_recursively: called CC=22 SCAR=55.0
Pod undocumented
467 129 debug 2, "Starting 'set_from_params_recursively' for @{[ ref $self ]}";
468 129 foreach my $param (keys %params) { # probably needs to be sorted so we get specials (_destroy) first
469 197 debug 3, "Starting param $param";
470 # Spot to normalize serialized params (like for dates, etc).
471 197 ▶ if($self->has_column($param)) {
Branch: 7 branches
BranchTrueFalseTotal
if ($self->has_column($param)) { } 165 32 197
elsif ($self->has_relationship($param)) { } 32 0 32
elsif ($self->can($param)) { } 0 0 0
elsif ($param eq '_delete') { } 0 0 0
elsif ($param eq '_nop') { } 0 0 0
elsif ($param eq '_restore' and $params{$param}) { } 0 0 0
elsif ($param eq '_action') { } 0 0 0
472 165 $self->set_column($param => $params{$param});
473 } elsif($self->has_relationship($param)) {
474 32 my %nested = $self->result_class->accept_nested_for;
475 32 ▶ if(my $cb = $nested{$param}->{reject_if}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $nested{$param}{"reject_if"}) 5 27 32
476 5 ▶ next if $cb->($self, $params{$param});
Branch: 1 branch
BranchTrueFalseTotal
if &$cb($self, $params{$param}) 1 4 5
477 }
478 31 debug 3, "set_related_from_params for @{[ ref $self ]}, related $param";
479 31 $self->set_related_from_params($param, $params{$param});
480 } elsif($self->can($param)) {
481 # Right now this is only used by confirmation stuff
482 0 $self->$param($params{$param});
483 } elsif( $param eq '_delete') {
484 0 ▶ if( _param_is_delete($params{$param}) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_param_is_delete($params{$param})) 0 0 0
485 0 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 0 0 0
486 0 debug 2, "Marking record @{[ ref $self ]}, id @{[ $self->id ]} for deletion";
487 0 $self->mark_for_deletion;
488 } else {
489 0 ▶ debug 2, "Marking unsaved record @{[ ref $self ]}, id @{[ $self->id||'NA' ]} for deletion (wil be NOP)";
Condition0%0/2
$self->id || 'NA'
l!l
00
MC/DC0%0/1
$self->id || 'NA'
$self->id
Truth table0%0/2
A
A= $self->id
Aresult
11
00
490 0 $self->mark_for_deletion;
491 }
492 }
493 } elsif( $param eq '_nop') {
494 0 ▶ if($params{$param}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params{$param}) 0 0 0
495 0 debug 3, "Found _nop";
496 0 delete $params{$param};
497 0 $self->mark_for_deletion;
498 }
499 ▶ } elsif($param eq '_restore' && $params{$param}) {
Condition0%0/3
$param eq "_restore" and $params{$param}
!ll&&!rl&&r
000
MC/DC0%0/2
$param eq "_restore" and $params{$param}
$param eq "_restore" $params{$param}
Truth table0%0/3
A and B
A= $param eq "_restore"B= $params{$param}
ABresult
0X0
100
111
500 0 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 0 0 0
501 0 debug 3, "Unmarking record @{[ ref $self ]}, id @{[ $self->id ]} for deletion";
502 0 $self->unmark_for_deletion;
503 0 delete $params{_delete};
504 } else {
505 0 die "didn't deal with restore on unsaved records";
506 }
507 } elsif($param eq '_action') {
508 0 my $action = $params{$param};
509 0 ▶ $action = ref($action)||'' ? $action->[-1] : $action; # If action is a ref always use the last one
Branch: 1 branch
BranchTrueFalseTotal
ref $action || '' ? : 0 0 0
Condition0%0/2
ref $action or ""
l!l
00
MC/DC0%0/1
ref $action or ""
ref $action
Truth table0%0/2
A
A= ref $action
Aresult
11
00
510 0 debug 3, "Found _action param with value $action";
511 0 ▶ if($action eq 'delete') {
Branch: 2 branches
BranchTrueFalseTotal
if ($action eq 'delete') { } 0 0 0
elsif ($action eq 'nop') { } 0 0 0
512 0 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 0 0 0
513 0 debug 2, "Marking record @{[ ref $self ]}, id @{[ $self->id ]} for deletion";
514 0 $self->mark_for_deletion;
515 } else {
516 0 die "didn't deal with action 'delete' on unsaved records";
517 }
518 } elsif($action eq 'nop') {
519 # Just skip, this is just a no op to deal with checkboxes and radio controls in HTML
520 } else {
521 0 die "Not sure what action '$action' is";
522 }
523 } else {
524 0 die "Not sure what to do with '$param'";
525 }
526 }
527 }
528  
529 sub set_related_from_params {
530 115 ▶ my ($self, $related, $params) = @_;
Subroutine set_related_from_params: called CC=5 SCAR=16.2
Pod undocumented
531  
532 115 my $rel_data = $self->relationship_info($related);
533 115 ▶ unless($rel_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rel_data) 7 108 115
534 7 ▶ if(my $rel_data = $self->_m2m_metadata->{$related}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rel_data = $self->_m2m_metadata->{$related}) 7 0 7
535 7 debug 2, "Setting params for $related on @{[ ref $self ]} using rel_type m2m";
536 7 return $self->set_m2m_related_from_params($related, $params, $rel_data);
537 }
538 }
539  
540 108 my $rel_type = $rel_data->{attrs}{accessor};
541 108 debug 2, "Setting params for $related on @{[ ref $self ]} using rel_type $rel_type";
542 108 ▶ return $self->set_single_related_from_params($related, $params) if $rel_type eq 'single';
Branch: 1 branch
BranchTrueFalseTotal
if $rel_type eq "single" 80 28 108
543 28 ▶ return $self->set_multi_related_from_params($related, $params) if $rel_type eq 'multi';
Branch: 1 branch
BranchTrueFalseTotal
if $rel_type eq "multi" 28 0 28
544  
545 0 die "Unhandled relationship type: $rel_type";
546 }
547  
548 # m2m is tricky
549 sub set_m2m_related_from_params {
550 7 ▶ my ($self, $related, $params, $rel_data) = @_;
Subroutine set_m2m_related_from_params: called CC=5 SCAR=19.6
Pod undocumented
551 7 my $relation = $rel_data->{relation};
552 7 my $foreign_relation = $rel_data->{foreign_relation};
553  
554 # We do this to allow for both multi create/update via an array (typical DBIC
555 # usage or via a hash of ordered keys (typical via CGI/Web).
556 7 my @param_rows = ();
557 7 ▶ if(ref($params) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $params eq 'HASH') { } 0 7 7
elsif (ref $params eq 'ARRAY') { } 7 0 7
558 0 ▶ @param_rows = map { $params->{$_} } sort { $a <=> $b} keys %{$params || +{}};
Branch: 1 branch
BranchTrueFalseTotal
$params or {} 0 0 0
559 } elsif(ref($params) eq 'ARRAY') {
560 7 ▶ @param_rows = @{$params || []};
Branch: 1 branch
BranchTrueFalseTotal
$params or [] 0 7 7
561 } else {
562 # I think if we are here its because the nests set is
563 # empty and we can ignore it for now but... not 100% sure :)
564 0 next;
565 0 die "We expect '$params' to be some sort of reference but its not!";
566 }
567 7 debug 2, "Setting m2m relation '$related' for @{[ ref $self ]} via '$relation' => '$foreign_relation'";
568  
569 # TODO its possible we need to creeate the m2m cache here
570 # TODO We need to add PK columens to the @params_rows if we have them
571  
572 #use Devel::Dwarn;
573 #Dwarn $self->result_source->_resolve_relationship_condition (
574 # infer_values_based_on => +{},
575 # rel_name => $relation,
576 # self_result_object => $self,
577 # foreign_alias => $relation,
578 # self_alias => 'me',
579 #)->{inferred_values};
580
581 7 return $self->set_multi_related_from_params($relation, [ map { +{ $foreign_relation => $_ } } @param_rows ]);
582 }
583  
584 ## TODO
585 sub is_pruned {
586 2 ▶ return shift->{__valiant_is_pruned} ? 1:0;
Subroutine is_pruned: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
+(shift())->{'__valiant_is_pruned'} ? : 2 0 2
587 }
588  
589 sub is_removed {
590 119 ▶ return (($_[0]->{__valiant_is_pruned} || $_[0]->{__valiant_kiss_of_death}) ? 1:0);
Subroutine is_removed: called CC=3 SCAR=11.1
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'__valiant_is_pruned'} || $_[0]{'__valiant_kiss_of_death'} ? : 28 91 119
Condition66%2/3
$_[0]{"__valiant_is_pruned"} or $_[0]{"__valiant_kiss_of_death"}
l!l&&r!l&&!r
28091
MC/DC50%1/2
$_[0]{"__valiant_is_pruned"} or $_[0]{"__valiant_kiss_of_death"}
$_[0]{"__valiant_is_pruned"} $_[0]{"__valiant_kiss_of_death"}
Truth table66%2/3
A or B
A= $_[0]{"__valiant_is_pruned"}B= $_[0]{"__valiant_kiss_of_death"}
ABresult
1X1
011
000
591 }
592  
593 sub set_multi_related_from_params {
594 35 ▶ my ($self, $related, $params) = @_;
Subroutine set_multi_related_from_params: called CC=51 SCAR=40.8
Pod undocumented
595  
596 # We do this to allow for both multi create/update via an array (typical DBIC
597 # usage or via a hash of ordered keys (typical via CGI/Web).
598 35 my @param_rows = ();
599 35 ▶ if(ref($params) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $params eq 'HASH') { } 0 35 35
elsif (ref $params eq 'ARRAY') { } 35 0 35
600 0 ▶ @param_rows = map { $params->{$_} } sort { $a <=> $b} keys %{$params || +{}};
Branch: 1 branch
BranchTrueFalseTotal
$params or {} 0 0 0
601 } elsif(ref($params) eq 'ARRAY') {
602 35 ▶ @param_rows = @{$params || []};
Branch: 1 branch
BranchTrueFalseTotal
$params or [] 0 35 35
603 } else {
604 # I think if we are here its because the nests set is
605 # empty and we can ignore it for now but... not 100% sure :)
606 0 next;
607 0 die "We expect '$params' to be some sort of reference but its not!";
608 }
609  
610 35 my $allow_destroy = $self->_related_allow_destroy($related);
611  
612 # Queue up some meta data here just once. We get existing rows ans
613 # uniqiue key info (including PK info)
614 35 debug 2, "looking for $related cached or existing rows";
615 35 ▶ my @existing_rows = @{ $self->$related->get_cache||[] };
Branch: 1 branch
BranchTrueFalseTotal
$self->$related->get_cache or [] 20 15 35
616 35 ▶ unless(@existing_rows) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@existing_rows) 20 15 35
617 20 debug 3, "cache was empty so going to check DB"; ## TODO this is to support ->discard_changes but maybe not need
618 20 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 5 15 20
619 5 @existing_rows = $self->$related->all;
620 } else {
621 15 debug 3, "record not in storage, so no point in looking for related rows";
622 }
623 }
624 35 debug 2, "Found @{[ scalar @existing_rows ]} existing rows for $related";
625
626 35 debug 2, "looking for uniques for $related";
627 35 my @primary_columns = $self->$related->result_source->primary_columns;
628 35 my %uniques = $self->$related->result_source->unique_constraints;
629 35 my @search_sets = ('primary');
630 35 my %nested = $self->result_class->accept_nested_for;
631  
632 # Gather the list of fields which are single type rels
633 my @single_rels = grep {
634 35 my $rel_data = $self->$related->result_source->relationship_info($_);
635 54 ▶ ($rel_data && ($rel_data->{attrs}{accessor} eq 'single')) ? 1:0;
Branch: 1 branch
BranchTrueFalseTotal
$rel_data && $rel_data->{'attrs'}{'accessor'} eq 'single' ? : 54 0 54
Condition33%1/3
$rel_data and $rel_data->{"attrs"}{"accessor"} eq "single"
!ll&&!rl&&r
0054
MC/DC0%0/2
$rel_data and $rel_data->{"attrs"}{"accessor"} eq "single"
$rel_data $rel_data->{"attrs"}{"accessor"} eq "single"
Truth table33%1/3
A and B
A= $rel_dataB= $rel_data->{"attrs"}{"accessor"} eq "single"
ABresult
0X0
100
111
636 } $self->$related->result_source->relationships;
637  
638 # Generally we alow finding the row via the PK only but the user can allow finding
639 # by any unique if that's what they really want.
640 35 ▶ if($nested{$related}{find_with_uniques}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nested{$related}{"find_with_uniques"}) 19 16 35
641 19 push @search_sets, grep { $_ ne 'primary' } keys %uniques;
642 }
643  
644 # Ok now build up the new rows
645 35 my @related_models = ();
646 35 debug 2, "starting loop to update/create related $related (total @{[ scalar @param_rows ]} rows in loop)";
647 35 foreach my $param_row (@param_rows) {
648 58 debug 3, "top of new loop on param_rows";
649 58 ▶ if($param_row->{_nop}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($param_row->{"_nop"}) 0 58 58
650 0 debug 3, "Is a NOP row, so skipping";
651 0 next;
652 }
653  
654 # Ok so if $self is in storage we expect any $related FKs to match whatever is $self $PK. If that
655 # FK is empty we add it. If its there but has an unexpected value, that's an error (and probably
656 # a hacking attempt
657 58 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 20 38 58
658 20 my %cond = %{$self->result_source->relationship_info($related)->{cond}};
659 20 foreach my $fk_proto (keys %cond) {
660 20 my $pk_proto = $cond{$fk_proto};
661 20 my ($pk) = ($pk_proto=~m/^self\.(.+)$/);
662 20 my ($fk) = ($fk_proto=~m/^foreign\.(.+)$/);
663  
664 20 ▶ if(exists $param_row->{$fk}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $param_row->{$fk}) { } 1 19 20
665 1 ▶ unless($param_row->{$fk} eq $self->get_column($pk)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($param_row->{$fk} eq $self->get_column($pk)) 1 0 1
666 DBIx::Class::Valiant::Util::Exception::BadParameterFK->throw(
667 1 fk_field=>$fk, fk_value=>$param_row->{$fk},
668 pk_field=>$pk, pk_value=>$self->get_column($pk),
669 related=>$related, me=>$self);
670 }
671 } else {
672 19 $param_row->{$fk} = $self->get_column($pk); # set it since that should help with the lookups
673 }
674 }
675 } else {
676 # Now if $self is not in storage we expect the related FK to be empty. If not throw error since
677 # its possible a hacking attempt
678 38 my %cond = %{$self->result_source->relationship_info($related)->{cond}};
679 38 foreach my $fk_proto (keys %cond) {
680 38 my $pk_proto = $cond{$fk_proto};
681 38 my ($pk) = ($pk_proto=~m/^self\.(.+)$/);
682 38 my ($fk) = ($fk_proto=~m/^foreign\.(.+)$/);
683  
684 38 ▶ if(exists $param_row->{$fk}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $param_row->{$fk}) 1 37 38
685 1 ▶ unless(!defined($param_row->{$fk})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $param_row->{$fk}) 1 0 1
686 DBIx::Class::Valiant::Util::Exception::BadParameterFK->throw(
687 1 fk_field=>$fk, fk_value=>$param_row->{$fk},
688 pk_field=>$pk, pk_value=>'undef',
689 related=>$related, me=>$self);
690 }
691 }
692 }
693 }
694  
695 56 my $was_add = delete $param_row->{_add};
696 56 my $related_model;
697 56 ▶ if(blessed $param_row) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($param_row)) { } 4 52 56
elsif ((ref $param_row || '') eq 'HASH') { } 52 0 52
698 4 debug 1, "params are an object";
699 4 $related_model = $param_row;
700 ▶ } elsif( (ref($param_row)||'') eq 'HASH') {
Condition50%1/2
ref $param_row || ''
l!l
520
MC/DC0%0/1
ref $param_row || ''
ref $param_row
Truth table50%1/2
A
A= ref $param_row
Aresult
11
00
701  
702 # The first thing to do is to see if we can find a row either in the existing cache
703 # or in the DB, matched on the Primary key and (if enabled) unique keys.
704 52 my %keys_used_to_find = ();
705 52 SEARCH_UNIQUE_KEYS: foreach my $key (@search_sets) {
706 52 debug 2, "trying to find a row for $related using key $key";
707  
708 52 my @key_columns = @{$uniques{$key}};
709 52 my %matching = map { $_ => $param_row->{$_} } grep { exists $param_row->{$_} } @key_columns;
710  
711  
712 52 ▶ next unless scalar(@key_columns) == scalar(keys(%matching)); # only match when its a full key match
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @key_columns == scalar keys %matching 49 3 52
713 3 debug 2, "key $key exists in params";
714  
715 # Find matching if they exist in the cache
716 3 foreach my $row (@existing_rows) {
717 4 my %unique_fields = map { $_ => $row->get_column($_) } @key_columns;
718 4 my $a = join "", map { $_, $unique_fields{$_} } sort keys(%unique_fields);
719 4 my $b = join "", map { $_, $matching{$_} } sort keys(%matching);
720 4 ▶ if($a eq $b) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a eq $b) 2 2 4
721 2 $related_model = $row;
722 2 ▶ if($related_model) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_model) 2 0 2
723 2 debug 2, "found related model for $related with $key in cache";
724 2 %keys_used_to_find = (%keys_used_to_find, %matching);
725 last SEARCH_UNIQUE_KEYS
726 2 }
727 }
728 }
729  
730 # If it doesn't match in the cache then we have to find it in the DB. TODO I'm skipping this
731 # lookup for now since I don't think we need it unless the user failed to properly prefetch.
732 # Its pointless to do this unless $self is in storage anyway
733 1 ▶ unless($related_model) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_model) 1 0 1
734 1 debug 2, "Trying to find $related in DB with key $key (SKIPPING)";
735 #$related_model = $self->find_related($related, \%matching, +{key=>$key}) if $self->in_storage;
736 1 ▶ if($related_model) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_model) 0 1 1
737 0 debug 2, "found related model for $related with $key in DB";
738 0 %keys_used_to_find = (%keys_used_to_find, %matching);
739 last SEARCH_UNIQUE_KEYS
740 0 }
741 }
742 }
743  
744 # If we get here its possible there's a single type relation we can use to complete
745 # the lookup. TODO: Not sure if this should be a param setting in the nested_for data
746 # (it probably should be). Also not sure if we should limit the ->find_related to
747 # just the FK rel.
748  
749 52 ▶ if(grep {$param_row->{$_}} @single_rels) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$param_row->{$_};} @single_rels) 17 35 52
750 17 debug 2, "Falling back to default find_related for $related using full param_row";
751 17 ▶ $related_model = $self->find_related($related, $param_row) unless $related_model || !%{$param_row};
Branch: 1 branch
BranchTrueFalseTotal
unless $related_model or not %{$param_row;} 17 0 17
Condition33%1/3
$related_model or not %{$param_row;}
l!l&&r!l&&!r
0017
MC/DC0%0/2
$related_model or not %{$param_row;}
$related_model not %{$param_row;}
Truth table33%1/3
A or not(B)
A= $related_modelB= not %{$param_row;}
ABresult
1X1
011
000
752 }
753  
754 # OK so we didnt find it via keys either in the cache or in the DB so that means
755 # we need to just create it.
756 52 ▶ unless($related_model) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_model) 50 2 52
757 50 debug 2, "Didn't find related model '$related' so making it";
758 50 $related_model = $self->new_related($related, +{});
759 }
760 52 debug 2, "About to set_from_params_recursively for @{[ ref $related_model ]}";
761  
762 52 ▶ if($was_add) {
Branch: 1 branch
BranchTrueFalseTotal
if ($was_add) 0 52 52
763 0 debug 3, "Since @{[ ref $related_model]} was an _add we won't validate since its empty";
764 #$related_model->errors->add(undef, 'newwww');
765 #$related_model->skip_validate; Need to leave this off for now because doesn't play well with new models
766 0 $related_model->{__valiant_donot_insert} = 1;
767 }
768  
769 52 ▶ if($allow_destroy) {
Branch: 1 branch
BranchTrueFalseTotal
if ($allow_destroy) 28 24 52
770 28 $related_model->{__valiant_allow_destroy} = 1;
771 }
772
773 # Don't set params for the found keys (waste of time, no change)
774 52 my %params_for_recursive = %$param_row;
775 52 ▶ delete @params_for_recursive{ keys %keys_used_to_find} if %keys_used_to_find;
Branch: 1 branch
BranchTrueFalseTotal
if %keys_used_to_find 2 50 52
776 52 $related_model->set_from_params_recursively(%params_for_recursive);
777  
778 # Ok, so after set_from_params_recursively if the $related_model is not in storage
779 # we 'might' have enough info to actually load it now.
780 52 ▶ if(!$related_model->in_storage && !$related_model->is_marked_for_deletion) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_model->in_storage or $related_model->is_marked_for_deletion) 50 2 52
Condition66%2/3
$related_model->in_storage or $related_model->is_marked_for_deletion
l!l&&r!l&&!r
2050
MC/DC50%1/2
$related_model->in_storage or $related_model->is_marked_for_deletion
$related_model->in_storage $related_model->is_marked_for_deletion
Truth table66%2/3
A or B
A= $related_model->in_storageB= $related_model->is_marked_for_deletion
ABresult
1X1
011
000
781 # TODO: We should skip this if we've already tried a full PK
782 50 ▶ my %ident = %{ $related_model->_storage_ident_condition ||+{} };
Branch: 1 branch
BranchTrueFalseTotal
$related_model->_storage_ident_condition or {} 0 50 50
783 50 my $fully_id = 1;
784 50 foreach my $ident(keys %ident) {
785 71 ▶ next if defined($related_model->get_column($ident)); # can't try to load from DB if the PK isn't fully found
Branch: 1 branch
BranchTrueFalseTotal
if defined $related_model->get_column($ident) 28 43 71
786 43 $fully_id = 0;
787 }
788 50 ▶ if($fully_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fully_id) 8 42 50
789 8 my $copy = $related_model->get_from_storage(); # If we now have the full PK we can find it
790 8 ▶ $related_model = $copy if $copy;
Branch: 1 branch
BranchTrueFalseTotal
if $copy 1 7 8
791 }
792 }
793 } else {
794 0 die "Not sure what to do with $param_row";
795 }
796 56 push @related_models, $related_model;
797 }
798  
799 # This bit we diff between the rows loaded in the orignal cache and what it looks
800 # like after the multi update. Rows that are no longer present are marked for
801 # deletion if deletion is allowed
802 my @new_pks = map {
803 4 my $r = $_;
804 +{
805 4 map { $_ => $r->$_ } $r->result_source->primary_columns
806 }
807 33 } grep { $_->in_storage } @related_models;
808  
809 33 debug 1, "Reviewing existing rows for relation $related (total @{[ scalar @existing_rows ]}) for deletion";
810
811 33 foreach my $current (@existing_rows) {
812 next if grep {
813 32 ▶ my %fields = %$_;
Branch: 1 branch
BranchTrueFalseTotal
if grep {my(%fields) = %$_; my(@matches) = grep({$current->get_column($_) eq $fields{$_};} keys %fields); scalar @matches == keys %fields ? 1 : 0;} @new_pks 3 29 32
814 my @matches = grep {
815 5 $current->get_column($_) eq $fields{$_}
816 } keys %fields;
817 5 ▶ scalar(@matches) == keys %fields ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar @matches == keys %fields ? : 3 2 5
818 } @new_pks;
819  
820 29 debug 2, "ok its not a new one";
821  
822 # Only mark for deletion if its actually in store.
823 29 ▶ if($current->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current->in_storage) 14 15 29
824 14 debug 2, "Marking $current for deletion";
825 14 ▶ $current->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 14 0 14
826 14 $current->mark_for_deletion; # might be a good idea to find a way to expose this via an override-able method
827  
828 # Mark its children as pruned, recursively
829 14 my $cb; $cb = sub {
830 24 ▶ my $row = shift;
Subroutine __ANON__: called CC=6 SCAR=17.9
831 24 ▶ debug 3, "marking $row to be pruned" unless $row->is_marked_for_deletion;
Branch: 1 branch
BranchTrueFalseTotal
unless $row->is_marked_for_deletion 10 14 24
832 24 $row->{__valiant_is_pruned} = 1; # unless $row->is_marked_for_deletion;
833 24 ▶ my @related = keys %{$row->{_relationship_data}||+{}};
Branch: 1 branch
BranchTrueFalseTotal
$row->{"_relationship_data"} or {} 13 11 24
834 # TODO only do this for has_one, might_have, has_many
835 24 debug 3, "$row has related data to prune @{[ join ',', @related ]}";
836 24 foreach $related(@related) {
837 11 debug 3, "checking $related for possible pruning";
838 11 ▶ my @rows = @{$row->related_resultset($related)->get_cache||[]};
Branch: 1 branch
BranchTrueFalseTotal
$row->related_resultset($related)->get_cache or [] 1 10 11
839 11 debug 3, "found @{[ scalar @rows ]} to be pruned";
840 11 foreach my $inner_row (@rows) {
841 10 $cb->($inner_row);
842 }
843 }
844 14 };
845 14 ▶ $cb->($current) if $current->is_marked_for_deletion; # We check because 'mark_for_deletion' will skip unless 'allow_destroy' is set
Branch: 1 branch
BranchTrueFalseTotal
if $current->is_marked_for_deletion 14 0 14
846 }
847  
848 29 ▶ if ($current->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current->in_storage) { } 14 15 29
849 14 debug 3, "Current model is in storage so put it into cache";
850 14 push @related_models, $current;
851 } else {
852 15 debug 3, "Current model is not in storage so don't bother to cache it since its marked for delete anyway";
853 }
854 }
855  
856 33 debug 3, "About to save cache for @{[ ref $self ]} related resultset $related; has @{[ scalar @related_models ]} models to cache";
857  
858 33 $self->related_resultset($related)->set_cache(\@related_models);
859 33 $self->{_relationship_data}{$related} = \@related_models;
860 33 $self->{__valiant_related_resultset}{$related} = \@related_models; # we have a private copy
861 }
862  
863 sub set_single_related_from_params {
864 80 ▶ my ($self, $related, $params) = @_;
Subroutine set_single_related_from_params: called CC=37 SCAR=36.4
Pod undocumented
865 80 my %nested = $self->result_class->accept_nested_for;
866 80 my $allow_destroy = $nested{allow_destroy};
867  
868 # Is there an existing related object in the cache? If so then we
869 # will merge params with existing rather than create a new one or
870 # run a new query to find one. I 'think' that's the most expected behavior...
871 80 ▶ my ($related_result) = @{ $self->related_resultset($related)->get_cache ||[] }; # its single so only one
Branch: 1 branch
BranchTrueFalseTotal
$self->related_resultset($related)->get_cache or [] 70 10 80
872 80 ▶ $related_result = $self->{_relationship_data}{$related} unless $related_result;
Branch: 1 branch
BranchTrueFalseTotal
unless $related_result 70 10 80
873  
874 80 ▶ if($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_result) { } 17 63 80
875 ## TODO I might need to do something else if $params is blessed
876 ## TODO I think we need the below logic to see if $params has a PK and then use
877 ## that as an override.
878 #
879 ## TODO this is probably wrong if $params has different FKs or unique fields
880  
881 17 debug 2, "Found cached related_result $related for @{[ ref $self ]} ";
882 17 ▶ $related_result->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 0 17 17
883 17 $related_result->set_from_params_recursively(%$params);
884 } else {
885 63 debug 2, "No cached related_result $related for @{[ ref $self ]} ";
886 63 ▶ if(blessed($params)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($params)) { } 2 61 63
887 2 debug 2, "related_result $related for @{[ ref $self ]} is blessed object";
888 2 $related_result = $params;
889 } else {
890 61 debug 2, "related_result $related for @{[ ref $self ]} is hashed params";
891  
892 # When doing an update on single rels (has_one/belongs_to) you need to figure out
893 # if you are recursing an update into that exist rel or if you are replacing that
894 # rel with a new one (find_or_new).
895  
896 61 ▶ if($self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->in_storage) { } 13 48 61
897 13 my %local_params = %$params;
898 13 my %cond = %{$self->result_source->relationship_info($related)->{cond}};
899 13 my @pks = $self->result_source->primary_columns;
900 13 foreach my $fk_proto (keys %cond) {
901 13 my $pk_proto = $cond{$fk_proto};
902 13 my ($pk) = ($pk_proto=~m/^self\.(.+)$/);
903 13 my ($fk) = ($fk_proto=~m/^foreign\.(.+)$/);
904 13 ▶ next unless grep { $_ eq $pk } @pks;;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $pk;} @pks 3 10 13
905  
906 10 ▶ if(exists $local_params{$fk}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $local_params{$fk}) { } 1 9 10
907 1 ▶ unless($local_params{$fk} eq $self->get_column($pk)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($local_params{$fk} eq $self->get_column($pk)) 1 0 1
908 DBIx::Class::Valiant::Util::Exception::BadParameterFK->throw(
909 1 fk_field=>$fk, fk_value=>$local_params{$fk},
910 pk_field=>$pk, pk_value=>$self->get_column($pk),
911 related=>$related, me=>$self);
912 }
913 } else {
914 #$local_params{$fk} = $self->get_column($pk); # set it since that should help with the lookups
915 }
916 }
917  
918 12 debug 2, "Updating related result '$related' for @{[ ref $self ]} ";
919 1 my %pk = map { $_ => delete $local_params{$_} }
920 12 grep { exists $local_params{$_} }
921 $self->related_resultset($related)->result_source->primary_columns;
922  
923 # If the user supplied the PK that means use that exact record and replace the current one
924 # also apply any updates to that record as indicated.
925 12 ▶ if(%pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (%pk) { } 1 11 12
926 1 debug 3, "Updating with exact record matching pk";
927  
928 1 $related_result = $self->result_source->related_source($related)->resultset->find($params); ## TODO shouldnt this be \%pk??
929 1 $related_result = $self->result_source->related_source($related)->resultset->find(\%pk); ## TODO shouldnt this be \%pk??
930  
931 1 $self->set_from_related($related, $related_result);
932  
933 #my $rev_data = $self->result_source->reverse_relationship_info($related);
934 #my ($reverse_related) = keys %$rev_data;
935 #$related_result->set_from_related($reverse_related, $self) if $reverse_related; # Don't have this for might_have
936 1 ▶ $related_result->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 0 1 1
937 1 $related_result->set_from_params_recursively(%$params);
938 } else {
939 11 debug 3, "Updating with record from params (no matching PK)";
940  
941 # If the user did not give us a PK either;
942 # 1) if undate_only=>1 then update the current record (if existing; create otherwise)
943 # 2) otherwise create a new record off the parent.
944
945 11 ▶ if(+{$self->result_class->accept_nested_for}->{$related}{update_only}) {
Branch: 1 branch
BranchTrueFalseTotal
if ({$self->result_class->accept_nested_for}->{$related}{'update_only'}) { } 9 2 11
946 9 debug 3, 'update_only true';
947 9 $related_result = $self->related_resultset($related)->single;
948 9 ▶ unless($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_result) 2 7 9
949 #$related_result = $self->find_or_new_related($related, $params); # TODO should find from any unique keys on
950 # If one doesn't already exist that means 'make a new one'
951 2 $related_result = $self->new_related($related, $params);
952 }
953 } else {
954 2 debug 3, "update_only false for rel $related on @{[ $self]}";
955  
956 2 my %uniques = $self->related_resultset($related)->result_source->unique_constraints;
957 2 ▶ if(%uniques) {
Branch: 1 branch
BranchTrueFalseTotal
if (%uniques) 2 0 2
958 2 debug 4, "Have unique constraints to try to find on";
959 2 foreach my $unique_key (keys %uniques) {
960 5 ▶ next if $unique_key eq 'primary'; # already done
Branch: 1 branch
BranchTrueFalseTotal
if $unique_key eq "primary" 1 4 5
961 4 debug 4, "checking key $unique_key for related $related";
962 4 my %keys_found = map { $_=>$params->{$_} } grep { exists $params->{$_} } @{$uniques{$unique_key}};
963 #$related_result = $self->find_related($related, \%keys_found);
964 4 ▶ next unless %keys_found;
Branch: 1 branch
BranchTrueFalseTotal
unless %keys_found 2 2 4
965 2 $related_result = $self->result_source->related_source($related)->resultset->find(\%keys_found);
966 2 ▶ if($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_result) 1 1 2
967 1 debug 4, "found result with unique key $unique_key";
968 1 last;
969 }
970 }
971 }
972
973 #$related_result = $self->result_source->related_source($related)->resultset->find($params); # TODO problably shoulld search on unique keys only
974 2 ▶ unless($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_result) 1 1 2
975 1 debug 3, "Did not find result for $related so creating new result";
976 # $self is in storage so it 'shou;d be safe to do this;
977 1 $related_result = $self->new_related($related, $params);
978 #$related_result = $self->result_source->related_source($related)->resultset->new_result($params);
979 }
980  
981 2 $self->set_from_related($related, $related_result);
982 #my $rev_data = $self->result_source->reverse_relationship_info($related);
983 # my ($key) = keys(%$rev_data);
984 #$related_result->set_from_related($key, $self) if $key; # Don't have this for might_hav
985 }
986 11 ▶ $related_result->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 0 11 11
987 11 $related_result->set_from_params_recursively(%$params);
988 }
989 } else {
990 48 debug 2, "Find or new related result '$related' for @{[ ref $self ]} which is not saved yet";
991 # Ok so the object isn't in storage, which means you don't have an database supplied PKs. So
992 # can't do related_resultset since that always returns nothing (if $self doesn't exist in the DB
993 # there's nothing in the DB to find.
994 #$related_result = $self->find_or_new_related($related, $params);
995 #$related_result->set_from_params_recursively(%$params);
996 48 my %local_params = %$params;
997  
998 48 my %cond = %{$self->result_source->relationship_info($related)->{cond}};
999 48 my @pks = $self->result_source->primary_columns;
1000  
1001 48 my $flag = 0;
1002 48 foreach my $fk_proto (keys %cond) {
1003 48 my $pk_proto = $cond{$fk_proto};
1004 48 my ($pk) = ($pk_proto=~m/^self\.(.+)$/);
1005 48 my ($fk) = ($fk_proto=~m/^foreign\.(.+)$/);
1006 48 ▶ next unless grep { $_ eq $pk } @pks;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $pk;} @pks 10 38 48
1007 38 ▶ next unless exists $local_params{$fk};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $local_params{$fk} 37 1 38
1008 1 ▶ $flag++ if defined($local_params{$fk});
Branch: 1 branch
BranchTrueFalseTotal
if defined $local_params{$fk} 1 0 1
1009 }
1010  
1011 48 ▶ if($flag == scalar(@pks)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flag == scalar @pks) 1 47 48
1012 1 DBIx::Class::Valiant::Util::Exception::BadParameters->throw(related=>$related, me=>$self);
1013 }
1014  
1015 0 my %pk = map { $_ => delete $local_params{$_} }
1016 47 grep { exists $local_params{$_} }
1017 $self->related_resultset($related)->result_source->primary_columns;
1018  
1019 # If the user supplied the PK that means use that exact record and replace the current one
1020 # also apply any updates to that record as indicated.
1021 47 ▶ if(%pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (%pk) { } 0 47 47
1022 0 debug 3, "setting with exact record matching pk %pk";
1023 0 $related_result = $self->result_source->related_source($related)->resultset->find(\%pk);
1024 # $self->set_from_related($related, $related_result);
1025 0 ▶ $related_result->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 0 0 0
1026 0 $related_result->set_from_params_recursively(%$params);
1027 } else {
1028 47 debug 3, "No PK for $related, lets see if there's other ways to find it";
1029 47 ▶ if($nested{$related}{find_with_uniques}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nested{$related}{"find_with_uniques"}) 17 30 47
1030 17 debug 3, "finding $related for $self with find_with_uniques matching";
1031 17 my %uniques = $self->result_source->related_source($related)->unique_constraints;
1032 17 foreach my $unique (keys %uniques) {
1033 31 ▶ next if $unique eq 'primary'; # already done
Branch: 1 branch
BranchTrueFalseTotal
if $unique eq "primary" 14 17 31
1034 17 my @key_columns = @{$uniques{$unique}};
1035 17 my %matching = map { $_ => $params->{$_} } grep { exists $params->{$_} } @key_columns;
1036  
1037 17 ▶ next unless scalar(@key_columns) == scalar(keys(%matching)); # only match when its a full key match
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @key_columns == scalar keys %matching 0 17 17
1038 17 debug 2, "key $unique exists in params";
1039 17 $related_result = $self->result_source->related_source($related)->resultset->find(\%matching);
1040 17 ▶ if($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_result) 12 5 17
1041 12 debug 3, "Found result via unique keys";
1042 12 last;
1043 }
1044 }
1045 }
1046  
1047 47 ▶ unless($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_result) 35 12 47
1048 35 debug 3, "Did not find result for $related so creating new result";
1049 35 $related_result = $self->new_related($related, $params);
1050 }
1051 47 ▶ $self->set_from_related($related, $related_result) unless $self->in_storage;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->in_storage 47 0 47
1052 47 ▶ $related_result->{__valiant_allow_destroy} = 1 if $allow_destroy;
Branch: 1 branch
BranchTrueFalseTotal
if $allow_destroy 0 47 47
1053 47 $related_result->set_from_params_recursively(%$params);
1054 }
1055 }
1056 }
1057 }
1058  
1059 78 $self->related_resultset($related)->set_cache([$related_result]);
1060 78 $self->{_relationship_data}{$related} = $related_result;
1061 78 $self->{__valiant_related_resultset}{$related} = [$related_result];
1062  
1063 # ok so... what about the reverse side of this rel? Seems this makes for infinite recursion
1064 #my $rev_data = $self->result_source->reverse_relationship_info($related);
1065 #my ($key) = keys(%$rev_data);
1066 #$related_result->{_relationship_data}{$key} = $self;
1067 }
1068  
1069 sub mutate_recursively {
1070 61 ▶ my ($self) = @_;
Subroutine mutate_recursively: called CC=4 SCAR=13.9
Pod undocumented
1071 61 debug 2, "mutating relationships for @{[ $self ]}";
1072  
1073 61 ▶ $self->_mutate if $self->is_changed || $self->is_marked_for_deletion;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_changed or $self->is_marked_for_deletion 31 30 61
Condition100%3/3
$self->is_changed or $self->is_marked_for_deletion
l!l&&r!l&&!r
24730
MC/DC100%2/2
$self->is_changed or $self->is_marked_for_deletion
$self->is_changed $self->is_marked_for_deletion
Truth table100%3/3
A or B
A= $self->is_changedB= $self->is_marked_for_deletion
ABresult
1X1
011
000
1074 61 foreach my $related (keys %{$self->{_relationship_data}}) {
1075 #next unless $self->related_resultset($related)->first; # TODO don't think I need this
1076 17 debug 2, "mutating relationship $related";
1077 17 $self->_mutate_related($related);
1078 }
1079 }
1080  
1081 sub _mutate {
1082 31 ▶ my ($self) = @_;
Subroutine _mutate: called CC=5 SCAR=16.1
1083 31 ▶ if($self->is_marked_for_deletion) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_marked_for_deletion) { } 7 24 31
1084 7 debug 2, "deleting @{[ ref $self ]} if in storage";
1085 7 $self->delete_if_in_storage;
1086 } else {
1087 24 debug 2, "update_or_insert for @{[ ref $self ]}";
1088  
1089 # Ok so when doing update we are losing the relationed info so brute forse
1090 # cache and restore it (probably wrong but passing tests for now....)
1091  
1092 24 ▶ my %rels = %{$self->{_relationship_data}||+{}};
Branch: 1 branch
BranchTrueFalseTotal
$self->{"_relationship_data"} or {} 9 15 24
1093 24 ▶ my %rels_rs = %{$self->{related_resultsets}||+{}};
Branch: 1 branch
BranchTrueFalseTotal
$self->{"related_resultsets"} or {} 10 14 24
1094  
1095 24 $self->update_or_insert;
1096  
1097 # copies but quite likely now incorrect even thos my tests pass.....
1098 # maybe I need a better way to restore this stuff.
1099 24 $self->{_relationship_data} = \%rels;
1100 24 ▶ $self->{related_resultsets} = \%rels_rs if %rels_rs;
Branch: 1 branch
BranchTrueFalseTotal
if %rels_rs 9 15 24
1101 }
1102 }
1103  
1104 sub _mutate_related {
1105 74 ▶ my ($self, $related) = @_;
Subroutine _mutate_related: called CC=5 SCAR=16.4
1106 74 my $rel_data = $self->relationship_info($related);
1107 74 ▶ unless($rel_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rel_data) 7 67 74
1108 7 ▶ if(my $rel_data = $self->_m2m_metadata->{$related}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rel_data = $self->_m2m_metadata->{$related}) 7 0 7
1109 7 return $self->_mutate_m2m_related($related, $rel_data);
1110 }
1111 }
1112
1113 67 my $rel_type = $rel_data->{attrs}{accessor};
1114  
1115 67 ▶ return $self->_mutate_single_related($related) if $rel_type eq 'single';
Branch: 1 branch
BranchTrueFalseTotal
if $rel_type eq "single" 54 13 67
1116 13 ▶ return $self->_mutate_multi_related($related) if $rel_type eq 'multi';
Branch: 1 branch
BranchTrueFalseTotal
if $rel_type eq "multi" 13 0 13
1117  
1118 0 die "not sure how to mutate $related of type $rel_type";
1119 }
1120  
1121 sub _mutate_m2m_related {
1122 7 ▶ my ($self, $related, $rel_data) = @_;
Subroutine _mutate_m2m_related: called CC=1 SCAR=0.0
1123 7 my $relation = $rel_data->{relation};
1124 7 my $foreign_relation = $rel_data->{foreign_relation};
1125  
1126 7 return $self->_mutate_multi_related($relation);
1127 }
1128  
1129 sub _mutate_multi_related {
1130 20 ▶ my ($self, $related) = @_;
Subroutine _mutate_multi_related: called CC=7 SCAR=19.5
1131 20 ▶ my @related_results = @{ $self->{__valiant_related_resultset}{$related} ||[] };
Branch: 1 branch
BranchTrueFalseTotal
$self->{"__valiant_related_resultset"}{$related} or [] 6 14 20
1132 20 my $rev_data = $self->result_source->reverse_relationship_info($related);
1133 20 my ($reverse_related) = keys %$rev_data;
1134  
1135 20 debug 2, "Trying to mutate multi relations '$related'";
1136  
1137 20 foreach my $related_result (@related_results) {
1138 21 ▶ next unless $related_result->is_changed || $related_result->is_marked_for_deletion || !$related_result->in_storage;
Branch: 1 branch
BranchTrueFalseTotal
unless $related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage 5 16 21
Condition83%5/6
$related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage
l!l&&r!l&&!r
1605
$related_result->is_changed or $related_result->is_marked_for_deletion
l!l&&r!l&&!r
975
MC/DC66%2/3
$related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage
$related_result->is_changed $related_result->is_marked_for_deletion not $related_result->in_storage
Truth table75%3/4
A or B or not(C)
A= $related_result->is_changedB= $related_result->is_marked_for_deletionC= not $related_result->in_storage
ABCresult
1XX1
01X1
0011
0000
1139 16 debug 3, "@{[ ref $related_result ]} ready for mutating";
1140 16 ▶ $related_result->set_from_related($reverse_related, $self) if $reverse_related; # Don't have this for might_have
Branch: 1 branch
BranchTrueFalseTotal
if $reverse_related 16 0 16
1141 16 $related_result->mutate_recursively;
1142 }
1143  
1144 # If the mutation completed we need to remove all marked for delation
1145 20 my @new_results = grep { !$_->is_marked_for_deletion } @related_results;
1146  
1147 20 $self->related_resultset($related)->set_cache(\@new_results);
1148 20 $self->{_relationship_data}{$related} = \@new_results;
1149 20 $self->{__valiant_related_resultset}{$related} = [@new_results];
1150  
1151 # TODO need to update rels
1152 }
1153  
1154  
1155 sub _mutate_single_related {
1156 54 ▶ my ($self, $related) = @_;
Subroutine _mutate_single_related: called CC=6 SCAR=17.9
1157 #my ($related_result) = @{ $self->{__valiant_related_resultset}{$related} ||[] };
1158 #my ($related_result) = @{ $self->related_resultset($related)->get_cache ||[] };
1159 54 my $related_result = $self->{_relationship_data}{$related};
1160 54 ▶ unless($related_result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($related_result) 9 45 54
1161 9 debug 2, "Skipping _mutate_single_related because related $related is not cached";
1162 9 return;
1163 }
1164  
1165 45 my $rev_data = $self->result_source->reverse_relationship_info($related);
1166 45 my ($reverse_related) = keys %$rev_data;
1167  
1168 45 debug 2, "Trying to mutate @{[ ref $related_result ]}";
1169 45 debug 3, "@{[ ref $related_result ]} is_changed: @{[ $related_result->is_changed]}";
1170 45 debug 3, "@{[ ref $related_result ]} is_marked_for_deletion: @{[ $related_result->is_marked_for_deletion]}";
1171 45 debug 3, "@{[ ref $related_result ]} in_storage: @{[ $related_result->in_storage]}";
1172  
1173 45 ▶ if($related_result->is_changed || $related_result->is_marked_for_deletion || !$related_result->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage) 0 30 30
Condition66%4/6
$related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage
l!l&&r!l&&!r
15030
$related_result->is_changed or $related_result->is_marked_for_deletion
l!l&&r!l&&!r
15030
MC/DC33%1/3
$related_result->is_changed or $related_result->is_marked_for_deletion or not $related_result->in_storage
$related_result->is_changed $related_result->is_marked_for_deletion not $related_result->in_storage
Truth table50%2/4
A or B or not(C)
A= $related_result->is_changedB= $related_result->is_marked_for_deletionC= not $related_result->in_storage
ABCresult
1XX1
01X1
0011
0000
1174 15 debug 3, "@{[ ref $related_result ]} ready for mutating";
1175 15 ▶ $related_result->set_from_related($reverse_related, $self) if $reverse_related; # Don't have this for might_have
Branch: 1 branch
BranchTrueFalseTotal
if $reverse_related 12 3 15
1176 15 $related_result->mutate_recursively;
1177  
1178 # I think if its in storage we need to set cache and all even if marked for deletation
1179 #my @new_cache = $related_result->is_marked_for_deletion ? () : ($related_result);
1180 15 $self->related_resultset($related)->set_cache([$related_result]);
1181 15 $self->{__valiant_related_resultset}{$related} = [$related_result];
1182 15 $self->{_relationship_data}{$related} = $related_result;
1183 15 return;
1184 }
1185  
1186 # Just continue, we need to do this since related objects might have changed...
1187 30 $related_result->mutate_recursively;
1188 }
1189  
1190 7 1;
1191  
1192 =head1 NAME
1193  
1194 DBIx::Class::Valiant::Result - Base component to add Valiant functionality
1195  
1196 =head1 SYNOPSIS
1197  
1198 package Example::Schema::Result::Person;
1199  
1200 use base 'DBIx::Class::Core';
1201  
1202 __PACKAGE__->load_components('Valiant::Result');
1203  
1204 Or just add to your base Result class
1205  
1206  
1207 package Example::Schema::Result;
1208  
1209 use strict;
1210 use warnings;
1211 use base 'DBIx::Class::Core';
1212  
1213 __PACKAGE__->load_components('Valiant::Result');
1214  
1215 =head1 DESCRIPTION
1216  
1217 Glue L<Valiant> validations into your DBIC result sources. This package just has some basic
1218 API level docs, you should see L<DBIx::Class::Valiant> for a somewhat more detailed documentation
1219 and examples.
1220  
1221 =head1 CONTEXTS
1222  
1223 When doing an insert / create on a result, we automatically add a 'create' context which you
1224 can use to limit validations to create events. Additionally for an update we add an 'update'
1225 context.
1226  
1227 =head1 CLASS METHODS
1228  
1229 This component adds the following class or package methods to your result classes. Please note
1230 this is only class methods added by this package, it does not cover those which are aggregated
1231 from the L<Valiant::Validates> role.
1232  
1233 =head2 auto_validation (Boolean)
1234  
1235 Defaults to true. When true Valiant will first perform a validation on the existing result
1236 object (and any related objects nested under it which have been loaded from the DB or created)
1237 and if there are validation errors will skip persisting the data to the database. You can use
1238 this to disable this behavior globally. Please not there are features to enable skipping auto
1239 validation on a per result/set basis as well.
1240  
1241 =head2 accept_nested_for (field => \%options)
1242  
1243 Allows you to update / create related objected which are nested under the parent (via has_one,
1244 might_have or has_many defined relationships). Accepts the following hashref of options:
1245  
1246 =over 4
1247  
1248 =item allow_destroy
1249  
1250 By default you cannot delete related (nested) results. Setting this to true allows that.
1251  
1252 =item reject_if
1253  
1254 A coderef that will cause a nested result to skip if you return true. Arguments are the
1255 parent result and a hashref of the values to be used for the nested build:
1256  
1257 __PACKAGE__->accept_nested_for(
1258 might => {
1259 reject_if => sub {
1260 my ($self, $params) = @_;
1261 return ($params->{value}||'') eq 'test14' ? 1:0;
1262 },
1263 }
1264 );
1265  
1266 Please note that if you have this on a C<has_many> relationship the code ref will be invoked
1267 on each result in the collection of related results you are attempted to nest values into. This
1268 can impact performance.
1269  
1270 =item limit
1271  
1272 accepts a scalar which will cause the nested results to fail of the number of items is
1273 greater than the scalar.
1274  
1275 =item update_only
1276  
1277 For C<has_one> or C<might_have> relationships will force update the existing nested result (if
1278 any exists) even if you fail to set the primary key. Otherwise the current record will be
1279 deleted and a new one inserted. Default is false.
1280  
1281 =item find_with_uniques
1282  
1283 Generally we only try to find a matching row in the DB if a primary key is given. If you set
1284 this to true then we also try to match using and unique keys establish for the related row.
1285  
1286 =back
1287  
1288 B<NOTE> Recursion warning! You cannot currently C<accept_nested_for> for a relationship
1289 whose target result source is setting C<accept_nested_for> into yourself. This is probably
1290 fixable, patches and use cases welcomed!
1291  
1292 =head1 METHODS
1293  
1294 This component adds the following object methods. Please note
1295 this is only class methods added by this package, it does not cover those which are aggregated
1296 from the L<Valiant::Validates> role.
1297  
1298 =head2 is_marked_for_deletion
1299  
1300 Will be true if the result has been marked for deletion. You might see this in a related result
1301 nested under a parent when an update calls for the record to be deleted but validation errors prevented
1302 the deletion from occuring.
1303  
1304 =head2 is_pruned
1305  
1306 Will be true if the result is nested under a result which has been C<marked_for_deletion>. The result
1307 is not itself marked to be deleted (if validation passes) but it will no longer be attached to the
1308 parent result under which it is nested.
1309  
1310 =head2 is_removed
1311  
1312 Is true if C<is_pruned> or C<is_marked_for_deletion> is true.
1313  
1314 =head2 build_related
1315  
1316 =head2 build_related_if_empty
1317  
1318 Builds a related result into the cache. The result is only in memory; it can be used to run validation
1319 but is not inserted unless specified later.
1320  
1321 You might use these methods if you are validating a nested results but the results are not already in
1322 the database (see C<example> directory for an application that uses this).
1323  
1324 =head1 AUTHOR
1325
1326 John Napiorkowski L<email:jjnapiork@cpan.org>
1327
1328 =head1 SEE ALSO
1329
1330 L<Valiant>, L<DBIx::Class>
1331  
1332 =head1 COPYRIGHT & LICENSE
1333
1334 Copyright 2020, John Napiorkowski L<email:jjnapiork@cpan.org>
1335
1336 This library is free software; you can redistribute it and/or modify it under
1337 the same terms as Perl itself.
1338  
1339 =cut
1340  
1341  
« Valiant/Validator/Each.pm ↑ Summary Valiant/Validator/Collection.pm »