DBIx/Class/Valiant/Result.pm

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