blib/lib/DBIO/ResultSet.pm

filter: Statementstmt 90.0% 1854 / 2058 Branchbran 79.0% 1034 / 1308 Conditioncond 65.0% 537 / 826 MC/DCmcdc 43.1% 201 / 466 Subroutinesub 94.2% 230 / 244 Podpod 98.9% 98 / 99 totaltotal 79.0% 3954 / 5001 CC 1041 SCAR 45.2
CC
1041
Cov
82%
populate
878.6
_construct_results
174.4
_resolved_attrs
104.3
CRAP 92.1
« blib/lib/DBIO/SQL/Util.pm ↑ Summary blib/lib/DBIO/Storage/DBI/Cursor.pm »
1 package DBIO::ResultSet;
2 # ABSTRACT: Lazy query object for fetching and manipulating DBIO rows
3  
4 379 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 379 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 379 our $VERSION = '0.900007';
8  
9 379 ▶use base qw/DBIO::Base/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 379 ▶use DBIO::Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 379 ▶use DBIO::ResultSetColumn;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 379 ▶use Scalar::Util qw/blessed weaken reftype/;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 379 ▶use DBIO::Util qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
14 assert_no_list_context fail_on_internal_call UNRESOLVABLE_CONDITION
15 assert_no_internal_indirect_calls
16 help_url is_literal_value is_plain_value bare_binds assert_column_value
17 stresstest_utf8_upgrade_generated_collapser_source
18 379 );
19 379 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 379 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
22 # De-duplication in _merge_attr() is disabled, but left in for reference
23 # (the merger is used for other things that ought not to be de-duped)
24 379 *__HM_DEDUP = sub () { 0 };
25 }
26  
27 # FIXME - get rid of this
28 379 ▶use Hash::Merge ();
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 379 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 use overload
33 # numification passes (undef, "") - count() must see no arguments
34 1 ▶ '0+' => sub { $_[0]->count },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
35 379 'bool' => "_bool",
36 379 fallback => 1;
37  
38 sub _bool () { 1 }
39  
40 379 __PACKAGE__->mk_group_accessors('simple' => qw/_result_class result_source/);
41  
42  
43 14653 ▶sub new {
Subroutine new: called CC=9 SCAR=22.0
Pod documented
44 14653 my $class = shift;
45  
46 14653 ▶ if (ref $class) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class) 2 14651 14653
47 2 ▶ assert_no_internal_indirect_calls and fail_on_internal_call;
Branch: 1 branch
BranchTrueFalseTotal
&assert_no_internal_indirect_calls() and fail_on_internal_call() 0 2 2
48 2 return $class->new_result(@_);
49 }
50  
51 14651 my ($source, $attrs) = @_;
52  
53 14651 ▶ $attrs = { %{$attrs||{}} };
Condition50%1/2
$attrs || {}
l!l
146510
MC/DC0%0/1
$attrs || {}
$attrs
Truth table50%1/2
A
A= $attrs
Aresult
11
00
54 14651 delete @{$attrs}{qw(_last_sqlmaker_alias_map _simple_passthrough_construction)};
55  
56 14651 ▶ if ($attrs->{page}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"page"}) 30 14621 14651
57 30 ▶ $attrs->{rows} ||= 10;
Condition100%2/2
$attrs->{"rows"} ||= 10
l!l
237
MC/DC100%1/1
$attrs->{"rows"} ||= 10
$attrs->{"rows"}
Truth table100%2/2
A
A= $attrs->{"rows"}
Aresult
11
00
58 }
59  
60 14651 ▶ $attrs->{alias} ||= 'me';
Condition100%2/2
$attrs->{"alias"} ||= "me"
l!l
81846467
MC/DC100%1/1
$attrs->{"alias"} ||= "me"
$attrs->{"alias"}
Truth table100%2/2
A
A= $attrs->{"alias"}
Aresult
11
00
61  
62 my $self = bless {
63 result_source => $source,
64 cond => $attrs->{where},
65 14651 pager => undef,
66 attrs => $attrs,
67 }, $class;
68  
69 # if there is a dark selector, this means we are already in a
70 # chain and the cleanup/sanification was taken care of by
71 # _search_rs already
72 $self->_normalize_selection($attrs)
73 14651 ▶ unless $attrs->{_dark_selector};
Branch: 1 branch
BranchTrueFalseTotal
unless $attrs->{"_dark_selector"} 14634 17 14651
74  
75 $self->result_class(
76 14651 ▶ $attrs->{result_class} || $source->result_class
Condition66%2/3
$attrs->{'result_class'} || $source->result_class
l!l&&r!l&&!r
1155134960
MC/DC0%0/2
$attrs->{'result_class'} || $source->result_class
$attrs->{'result_class'} $source->result_class
Truth table66%2/3
A || B
A= $attrs->{'result_class'}B= $source->result_class
ABresult
1X1
011
000
77 );
78  
79 14641 $self;
80 }
81  
82  
83 4729 ▶sub search {
Subroutine search: called CC=4 SCAR=14.0
Pod documented
84 4729 my $self = shift;
85  
86 # ADR 0042: DBIO has no wantarray-dependent return types. search() used to
87 # return the rows in list context; it now refuses that outright so that a
88 # later "fix" cannot turn `my @cds = $rs->search(...)` into a silent
89 # one-element list containing the ResultSet.
90 4729 ▶ assert_no_list_context('->search') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 2 4727 4729
91  
92 4727 my $rs = $self->search_rs( @_ );
93  
94 4713 ▶ if (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 4712 1 4713
95 4712 return $rs;
96 }
97 else {
98 # we can be called by a relationship helper, which in
99 # turn may be called in void context due to some braindead
100 # overload or whatever else the user decided to be clever
101 # at this particular day. Thus limit the exception to
102 # external code calls only
103 1 ▶ $self->throw_exception ('->search is *not* a mutator, calling it in void context makes no sense')
Branch: 1 branch
BranchTrueFalseTotal
unless (caller)[0] =~ /^DBIO\:\:/ 1 0 1
104 if (caller)[0] !~ /^\QDBIO::/;
105  
106 0 return ();
107 }
108 }
109  
110  
111 7684 ▶sub search_rs {
Subroutine search_rs: called CC=36 SCAR=36.7
Pod documented
112 7684 my $self = shift;
113  
114 7684 my $rsrc = $self->result_source;
115 7684 my ($call_cond, $call_attrs);
116  
117 # Special-case handling for (undef, undef) or (undef)
118 # Note that (foo => undef) is valid deprecated syntax
119 7684 ▶ @_ = () if not scalar grep { defined $_ } @_;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar grep({defined $_;} @_) 2529 5155 7684
120  
121 # just a cond
122 7684 ▶ if (@_ == 1) {
Branch: 4 branches
BranchTrueFalseTotal
if (@_ == 1) { } 875 6809 7684
elsif (@_ == 2 and !defined($_[0]) || ref $_[0] ne '') { } 4274 2535 6809
elsif (@_ % 2) { } 6 2529 2535
elsif (@_) { } 0 2529 2529
123 875 $call_cond = shift;
124 }
125 # fish out attrs in the ($condref, $attr) case
126 ▶ elsif (@_ == 2 and ( ! defined $_[0] or (ref $_[0]) ne '') ) {
Condition66%4/6
@_ == 2 and !defined($_[0]) || ref $_[0] ne ""
!ll&&!rl&&r
253504274
not defined $_[0] or ref $_[0] ne ""
l!l&&r!l&&!r
64636280
MC/DC33%1/3
@_ == 2 and !defined($_[0]) || ref $_[0] ne ""
@_ == 2 not defined $_[0] ref $_[0] ne ""
Truth table75%3/4
A and not(B) or C
A= @_ == 2B= not defined $_[0]C= ref $_[0] ne ""
ABCresult
0XX0
1000
11X1
1011
127 4274 ($call_cond, $call_attrs) = @_;
128 }
129 elsif (@_ % 2) {
130 6 $self->throw_exception('Odd number of arguments to search')
131 }
132 # legacy search
133 elsif (@_) {
134 0 carp_unique 'search( %condition ) is deprecated, use search( \%condition ) instead';
135  
136 0 for my $i (0 .. $#_) {
137 0 ▶ next if $i % 2;
Branch: 1 branch
BranchTrueFalseTotal
if $i % 2 0 0 0
138 0 ▶ $self->throw_exception ('All keys in condition key/value pairs must be plain scalars')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_[$i] or ref $_[$i] ne "" 0 0 0
Condition0%0/3
not defined $_[$i] or ref $_[$i] ne ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $_[$i] or ref $_[$i] ne ""
not defined $_[$i] ref $_[$i] ne ""
Truth table0%0/3
not(A) or B
A= not defined $_[$i]B= ref $_[$i] ne ""
ABresult
1X1
011
000
139 if (! defined $_[$i] or ref $_[$i] ne '');
140 }
141  
142 0 $call_cond = { @_ };
143 }
144  
145 # see if we can keep the cache (no $rs changes)
146 7678 my $cache;
147 7678 my %safe = (alias => 1, cache => 1);
148 7678 ▶ if ( ! grep { !$safe{$_} } keys %$call_attrs and (
Branch: 1 branch
BranchTrueFalseTotal
if (not grep({not $safe{$_};} keys %$call_attrs) and !defined($call_cond) || ref $call_cond eq "HASH" && !keys(%$call_cond) || ref $call_cond eq "ARRAY" && !@$call_cond) 2594 5084 7678
Condition100%15/15
not grep({not $safe{$_};} keys %$call_attrs) and !defined($call_cond) || ref $call_cond eq "HASH" && !keys(%$call_cond) || ref $call_cond eq "ARRAY" && !@$call_cond
!ll&&!rl&&r
42358492594
not defined $call_cond or ref $call_cond eq "HASH" and not keys %$call_cond or ref $call_cond eq "ARRAY" and not @$call_cond
l!l&&r!l&&!r
25922849
not defined $call_cond or ref $call_cond eq "HASH" and not keys %$call_cond
l!l&&r!l&&!r
253557851
ref $call_cond eq "HASH" and not keys %$call_cond
!ll&&!rl&&r
2882357
ref $call_cond eq "ARRAY" and not @$call_cond
!ll&&!rl&&r
832172
MC/DC100%6/6
not grep({not $safe{$_};} keys %$call_attrs) and !defined($call_cond) || ref $call_cond eq "HASH" && !keys(%$call_cond) || ref $call_cond eq "ARRAY" && !@$call_cond
not grep({not $safe{$_};} keys %$call_attrs) not defined $call_cond ref $call_cond eq "HASH" not keys %$call_cond ref $call_cond eq "ARRAY" not @$call_cond
Truth table77%7/9
not(A) and not(B) or C and not(D) or E and not(F)
A= not grep({not $safe{$_};} keys %$call_attrs)B= not defined $call_condC= ref $call_cond eq "HASH"D= not keys %$call_condE= ref $call_cond eq "ARRAY"F= not @$call_cond
ABCDEFresult
0XXXXX0
100X0X0
100X100
10100X0
1010100
11XXXX1
1011XX1
100X111
1010111
149 ! defined $call_cond
150 or
151 ref $call_cond eq 'HASH' && ! keys %$call_cond
152 or
153 ref $call_cond eq 'ARRAY' && ! @$call_cond
154 )) {
155 2594 $cache = $self->get_cache;
156 }
157  
158 7678 my $old_attrs = { %{$self->{attrs}} };
159 7678 my ($old_having, $old_where) = delete @{$old_attrs}{qw(having where)};
160  
161 7678 my $new_attrs = { %$old_attrs };
162  
163 # take care of call attrs (only if anything is changing)
164 7678 ▶ if ($call_attrs and keys %$call_attrs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($call_attrs and keys %$call_attrs) 4263 3415 7678
Condition66%2/3
$call_attrs and keys %$call_attrs
!ll&&!rl&&r
034154263
MC/DC50%1/2
$call_attrs and keys %$call_attrs
$call_attrs keys %$call_attrs
Truth table66%2/3
A and B
A= $call_attrsB= keys %$call_attrs
ABresult
0X0
100
111
165  
166 # copy for _normalize_selection
167 4263 $call_attrs = { %$call_attrs };
168  
169 4263 my @selector_attrs = qw/select as columns cols +select +as +columns include_columns/;
170  
171 # reset the current selector list if new selectors are supplied
172 589 delete @{$old_attrs}{(@selector_attrs, '_dark_selector')}
173 4263 ▶ if grep { exists $call_attrs->{$_} } qw(columns cols select as);
Branch: 1 branch
BranchTrueFalseTotal
if grep {exists $call_attrs->{$_};} "columns", "cols", "select", "as" 589 3674 4263
174  
175 # Normalize the new selector list (operates on the passed-in attr structure)
176 # Need to do it on every chain instead of only once on _resolved_attrs, in
177 # order to allow detection of empty vs partial 'as'
178 $call_attrs->{_dark_selector} = $old_attrs->{_dark_selector}
179 4263 ▶ if $old_attrs->{_dark_selector};
Branch: 1 branch
BranchTrueFalseTotal
if $old_attrs->{"_dark_selector"} 8 4255 4263
180 4263 $self->_normalize_selection ($call_attrs);
181  
182 # start with blind overwriting merge, exclude selector attrs
183 4261 $new_attrs = { %{$old_attrs}, %{$call_attrs} };
184 4261 delete @{$new_attrs}{@selector_attrs};
185  
186 4261 for (@selector_attrs) {
187 $new_attrs->{$_} = $self->_merge_attr($old_attrs->{$_}, $call_attrs->{$_})
188 34088 ▶ if ( exists $old_attrs->{$_} or exists $call_attrs->{$_} );
Branch: 1 branch
BranchTrueFalseTotal
if exists $old_attrs->{$_} or exists $call_attrs->{$_} 820 33268 34088
Condition100%3/3
exists $old_attrs->{$_} or exists $call_attrs->{$_}
l!l&&r!l&&!r
9272833268
MC/DC100%2/2
exists $old_attrs->{$_} or exists $call_attrs->{$_}
exists $old_attrs->{$_} exists $call_attrs->{$_}
Truth table100%3/3
A or B
A= exists $old_attrs->{$_}B= exists $call_attrs->{$_}
ABresult
1X1
011
000
189 }
190  
191 # older deprecated name, use only if {columns} is not there
192 4261 ▶ if (my $c = delete $new_attrs->{cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $c = delete $new_attrs->{"cols"}) 1 4260 4261
193 1 carp_unique( "Resultset attribute 'cols' is deprecated, use 'columns' instead" );
194 1 ▶ if ($new_attrs->{columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_attrs->{'columns'}) { } 0 1 1
195 0 carp "Resultset specifies both the 'columns' and the legacy 'cols' attributes - ignoring 'cols'";
196 }
197 else {
198 1 $new_attrs->{columns} = $c;
199 }
200 }
201  
202  
203 # join/prefetch use their own crazy merging heuristics
204 4261 foreach my $key (qw/join prefetch/) {
205 $new_attrs->{$key} = $self->_merge_joinpref_attr($old_attrs->{$key}, $call_attrs->{$key})
206 8522 ▶ if exists $call_attrs->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $call_attrs->{$key} 97 8425 8522
207 }
208  
209 # stack binds together
210 4261 ▶ $new_attrs->{bind} = [ @{ $old_attrs->{bind} || [] }, @{ $call_attrs->{bind} || [] } ];
Condition100%4/4
$old_attrs->{'bind'} || []
l!l
2594002
$call_attrs->{'bind'} || []
l!l
134248
MC/DC100%1/1
$old_attrs->{'bind'} || []
$old_attrs->{'bind'}
MC/DC100%1/1
$call_attrs->{'bind'} || []
$call_attrs->{'bind'}
Truth table100%2/2
A
A= $old_attrs->{'bind'}
Aresult
11
00
Truth table100%2/2
A
A= $call_attrs->{'bind'}
Aresult
11
00
211 }
212  
213  
214 7676 for ($old_where, $call_cond) {
215 15352 ▶ if (defined $_) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_) 7280 8072 15352
216 $new_attrs->{where} = $self->_stack_cond (
217 $_, $new_attrs->{where}
218 7280 );
219 }
220 }
221  
222 7676 ▶ if (defined $old_having) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $old_having) 4 7672 7676
223 $new_attrs->{having} = $self->_stack_cond (
224 $old_having, $new_attrs->{having}
225 )
226 4 }
227  
228 7676 my $rs = (ref $self)->new($rsrc, $new_attrs);
229  
230 7667 ▶ $rs->set_cache($cache) if ($cache);
Branch: 1 branch
BranchTrueFalseTotal
if $cache 20 7647 7667
231  
232 # A bound async context propagates across search_rs clones, so
233 # $rs->with_context($ctx)->search({...}) keeps routing async ops onto the
234 # pinned connection. Kept OUT of {attrs} on purpose -- attrs are copied,
235 # merged and serialized, and a live connection pin has no business there.
236 $rs->{_async_context} = $self->{_async_context}
237 7667 ▶ if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 258 7409 7667
238  
239 7667 return $rs;
240 }
241  
242  
243 my %UNTRUSTED_OPERAND_OPERATORS = (
244 3411 ( map { $_ => 'scalar' } ('=', '!=', '<>', '<', '<=', '>', '>=', '-like', '-not_like') ),
245 758 ( map { $_ => 'list' } ('-in', '-not_in') ),
246 758 ( map { $_ => 'pair' } ('-between', '-not_between') ),
247 379 ( map { $_ => 'null' } ('-is', '-is_not') ),
248 );
249  
250 84 ▶sub search_untrusted {
Subroutine search_untrusted: called CC=9 SCAR=22.8
Pod documented
251 84 my $self = shift;
252  
253 84 ▶ assert_no_list_context('->search_untrusted') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 83 84
254  
255 83 ▶ $self->throw_exception('->search_untrusted takes exactly one argument, a condition')
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 3 80 83
256 unless @_ == 1;
257  
258 80 my $cond = $_[0];
259  
260 80 my %aliases;
261 80 ▶ for my $chunk (@{ $self->_resolved_attrs->{from} || [] }) {
Condition50%1/2
$self->_resolved_attrs->{'from'} || []
l!l
800
MC/DC0%0/1
$self->_resolved_attrs->{'from'} || []
$self->_resolved_attrs->{'from'}
Truth table50%1/2
A
A= $self->_resolved_attrs->{'from'}
Aresult
11
00
262 84 ▶ my $head = ref $chunk eq 'ARRAY' ? $chunk->[0] : $chunk;
Branch: 1 branch
BranchTrueFalseTotal
ref $chunk eq 'ARRAY' ? : 4 80 84
263 84 ▶ next unless ref $head eq 'HASH' and $head->{-alias} and $head->{-rsrc};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $head eq "HASH" and $head->{"-alias"} and $head->{"-rsrc"} 0 84 84
Condition33%2/6
ref $head eq "HASH" and $head->{"-alias"} and $head->{"-rsrc"}
!ll&&!rl&&r
0084
ref $head eq "HASH" and $head->{"-alias"}
!ll&&!rl&&r
0084
MC/DC0%0/3
ref $head eq "HASH" and $head->{"-alias"} and $head->{"-rsrc"}
ref $head eq "HASH" $head->{"-alias"} $head->{"-rsrc"}
Truth table25%1/4
A and B and C
A= ref $head eq "HASH"B= $head->{"-alias"}C= $head->{"-rsrc"}
ABCresult
0XX0
10X0
1100
1111
264 84 $aliases{ $head->{-alias} } = $head->{-rsrc};
265 }
266  
267 80 $self->_assert_untrusted_node($cond, '', \%aliases, {});
268  
269 30 return $self->search_rs($cond);
270 }
271  
272 50 ▶sub _untrusted_fail {
Subroutine _untrusted_fail: called CC=2 SCAR=6.9
273 50 my ($self, $path, $what) = @_;
274 50 ▶ $self->throw_exception(sprintf '->search_untrusted: %s%s', (length $path ? "$path: " : ''), $what);
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 46 4 50
275 }
276  
277 104 ▶sub _assert_untrusted_node {
Subroutine _assert_untrusted_node: called CC=14 SCAR=26.4
278 104 my ($self, $node, $path, $aliases, $seen) = @_;
279  
280 104 my $type = ref $node;
281 104 ▶ $self->_untrusted_fail($path, 'a condition is a hash or array reference, not '
Branch: 3 branches
BranchTrueFalseTotal
unless $type eq "HASH" or $type eq "ARRAY" 6 98 104
defined $node ? : 5 1 6
$type ? : 2 3 5
Condition100%3/3
$type eq "HASH" or $type eq "ARRAY"
l!l&&r!l&&!r
85136
MC/DC100%2/2
$type eq "HASH" or $type eq "ARRAY"
$type eq "HASH" $type eq "ARRAY"
Truth table100%3/3
A or B
A= $type eq "HASH"B= $type eq "ARRAY"
ABresult
1X1
011
000
282 . (defined $node ? ($type ? DBIO::Util::refdesc($node) : 'a scalar') : 'undef'))
283 unless $type eq 'HASH' or $type eq 'ARRAY';
284  
285 98 my $addr = Scalar::Util::refaddr($node);
286 98 ▶ $self->_untrusted_fail($path, 'the condition holds a cycle') if $seen->{$addr};
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$addr} 2 96 98
287 96 local $seen->{$addr} = 1;
288  
289 96 ▶ if ($type eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "ARRAY") 12 84 96
290 12 for my $i (0 .. $#$node) {
291 15 $self->_assert_untrusted_node($node->[$i], "$path\[$i]", $aliases, $seen);
292 }
293 7 return;
294 }
295  
296 84 for my $key (sort keys %$node) {
297 85 my $kpath = "$path\{$key}";
298 85 my $val = $node->{$key};
299  
300 85 ▶ if ($key eq '-and' or $key eq '-or') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "-and" or $key eq "-or") 12 73 85
Condition100%3/3
$key eq "-and" or $key eq "-or"
l!l&&r!l&&!r
8473
MC/DC100%2/2
$key eq "-and" or $key eq "-or"
$key eq "-and" $key eq "-or"
Truth table100%3/3
A or B
A= $key eq "-and"B= $key eq "-or"
ABresult
1X1
011
000
301 12 ▶ $self->_untrusted_fail($kpath, "$key takes an array or hash reference of conditions")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "HASH" or ref $val eq "ARRAY" 3 9 12
Condition100%3/3
ref $val eq "HASH" or ref $val eq "ARRAY"
l!l&&r!l&&!r
273
MC/DC100%2/2
ref $val eq "HASH" or ref $val eq "ARRAY"
ref $val eq "HASH" ref $val eq "ARRAY"
Truth table100%3/3
A or B
A= ref $val eq "HASH"B= ref $val eq "ARRAY"
ABresult
1X1
011
000
302 unless ref $val eq 'HASH' or ref $val eq 'ARRAY';
303 9 $self->_assert_untrusted_node($val, $kpath, $aliases, $seen);
304 6 next;
305 }
306  
307 73 ▶ $self->_untrusted_fail($kpath, "'$key' is not a column")
Branch: 1 branch
BranchTrueFalseTotal
if $key =~ /\A-/ 5 68 73
308 if $key =~ /\A-/;
309  
310 68 $self->_assert_untrusted_column($key, $kpath, $aliases);
311 61 $self->_assert_untrusted_operand($val, $kpath);
312 }
313 }
314  
315 68 ▶sub _assert_untrusted_column {
Subroutine _assert_untrusted_column: called CC=4 SCAR=13.9
316 68 my ($self, $key, $path, $aliases) = @_;
317  
318 68 my ($rsrc, $col) = ($self->result_source, $key);
319 68 ▶ if ($key =~ /\A(.+)\.([^.]+)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /\A(.+)\.([^.]+)\z/) 8 60 68
320 8 $rsrc = $aliases->{$1};
321 8 $col = $2;
322 8 ▶ $self->_untrusted_fail($path, "'$1' is not an alias of this resultset")
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc 3 5 8
323 unless $rsrc;
324 }
325  
326 65 ▶ $self->_untrusted_fail($path, "'$key' is not a column")
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->has_column($col) 4 61 65
327 unless $rsrc->has_column($col);
328 }
329  
330 61 ▶sub _assert_untrusted_operand {
Subroutine _assert_untrusted_operand: called CC=17 SCAR=28.3
331 61 my ($self, $val, $path) = @_;
332  
333 61 ▶ if (! ref $val) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $val) { } 18 43 61
elsif (ref $val eq 'ARRAY') { } 3 40 43
elsif (ref $val eq 'HASH') { } 35 5 40
334 18 return;
335 }
336 elsif (ref $val eq 'ARRAY') {
337 3 for my $i (0 .. $#$val) {
338 5 ▶ $self->_untrusted_fail("$path\[$i]", 'a list of values holds scalars only, not '
Branch: 1 branch
BranchTrueFalseTotal
if ref $val->[$i] 2 3 5
339 . DBIO::Util::refdesc($val->[$i])) if ref $val->[$i];
340 }
341 1 return;
342 }
343 elsif (ref $val eq 'HASH') {
344 35 ▶ $self->_untrusted_fail($path, 'an operand holds exactly one operator')
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$val == 1 2 33 35
345 unless keys %$val == 1;
346  
347 33 my ($op) = keys %$val;
348 33 my $opath = "$path\{$op}";
349 33 my $arg = $val->{$op};
350  
351 33 ▶ my $kind = $UNTRUSTED_OPERAND_OPERATORS{$op}
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $UNTRUSTED_OPERAND_OPERATORS{$op} or $self->_untrusted_fail($opath, "'${op}' is not an allowed operator") 24 9 33
352 or $self->_untrusted_fail($opath, "'$op' is not an allowed operator");
353  
354 24 ▶ if ($kind eq 'scalar') {
Branch: 2 branches
BranchTrueFalseTotal
if ($kind eq 'scalar') { } 11 13 24
elsif ($kind eq 'null') { } 4 9 13
355 11 ▶ $self->_untrusted_fail($opath, "'$op' takes a scalar") if ref $arg;
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg 2 9 11
356 }
357 elsif ($kind eq 'null') {
358 4 ▶ $self->_untrusted_fail($opath, "'$op' takes undef") if defined $arg;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg 2 2 4
359 }
360 else {
361 $self->_untrusted_fail($opath, "'$op' takes an array reference of "
362 . ($kind eq 'pair' ? 'two scalars' : 'scalars'))
363 9 ▶ unless ref $arg eq 'ARRAY' and ! grep { ref } @$arg
Branch: 2 branches
BranchTrueFalseTotal
unless ref $arg eq "ARRAY" and not grep({ref $_;} @$arg) and $kind ne "pair" || @$arg == 2 5 4 9
$kind eq 'pair' ? : 3 2 5
Condition100%9/9
ref $arg eq "ARRAY" and not grep({ref $_;} @$arg) and $kind ne "pair" || @$arg == 2
!ll&&!rl&&r
324
ref $arg eq "ARRAY" and not grep({ref $_;} @$arg)
!ll&&!rl&&r
216
$kind ne "pair" or @$arg == 2
l!l&&r!l&&!r
222
MC/DC100%4/4
ref $arg eq "ARRAY" and not grep({ref $_;} @$arg) and $kind ne "pair" || @$arg == 2
ref $arg eq "ARRAY" not grep({ref $_;} @$arg) $kind ne "pair" @$arg == 2
Truth table100%5/5
A and not(B) and C or D
A= ref $arg eq "ARRAY"B= not grep({ref $_;} @$arg)C= $kind ne "pair"D= @$arg == 2
ABCDresult
0XXX0
10XX0
11000
111X1
11011
364 and ($kind ne 'pair' or @$arg == 2);
365 }
366 15 return;
367 }
368  
369 5 $self->_untrusted_fail($path, 'a value is a scalar, not ' . DBIO::Util::refdesc($val));
370 }
371  
372  
373 164 ▶sub with_context {
Subroutine with_context: called CC=7 SCAR=19.6
Pod documented
374 164 my ($self, $ctx) = @_;
375 164 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ctx and builtin::blessed($ctx) and $ctx->can("select_async") 3 161 164
Condition100%6/6
defined $ctx and builtin::blessed($ctx) and $ctx->can("select_async")
!ll&&!rl&&r
21161
defined $ctx and builtin::blessed($ctx)
!ll&&!rl&&r
11162
MC/DC100%3/3
defined $ctx and builtin::blessed($ctx) and $ctx->can("select_async")
defined $ctx builtin::blessed($ctx) $ctx->can("select_async")
Truth table100%4/4
A and B and C
A= defined $ctxB= builtin::blessed($ctx)C= $ctx->can("select_async")
ABCresult
0XX0
10X0
1100
1111
376 'with_context requires an async context object (the one passed to a '
377 . 'txn_do_async / pipeline coderef)'
378 ) unless defined $ctx and blessed($ctx) and $ctx->can('select_async');
379 161 my $storage = $self->result_source->storage;
380 161 $storage->_assert_async_context_owner($ctx);
381 150 my $clone = $self->search_rs;
382 150 $clone->{_async_context} = $ctx;
383  
384 # A bound clone that already carries a pre-filled row cache (an explicit
385 # set_cache, or a prefetch cache copied by search_rs) returns those rows
386 # directly from the cache -- so all/all_async off it would hand back
387 # context-less rows and a write-back on one would miss the pin. Rebind the
388 # cached rows onto the context in a FRESH cache, leaving the unbound source's
389 # shared rows untouched (karr k195, ADR 0045).
390 150 ▶ if (my $cache = $clone->get_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = $clone->get_cache) 3 147 150
391 $clone->set_cache([
392 3 ▶ map { blessed $_ && $_->can('with_context') ? $_->with_context($ctx) : $_ } @$cache
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_) && $_->can('with_context') ? : 3 0 3
Condition33%1/3
builtin::blessed($_) and $_->can("with_context")
!ll&&!rl&&r
003
MC/DC0%0/2
builtin::blessed($_) and $_->can("with_context")
builtin::blessed($_) $_->can("with_context")
Truth table33%1/3
A and B
A= builtin::blessed($_)B= $_->can("with_context")
ABresult
0X0
100
111
393 ]);
394 }
395  
396 150 return $clone;
397 }
398  
399 # ADR 0045: the pinned async context bound via with_context (undef if unbound).
400 # Read on every RS async op before the pooled backend; see _rs_run_async.
401 875 ▶sub _async_context { $_[0]->{_async_context} }
Subroutine _async_context: called CC=1 SCAR=0.0
402  
403 379 my $dark_sel_dumper;
404 18897 ▶sub _normalize_selection {
Subroutine _normalize_selection: called CC=20 SCAR=30.3
405 18897 my ($self, $attrs) = @_;
406  
407 # legacy syntax
408 18897 ▶ if ( exists $attrs->{include_columns} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $attrs->{"include_columns"}) 1 18896 18897
409 1 carp_unique( "Resultset attribute 'include_columns' is deprecated, use '+columns' instead" );
410 $attrs->{'+columns'} = $self->_merge_attr(
411 $attrs->{'+columns'}, delete $attrs->{include_columns}
412 1 );
413 }
414  
415 # columns are always placed first, however
416  
417 # Keep the X vs +X separation until _resolved_attrs time - this allows to
418 # delay the decision on whether to use a default select list ($rsrc->columns)
419 # allowing stuff like the remove_columns helper to work
420 #
421 # select/as +select/+as pairs need special handling - the amount of select/as
422 # elements in each pair does *not* have to be equal (think multicolumn
423 # selectors like distinct(foo, bar) ). If the selector is bare (no 'as'
424 # supplied at all) - try to infer the alias, either from the -as parameter
425 # of the selector spec, or use the parameter whole if it looks like a column
426 # name (ugly legacy heuristic). If all fails - leave the selector bare (which
427 # is ok as well), but make sure no more additions to the 'as' chain take place
428 18897 for my $pref ('', '+') {
429  
430 my ($sel, $as) = map {
431 37794 my $key = "${pref}${_}";
432  
433 my $val = [ ref $attrs->{$key} eq 'ARRAY'
434 621 ▶ ? @{$attrs->{$key}}
Condition66%2/3
$attrs->{$key} or ()
l!l&&r!l&&!r
403745640
MC/DC0%0/2
$attrs->{$key} or ()
$attrs->{$key} ()
Truth table66%2/3
A or B
A= $attrs->{$key}B= ()
ABresult
1X1
011
000
435 75588 ▶ : $attrs->{$key} || ()
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{$key} eq 'ARRAY' ? : 621 74967 75588
436 ];
437 75588 delete $attrs->{$key};
438 75588 $val;
439 } qw/select as/;
440  
441 37794 ▶ if (! @$as and ! @$sel ) {
Branch: 5 branches
BranchTrueFalseTotal
if (not @$as || @$sel) { } 37232 562 37794
elsif (@$as and not @$sel) { } 0 562 562
elsif (not @$as) { } 101 461 562
elsif (@$as < @$sel) { } 0 461 461
elsif ($pref and $attrs->{'_dark_selector'}) { } 2 880 882
Condition100%3/3
@$as || @$sel
l!l&&r!l&&!r
46110137232
MC/DC100%2/2
@$as || @$sel
@$as @$sel
Truth table100%3/3
A || B
A= @$asB= @$sel
ABresult
1X1
011
000
442 37232 next;
443 }
444 ▶ elsif (@$as and ! @$sel) {
Condition66%2/3
@$as and not @$sel
!ll&&!rl&&r
1014610
MC/DC0%0/2
@$as and not @$sel
@$as not @$sel
Truth table66%2/3
A and not(B)
A= @$asB= not @$sel
ABresult
0X0
100
111
445 0 $self->throw_exception(
446 "Unable to handle ${pref}as specification (@$as) without a corresponding ${pref}select"
447 );
448 }
449 elsif( ! @$as ) {
450 # no as part supplied at all - try to deduce (unless explicit end of named selection is declared)
451 # if any @$as has been supplied we assume the user knows what (s)he is doing
452 # and blindly keep stacking up pieces
453 101 ▶ unless ($attrs->{_dark_selector}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attrs->{"_dark_selector"}) 96 5 101
454 SELECTOR:
455 96 for (@$sel) {
456 106 ▶ if ( ref $_ eq 'HASH' and exists $_->{-as} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $_ eq 'HASH' and exists $_->{'-as'}) { } 4 102 106
elsif (not ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) { } 89 13 102
Condition100%3/3
ref $_ eq "HASH" and exists $_->{"-as"}
!ll&&!rl&&r
10114
MC/DC100%2/2
ref $_ eq "HASH" and exists $_->{"-as"}
ref $_ eq "HASH" exists $_->{"-as"}
Truth table100%3/3
A and B
A= ref $_ eq "HASH"B= exists $_->{"-as"}
ABresult
0X0
100
111
457 4 push @$as, $_->{-as};
458 }
459 # assume any plain no-space, no-parenthesis string to be a column spec
460 # FIXME - this is retarded but is necessary to support shit like 'count(foo)'
461 ▶ elsif ( ! ref $_ and $_ =~ /^ [^\s\(\)]+ $/x) {
Condition66%2/3
not ref $_ and $_ =~ /^ [^\s\(\)]+ $/x
!ll&&!rl&&r
13089
MC/DC50%1/2
not ref $_ and $_ =~ /^ [^\s\(\)]+ $/x
not ref $_ $_ =~ /^ [^\s\(\)]+ $/x
Truth table66%2/3
not(A) and B
A= not ref $_B= $_ =~ /^ [^\s\(\)]+ $/x
ABresult
0X0
100
111
462 89 push @$as, $_;
463 }
464 # if all else fails - raise a flag that no more aliasing will be allowed
465 else {
466 $attrs->{_dark_selector} = {
467 plus_stage => $pref,
468 13 ▶ string => ($dark_sel_dumper ||= do {
Condition66%2/3
$dark_sel_dumper ||= do { require Data::Dumper; "Data::Dumper"->new([])->Indent(0)->Terse(1)->Sortkeys(1) }
l!l&&r!l&&!r
670
MC/DC0%0/2
$dark_sel_dumper ||= do { require Data::Dumper; "Data::Dumper"->new([])->Indent(0)->Terse(1)->Sortkeys(1) }
$dark_sel_dumper do { require Data::Dumper; "Data::Dumper"->new([])->Indent(0)->Terse(1)->Sortkeys(1) }
Truth table66%2/3
A ||= B
A= $dark_sel_dumperB= do { require Data::Dumper; "Data::Dumper"->new([])->Indent(0)->Terse(1)->Sortkeys(1) }
ABresult
1X1
011
000
469 7 require Data::Dumper;
470 7 Data::Dumper->new([])->Indent(0)->Terse(1)->Sortkeys(1);
471 })->Values([$_])->Dump
472 ,
473 };
474 13 last SELECTOR;
475 }
476 }
477 }
478 }
479 elsif (@$as < @$sel) {
480 0 $self->throw_exception(
481 "Unable to handle an ${pref}as specification (@$as) with less elements than the corresponding ${pref}select"
482 );
483 }
484 ▶ elsif ($pref and $attrs->{_dark_selector}) {
Condition100%3/3
$pref and $attrs->{"_dark_selector"}
!ll&&!rl&&r
421382
MC/DC100%2/2
$pref and $attrs->{"_dark_selector"}
$pref $attrs->{"_dark_selector"}
Truth table100%3/3
A and B
A= $prefB= $attrs->{"_dark_selector"}
ABresult
0X0
100
111
485 2 $self->throw_exception(
486 "Unable to process named '+select', resultset contains an unnamed selector $attrs->{_dark_selector}{string}"
487 );
488 }
489  
490  
491 # merge result
492 560 $attrs->{"${pref}select"} = $self->_merge_attr($attrs->{"${pref}select"}, $sel);
493 560 $attrs->{"${pref}as"} = $self->_merge_attr($attrs->{"${pref}as"}, $as);
494 }
495 }
496  
497 7284 ▶sub _stack_cond {
Subroutine _stack_cond: called CC=10 SCAR=23.0
498 7284 my ($self, $left, $right) = @_;
499  
500 (
501 (ref $_ eq 'ARRAY' and !@$_)
502 or
503 (ref $_ eq 'HASH' and ! keys %$_)
504 7284 ▶ ) and $_ = undef for ($left, $right);
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq "ARRAY" && !@$_ || ref $_ eq "HASH" && !keys(%$_) and $_ = undef 359 14209 14568
Condition100%9/9
ref $_ eq "ARRAY" and not @$_ or ref $_ eq "HASH" and not keys %$_
l!l&&r!l&&!r
235714209
ref $_ eq "ARRAY" and not @$_
!ll&&!rl&&r
14501652
ref $_ eq "HASH" and not keys %$_
!ll&&!rl&&r
70397170357
MC/DC100%4/4
ref $_ eq "ARRAY" and not @$_ or ref $_ eq "HASH" and not keys %$_
ref $_ eq "ARRAY" not @$_ ref $_ eq "HASH" not keys %$_
Truth table71%5/7
A and not(B) or C and not(D)
A= ref $_ eq "ARRAY"B= not @$_C= ref $_ eq "HASH"D= not keys %$_
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
505  
506 # either one of the two undef
507 7284 ▶ if ( (defined $left) xor (defined $right) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $left xor defined $right) { } 6812 472 7284
elsif (not defined $left) { } 248 224 472
Condition100%4/4
defined $left xor defined $right
l&&rl&&!r!l&&r!l&&!r
2246701111248
MC/DC100%2/2
defined $left xor defined $right
defined $left defined $right
Truth table100%4/4
A xor B
A= defined $leftB= defined $right
ABresult
110
101
011
000
508 6812 ▶ return defined $left ? $left : $right;
Branch: 1 branch
BranchTrueFalseTotal
defined $left ? : 6701 111 6812
509 }
510 # both undef
511 elsif ( ! defined $left ) {
512 return undef
513 248 }
514 else {
515 224 return $self->result_source->schema->storage->_collapse_cond({ -and => [$left, $right] });
516 }
517 }
518  
519  
520 9 ▶sub search_literal {
Subroutine search_literal: called CC=5 SCAR=17.5
Pod documented
521 9 my ($self, $sql, @bind) = @_;
522  
523 9 ▶ assert_no_list_context('->search_literal') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 8 9
524  
525 8 my $attr;
526 8 ▶ if ( @bind && ref($bind[-1]) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bind and ref $bind[-1] eq "HASH") 0 8 8
Condition66%2/3
@bind and ref $bind[-1] eq "HASH"
!ll&&!rl&&r
440
MC/DC0%0/2
@bind and ref $bind[-1] eq "HASH"
@bind ref $bind[-1] eq "HASH"
Truth table66%2/3
A and B
A= @bindB= ref $bind[-1] eq "HASH"
ABresult
0X0
100
111
527 0 $attr = pop @bind;
528 }
529 8 ▶ return $self->search_rs(\[ $sql, map [ {} => $_ ], @bind ], ($attr || () ));
Condition33%1/3
$attr || ()
l!l&&r!l&&!r
080
MC/DC0%0/2
$attr || ()
$attr ()
Truth table33%1/3
A || B
A= $attrB= ()
ABresult
1X1
011
000
530 }
531  
532  
533 1036 ▶sub find {
Subroutine find: called CC=4 SCAR=13.9
Pod documented
534 1036 my $self = shift;
535 1036 my ($final_cond, $attrs, $is_miss) = $self->_resolve_find_query(@_);
536 1018 ▶ return undef if $is_miss;
Branch: 1 branch
BranchTrueFalseTotal
if $is_miss 2 1016 1018
537  
538 # Run the query, passing the result_class since it should propagate for find
539 1016 my $rs = $self->search ($final_cond, {result_class => $self->result_class, %$attrs});
540 1016 ▶ if ($rs->_resolved_attrs->{collapse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rs->_resolved_attrs->{'collapse'}) { } 1 1015 1016
541 1 my $row = $rs->next;
542 1 ▶ carp "Query returned more than one row" if $rs->next;
Branch: 1 branch
BranchTrueFalseTotal
if $rs->next 0 1 1
543 1 return $row;
544 }
545 else {
546 1015 return $rs->single;
547 }
548 }
549  
550 # Resolve find()'s arguments down to a (condition, attrs) pair ready to hand to
551 # ->search, shared verbatim by find() and find_async() so the two can never
552 # drift: same constraint check (key => ... or any covered constraint), same
553 # relationship-valued-key resolution (ADR 0034). $is_miss is true only for the
554 # non-concrete-relation-condition guard, in which case $final_cond is
555 # meaningless and no query should be run at all.
556 #
557 # Every key of the passed condition goes into the query (ADR 0070); the
558 # constraint check decides whether the condition is allowed to run, it never
559 # narrows it.
560 1100 ▶sub _resolve_find_query {
Subroutine _resolve_find_query: called CC=15 SCAR=27.2
561 1100 my $self = shift;
562 1100 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 984 116 1100
Condition66%2/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
1160984
MC/DC50%1/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table66%2/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
563  
564 1100 my $rsrc = $self->result_source;
565  
566 1100 my $constraint_name;
567 1100 ▶ if (exists $attrs->{key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $attrs->{"key"}) 966 134 1100
568 $constraint_name = defined $attrs->{key}
569 ? $attrs->{key}
570 966 ▶ : $self->throw_exception("An undefined 'key' resultset attribute makes no sense")
Branch: 1 branch
BranchTrueFalseTotal
defined $attrs->{'key'} ? : 966 0 966
571 ;
572 }
573  
574 # Parse out the condition from input
575 1100 my $call_cond;
576  
577 1100 ▶ if (ref $_[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 1048 52 1100
578 1048 $call_cond = { %{$_[0]} };
579 }
580 else {
581 # if only values are supplied we need to default to 'primary'
582 52 ▶ $constraint_name = 'primary' unless defined $constraint_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $constraint_name 51 1 52
583  
584 52 my @c_cols = $rsrc->unique_constraint_columns($constraint_name);
585  
586 52 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @c_cols 0 52 52
587 "No constraint columns, maybe a malformed '$constraint_name' constraint?"
588 ) unless @c_cols;
589  
590 52 ▶ $self->throw_exception (
Branch: 1 branch
BranchTrueFalseTotal
unless @c_cols == @_ 0 52 52
591 'find() expects either a column/value hashref, or a list of values '
592 . "corresponding to the columns of the specified unique constraint '$constraint_name'"
593 ) unless @c_cols == @_;
594  
595 52 @{$call_cond}{@c_cols} = @_;
596 }
597  
598 1100 ▶ return (undef, $attrs, 1) if $self->_fold_relation_conditions($call_cond);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_fold_relation_conditions($call_cond) 3 1095 1098
599  
600 1095 ▶ my $alias = exists $attrs->{alias} ? $attrs->{alias} : $self->{attrs}{alias};
Branch: 1 branch
BranchTrueFalseTotal
exists $attrs->{'alias'} ? : 0 1095 1095
601 1095 my $merged_values = ($self->_merge_with_rscond($call_cond))[0];
602  
603 1095 ▶ if (defined $constraint_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $constraint_name) { } 1016 79 1095
604 # the named constraint must be covered by the condition: a column that is
605 # missing or undef throws (undef is no concrete value, ADR 0070)
606 1016 my $fixed = $rsrc->storage->_extract_fixed_condition_columns($merged_values, 'consider_nulls');
607 my @undef = grep {
608 1014 ▶ exists $fixed->{$_} and ! defined $fixed->{$_}
Condition100%3/3
exists $fixed->{$_} && !defined($fixed->{$_})
!ll&&!rl&&r
210242
MC/DC100%2/2
exists $fixed->{$_} && !defined($fixed->{$_})
exists $fixed->{$_} !defined($fixed->{$_})
Truth table100%3/3
A && not(B)
A= exists $fixed->{$_}B= !defined($fixed->{$_})
ABresult
0X0
100
111
609 } $rsrc->unique_constraint_columns($constraint_name);
610  
611 $self->throw_exception(sprintf(
612 "find() with key '%s': column(s) %s %s undef; a unique constraint is covered by defined values, "
613 . "to look rows up by any other condition use search(...)->single",
614 $constraint_name,
615 1014 ▶ join(', ', map { "'$_'" } sort @undef),
Branch: 2 branches
BranchTrueFalseTotal
if @undef 2 1012 1014
@undef > 1 ? : 0 2 2
616 @undef > 1 ? 'are' : 'is',
617 )) if @undef;
618  
619 1012 $rsrc->_minimal_valueset_satisfying_constraint(
620 constraint_name => $constraint_name,
621 values => $merged_values,
622 );
623 }
624 else {
625 79 $self->_assert_covered_constraint($call_cond, $merged_values, 'find');
626 }
627  
628 1078 return ($self->_qualify_cond_columns($call_cond, $alias), $attrs, 0);
629 }
630  
631 # Fold the relationship-valued keys of a find() condition into columns of this
632 # source, in place (belongs_to given a related row or a condition hashref
633 # resolves to its foreign-key columns). An explicitly passed column keeps its
634 # value: a relationship resolving to a different value for it is a
635 # contradiction and throws. Returns true when a relationship does not reduce to
636 # a concrete condition (the find is a miss, ADR 0034).
637 2062 ▶sub _fold_relation_conditions {
Subroutine _fold_relation_conditions: called CC=22 SCAR=37.1
638 2062 my ($self, $call_cond) = @_;
639  
640 2062 my $rsrc = $self->result_source;
641 2062 my %explicit = %$call_cond;
642  
643 2062 for my $key (sort keys %explicit) {
644 2210 ▶ next unless length ref $explicit{$key} and $rsrc->relationship_info($key);
Branch: 1 branch
BranchTrueFalseTotal
unless length ref $explicit{$key} and $rsrc->relationship_info($key) 2195 15 2210
Condition100%3/3
length ref $explicit{$key} and $rsrc->relationship_info($key)
!ll&&!rl&&r
2191415
MC/DC100%2/2
length ref $explicit{$key} and $rsrc->relationship_info($key)
length ref $explicit{$key} $rsrc->relationship_info($key)
Truth table100%3/3
A and B
A= length ref $explicit{$key}B= $rsrc->relationship_info($key)
ABresult
0X0
100
111
645  
646 $self->throw_exception(
647 "A list value for relationship '$key' is unsupported in find()"
648 15 ▶ ) if ref $explicit{$key} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $explicit{$key} eq "ARRAY" 0 15 15
649  
650 15 my $val = delete $call_cond->{$key};
651 15 my ($rel_cond, $crosstable) = $self->_resolve_related_cond($rsrc, $key, $val);
652  
653 15 ▶ $self->throw_exception("Complex condition via relationship '$key' is unsupported in find()")
Branch: 1 branch
BranchTrueFalseTotal
if $crosstable or ref $rel_cond ne "HASH" 1 14 15
Condition66%2/3
$crosstable or ref $rel_cond ne "HASH"
l!l&&r!l&&!r
1014
MC/DC50%1/2
$crosstable or ref $rel_cond ne "HASH"
$crosstable ref $rel_cond ne "HASH"
Truth table66%2/3
A or B
A= $crosstableB= ref $rel_cond ne "HASH"
ABresult
1X1
011
000
654 if $crosstable or ref($rel_cond) ne 'HASH';
655  
656 # A relation that reduces to a join-free but NON-concrete condition (e.g. a
657 # might_have searched by a non-key column resolves to { self_pk => undef })
658 # is not crosstable and IS a hashref, so it slips past the guard above --
659 # merging it would clobber a real key column with an undef foreign key.
660 # No row can match a condition that does not resolve to concrete columns,
661 # so this find() is a MISS (ADR 0034).
662 14 ▶ return 1 unless $self->_related_cond_is_concrete($rel_cond, $crosstable);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_related_cond_is_concrete($rel_cond, $crosstable) 3 11 14
663  
664 11 for my $col (sort keys %$rel_cond) {
665 11 ▶ next if $col eq $key or ! exists $explicit{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $col eq $key or not exists $explicit{$col} 9 2 11
Condition100%3/3
$col eq $key or not exists $explicit{$col}
l!l&&r!l&&!r
812
MC/DC100%2/2
$col eq $key or not exists $explicit{$col}
$col eq $key not exists $explicit{$col}
Truth table100%3/3
A or not(B)
A= $col eq $keyB= not exists $explicit{$col}
ABresult
1X1
011
000
666  
667 my $given = ref $explicit{$col} eq 'HASH'
668 0 && keys %{$explicit{$col}} == 1
669 && exists $explicit{$col}{'='}
670 ? $explicit{$col}{'='}
671 2 ▶ : $explicit{$col};
Branch: 1 branch
BranchTrueFalseTotal
ref $explicit{$col} eq 'HASH' && keys %{$explicit{$col};} == 1 && exists $explicit{$col}{'='} ? : 0 2 2
Condition33%2/6
ref $explicit{$col} eq "HASH" and keys %{$explicit{$col};} == 1 and exists $explicit{$col}{"="}
!ll&&!rl&&r
200
ref $explicit{$col} eq "HASH" and keys %{$explicit{$col};} == 1
!ll&&!rl&&r
200
MC/DC0%0/3
ref $explicit{$col} eq "HASH" and keys %{$explicit{$col};} == 1 and exists $explicit{$col}{"="}
ref $explicit{$col} eq "HASH" keys %{$explicit{$col};} == 1 exists $explicit{$col}{"="}
Truth table25%1/4
A and B and C
A= ref $explicit{$col} eq "HASH"B= keys %{$explicit{$col};} == 1C= exists $explicit{$col}{"="}
ABCresult
0XX0
10X0
1100
1111
672  
673 2 my $resolved = $rel_cond->{$col};
674  
675 2 ▶ my $same
Branch: 2 branches
BranchTrueFalseTotal
!(defined $given && defined $resolved) ? : 0 2 2
ref $given || ref $resolved ? : 0 2 2
Condition13%2/15
defined $given && defined $resolved
!ll&&!rl&&r
002
defined $given || defined $resolved
l!l&&r!l&&!r
000
ref $given or ref $resolved
l!l&&r!l&&!r
002
ref $given and ref $resolved and $given == $resolved
!ll&&!rl&&r
000
ref $given and ref $resolved
!ll&&!rl&&r
000
MC/DC0%0/2
defined $given && defined $resolved
defined $given defined $resolved
MC/DC0%0/2
defined $given || defined $resolved
defined $given defined $resolved
MC/DC0%0/2
ref $given or ref $resolved
ref $given ref $resolved
MC/DC0%0/3
ref $given and ref $resolved and $given == $resolved
ref $given ref $resolved $given == $resolved
Truth table33%1/3
A && B
A= defined $givenB= defined $resolved
ABresult
0X0
100
111
Truth table0%0/3
A || B
A= defined $givenB= defined $resolved
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= ref $givenB= ref $resolved
ABresult
1X1
011
000
Truth table0%0/4
A and B and C
A= ref $givenB= ref $resolvedC= $given == $resolved
ABCresult
0XX0
10X0
1100
1111
676 = ( ! defined $given or ! defined $resolved ) ? ( ! defined $given and ! defined $resolved )
677 : ( ref $given or ref $resolved ) ? ( ref $given and ref $resolved and $given == $resolved )
678 : $given eq $resolved;
679  
680 2 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $same 1 1 2
681 "The condition passes '$col' explicitly and relationship '$key' resolves it to a different value"
682 ) unless $same;
683 }
684  
685 10 @{$call_cond}{keys %$rel_cond} = values %$rel_cond;
686 }
687  
688 2057 return 0;
689 }
690  
691 # The unique constraints a condition covers: every column of the constraint is
692 # a concrete equality -- a defined scalar, or { '=' => $scalar } -- on the top
693 # AND level, after the resultset's own condition and the relationship values
694 # are merged in. Operators, value lists, undef and a column that only appears
695 # inside an OR branch do not count. Takes the merged values, returns constraint
696 # names, 'primary' first, constraints sharing a column set once.
697 1001 ▶sub _covered_constraints {
Subroutine _covered_constraints: called CC=13 SCAR=27.7
698 1001 my ($self, $merged_values) = @_;
699  
700 1001 my $rsrc = $self->result_source;
701 1001 my $fixed = $rsrc->storage->_extract_fixed_condition_columns($merged_values);
702  
703 1001 my (@covered, %seen, @fc_exceptions, $ci);
704  
705 1001 for my $c_name ( sort {
706 691 ▶ $a eq 'primary' ? -1
Branch: 2 branches
BranchTrueFalseTotal
$a eq 'primary' ? : 154 537 691
$b eq 'primary' ? : 153 384 537
707 : $b eq 'primary' ? 1
708 : $a cmp $b
709 } $rsrc->unique_constraint_names) {
710  
711 1445 my @c_cols = $rsrc->unique_constraint_columns($c_name);
712 1445 ▶ next unless @c_cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @c_cols 0 1445 1445
713  
714 1445 ▶ next if $seen{ join "\x00", sort @c_cols }++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{CORE::join "\0", sort(@c_cols)}++ 136 1309 1445
715  
716 next unless @c_cols == grep {
717 1309 ▶ exists $fixed->{$_}
Branch: 1 branch
BranchTrueFalseTotal
unless @c_cols == grep({exists $fixed->{$_} and defined $fixed->{$_} and !ref($fixed->{$_}) || &is_plain_value($fixed->{$_}) and $fixed->{$_} ne \"1 = 0";} @c_cols) 324 985 1309
718 and defined $fixed->{$_}
719 and ( ! ref $fixed->{$_} or is_plain_value $fixed->{$_} )
720 1479 ▶ and $fixed->{$_} ne UNRESOLVABLE_CONDITION
Condition58%7/12
exists $fixed->{$_} && defined $fixed->{$_} && (!ref($fixed->{$_}) || &is_plain_value($fixed->{$_})) && $fixed->{$_} ne \'1 = 0'
!ll&&!rl&&r
41101068
exists $fixed->{$_} and defined $fixed->{$_} and !ref($fixed->{$_}) || &is_plain_value($fixed->{$_})
!ll&&!rl&&r
41101068
exists $fixed->{$_} and defined $fixed->{$_}
!ll&&!rl&&r
41101068
not ref $fixed->{$_} or &is_plain_value($fixed->{$_})
l!l&&r!l&&!r
106800
MC/DC20%1/5
exists $fixed->{$_} && defined $fixed->{$_} && (!ref($fixed->{$_}) || &is_plain_value($fixed->{$_})) && $fixed->{$_} ne \'1 = 0'
exists $fixed->{$_} defined $fixed->{$_} not ref $fixed->{$_} &is_plain_value($fixed->{$_}) $fixed->{$_} ne \'1 = 0'
Truth table28%2/7
A and B and not(C) or D && E
A= exists $fixed->{$_}B= defined $fixed->{$_}C= not ref $fixed->{$_}D= &is_plain_value($fixed->{$_})E= $fixed->{$_} ne \'1 = 0'
ABCDEresult
0XXXX0
10XXX0
1100X0
111X00
110100
111X11
110111
721 } @c_cols;
722  
723 # FilterColumn values are not usable for a lookup; that throw has to be
724 # seen here
725 985 ▶ try {
Subroutine __ANON__: called CC=2 SCAR=7.1
726 985 ▶ $rsrc->_minimal_valueset_satisfying_constraint(
Condition66%2/3
$ci ||= $rsrc->columns_info
l!l&&r!l&&!r
179680
MC/DC0%0/2
$ci ||= $rsrc->columns_info
$ci $rsrc->columns_info
Truth table66%2/3
A ||= B
A= $ciB= $rsrc->columns_info
ABresult
1X1
011
000
727 constraint_name => $c_name,
728 values => $merged_values,
729 columns_info => ($ci ||= $rsrc->columns_info),
730 );
731 985 push @covered, $c_name;
732 }
733 0 ▶ catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
734 0 ▶ push @fc_exceptions, $_ if $_ =~ /\bFilterColumn\b/;
Branch: 1 branch
BranchTrueFalseTotal
if $_ =~ /\bFilterColumn\b/ 0 0 0
735 985 };
736 }
737  
738 0 ▶ $self->throw_exception(join "; ", map { $_ =~ /(.*) at .+ line \d+$/s } @fc_exceptions)
Branch: 1 branch
BranchTrueFalseTotal
if not @covered and @fc_exceptions 0 1001 1001
Condition66%2/3
not @covered and @fc_exceptions
!ll&&!rl&&r
968330
MC/DC0%0/2
not @covered and @fc_exceptions
not @covered @fc_exceptions
Truth table66%2/3
not(A) and B
A= not @coveredB= @fc_exceptions
ABresult
0X0
100
111
739 if ! @covered and @fc_exceptions;
740  
741 1001 return @covered;
742 }
743  
744 # Throws unless the condition covers a unique constraint; returns the covered
745 # constraint names. $caller names the public method in the message.
746 955 ▶sub _assert_covered_constraint {
Subroutine _assert_covered_constraint: called CC=4 SCAR=13.9
747 955 my ($self, $call_cond, $merged_values, $caller) = @_;
748  
749 955 my @covered = $self->_covered_constraints($merged_values);
750 955 ▶ return @covered if @covered;
Branch: 1 branch
BranchTrueFalseTotal
if @covered 934 21 955
751  
752 21 my $rsrc = $self->result_source;
753 21 my %constraints = $rsrc->unique_constraints;
754  
755 $self->throw_exception(sprintf(
756 "%s() needs a condition that gives every column of one unique constraint "
757 . "of source '%s' a concrete value. Columns given: %s. Unique constraints: %s. "
758 . "To look rows up by any other condition use search(...)->single",
759 $caller,
760 $rsrc->source_name,
761 21 ▶ ( join(', ', sort map { "'$_'" } keys %$call_cond) || '(none)' ),
Condition50%1/2
CORE::join('; ', map({"$_ (" . CORE::join(', ', @{$constraints{$_};}) . ')';} sort(keys %constraints))) || '(none)'
l!l
210
MC/DC0%0/1
CORE::join('; ', map({"$_ (" . CORE::join(', ', @{$constraints{$_};}) . ')';} sort(keys %constraints))) || '(none)'
CORE::join('; ', map({"$_ (" . CORE::join(', ', @{$constraints{$_};}) . ')';} sort(keys %constraints)))
Truth table50%1/2
A
A= CORE::join('; ', map({"$_ (" . CORE::join(', ', @{$constraints{$_};}) . ')';} sort(keys %constraints)))
Aresult
11
00
762 21 ▶ ( join('; ', map { "$_ (" . join(', ', @{$constraints{$_}}) . ')' } sort keys %constraints) || '(none)' ),
Condition100%2/2
CORE::join(', ', sort(map({"'${_}'";} keys %$call_cond))) || '(none)'
l!l
201
MC/DC100%1/1
CORE::join(', ', sort(map({"'${_}'";} keys %$call_cond))) || '(none)'
CORE::join(', ', sort(map({"'${_}'";} keys %$call_cond)))
Truth table100%2/2
A
A= CORE::join(', ', sort(map({"'${_}'";} keys %$call_cond)))
Aresult
11
00
763 ));
764 }
765  
766 # The find() a find_or_* / update_or_* method runs: only the columns of the one
767 # covered unique constraint (the one named by key => ...) go into the lookup;
768 # the remaining values are data for create or update. Several covered
769 # constraints without key throw, none covered throws. Returns
770 # ($lookup_cond, $lookup_attrs, $is_miss).
771 922 ▶sub _lookup_for_write {
Subroutine _lookup_for_write: called CC=6 SCAR=18.0
772 922 my ($self, $cond, $attrs, $caller) = @_;
773  
774 922 my $call_cond = $self->_lookup_data($cond);
775 922 ▶ return (undef, $attrs, 1) if $self->_fold_relation_conditions($call_cond);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_fold_relation_conditions($call_cond) 0 922 922
776  
777 922 my $c_name;
778 922 ▶ if (exists $attrs->{key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $attrs->{'key'}) { } 46 876 922
779 $c_name = defined $attrs->{key}
780 ? $attrs->{key}
781 46 ▶ : $self->throw_exception("An undefined 'key' resultset attribute makes no sense")
Branch: 1 branch
BranchTrueFalseTotal
defined $attrs->{'key'} ? : 46 0 46
782 ;
783 }
784 else {
785 876 my @covered = $self->_assert_covered_constraint(
786 $call_cond, ($self->_merge_with_rscond($call_cond))[0], $caller,
787 );
788  
789 $self->throw_exception(sprintf(
790 "%s() condition covers the unique constraints %s -- pass key => '...' to name the one to look up",
791 866 ▶ $caller, join(' and ', map { "'$_'" } @covered),
Branch: 1 branch
BranchTrueFalseTotal
if @covered > 1 8 858 866
792 )) if @covered > 1;
793  
794 858 $c_name = $covered[0];
795 }
796  
797 my %lookup = map {
798 904 ▶ exists $call_cond->{$_} ? ( $_ => $call_cond->{$_} ) : ()
Branch: 1 branch
BranchTrueFalseTotal
exists $call_cond->{$_} ? : 909 7 916
799 } $self->result_source->unique_constraint_columns($c_name);
800  
801 904 return (\%lookup, $self->_read_modify_write_attrs({ %$attrs, key => $c_name }), 0);
802 }
803  
804 # The read of a read-then-write call goes where the write goes. The storage
805 # names the pool through _read_pool_for_read_modify_write (nothing by default,
806 # 'master' for DBIO::Replicated::Storage); a force_pool the caller gave stays.
807 905 ▶sub _read_modify_write_attrs {
Subroutine _read_modify_write_attrs: called CC=3 SCAR=11.0
808 905 my ($self, $attrs) = @_;
809  
810 905 my $pool = $self->result_source->storage->_read_pool_for_read_modify_write;
811 905 ▶ $attrs->{force_pool} = $pool if defined $pool and ! exists $attrs->{force_pool};
Branch: 1 branch
BranchTrueFalseTotal
if defined $pool and not exists $attrs->{"force_pool"} 5 900 905
Condition66%2/3
defined $pool and not exists $attrs->{"force_pool"}
!ll&&!rl&&r
90005
MC/DC50%1/2
defined $pool and not exists $attrs->{"force_pool"}
defined $pool not exists $attrs->{"force_pool"}
Truth table66%2/3
A and not(B)
A= defined $poolB= not exists $attrs->{"force_pool"}
ABresult
0X0
100
111
812  
813 905 return $attrs;
814 }
815  
816 # The part of the data that identifies a row, as a copy: the alias removed from
817 # the keys (me.title is title), and without the lists under relationship names,
818 # which are the data of rows created along with this one (multi-create).
819 962 ▶sub _lookup_data {
Subroutine _lookup_data: called CC=3 SCAR=11.0
820 962 my ($self, $data) = @_;
821  
822 962 my $rsrc = $self->result_source;
823 return $self->_remove_alias(
824 { map {
825 1088 ▶ ( ref $data->{$_} eq 'ARRAY' and $rsrc->relationship_info($_) ) ? () : ( $_ => $data->{$_} )
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{$_} eq 'ARRAY' && $rsrc->relationship_info($_) ? : 2 1086 1088
Condition66%2/3
ref $data->{$_} eq "ARRAY" and $rsrc->relationship_info($_)
!ll&&!rl&&r
108602
MC/DC50%1/2
ref $data->{$_} eq "ARRAY" and $rsrc->relationship_info($_)
ref $data->{$_} eq "ARRAY" $rsrc->relationship_info($_)
Truth table66%2/3
A and B
A= ref $data->{$_} eq "ARRAY"B= $rsrc->relationship_info($_)
ABresult
0X0
100
111
826 } keys %$data },
827 $self->{attrs}{alias},
828 962 );
829 }
830  
831 # The existing row that nested multi-create data identifies, if any: the data
832 # is looked up by the columns of the unique constraints it covers (all of them,
833 # ANDed); data covering none identifies nothing and finds no row, so the caller
834 # creates it. Used by the row layer, which builds related rows from data it
835 # does not control.
836 40 ▶sub _find_identified {
Subroutine _find_identified: called CC=4 SCAR=14.0
837 40 my ($self, $data) = @_;
838  
839 40 my $call_cond = $self->_lookup_data($data);
840  
841 40 ▶ return undef if $self->_fold_relation_conditions($call_cond);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_fold_relation_conditions($call_cond) 0 40 40
842  
843 40 ▶ my @covered = $self->_covered_constraints(($self->_merge_with_rscond($call_cond))[0])
Branch: 1 branch
BranchTrueFalseTotal
my(@covered) = $self->_covered_constraints(($self->_merge_with_rscond($call_cond))[0]) or return undef 29 11 40
844 or return undef;
845  
846 my %lookup = map {
847 32 ▶ exists $call_cond->{$_} ? ( $_ => $call_cond->{$_} ) : ()
Branch: 1 branch
BranchTrueFalseTotal
exists $call_cond->{$_} ? : 32 0 32
848 29 } map { $self->result_source->unique_constraint_columns($_) } @covered;
849  
850 29 return $self->find(\%lookup);
851 }
852  
853 # find() for the find_or_* / update_or_* family, see _lookup_for_write
854 898 ▶sub _find_for_write {
Subroutine _find_for_write: called CC=3 SCAR=11.0
855 898 my ($self, $cond, $attrs, $caller, $lookup_cols) = @_;
856  
857 898 my ($lookup, $lattrs, $is_miss) = $self->_lookup_for_write($cond, $attrs, $caller);
858 880 ▶ return undef if $is_miss;
Branch: 1 branch
BranchTrueFalseTotal
if $is_miss 0 880 880
859  
860 880 ▶ @$lookup_cols = keys %$lookup if $lookup_cols;
Branch: 1 branch
BranchTrueFalseTotal
if $lookup_cols 845 35 880
861  
862 880 return $self->find($lookup, $lattrs);
863 }
864  
865 # What update_or_create / update_or_new hand to update() for the row they
866 # found (ADR 0071): the caller's data may not contradict the resultset's
867 # condition, and the columns of the lookup, which name the row and assign
868 # nothing, are left out where they are guarded.
869 29 ▶sub _update_data_for_found_row {
Subroutine _update_data_for_found_row: called CC=5 SCAR=16.2
870 29 my ($self, $cond, $lookup_cols) = @_;
871  
872 29 $self->_merge_with_rscond($cond, 1);
873  
874 27 my $columns = $self->result_source->_columns;
875 27 ▶ my %lookup = map { $_ => 1 } @{ $lookup_cols || [] };
Condition50%1/2
$lookup_cols || []
l!l
270
MC/DC0%0/1
$lookup_cols || []
$lookup_cols
Truth table50%1/2
A
A= $lookup_cols
Aresult
11
00
876  
877 return { map {
878 27 ( $lookup{$_} and $columns->{$_} and $columns->{$_}{is_guarded} )
879 ? ()
880 63 ▶ : ( $_ => $cond->{$_} )
Branch: 1 branch
BranchTrueFalseTotal
$lookup{$_} && $columns->{$_} && $columns->{$_}{'is_guarded'} ? : 1 62 63
Condition83%5/6
$lookup{$_} and $columns->{$_} and $columns->{$_}{"is_guarded"}
!ll&&!rl&&r
35271
$lookup{$_} and $columns->{$_}
!ll&&!rl&&r
35028
MC/DC66%2/3
$lookup{$_} and $columns->{$_} and $columns->{$_}{"is_guarded"}
$lookup{$_} $columns->{$_} $columns->{$_}{"is_guarded"}
Truth table75%3/4
A and B and C
A= $lookup{$_}B= $columns->{$_}C= $columns->{$_}{"is_guarded"}
ABCresult
0XX0
10X0
1100
1111
881 } keys %$cond };
882 }
883  
884 24 ▶sub _find_for_write_async {
Subroutine _find_for_write_async: called CC=4 SCAR=15.0
885 24 my ($self, $cond, $attrs, $caller, $lookup_cols) = @_;
886  
887 24 my ($lookup, $lattrs, $is_miss) = $self->_lookup_for_write($cond, $attrs, $caller);
888 24 ▶ @$lookup_cols = keys %$lookup if $lookup_cols and ! $is_miss;
Branch: 1 branch
BranchTrueFalseTotal
if $lookup_cols and not $is_miss 12 12 24
Condition66%2/3
$lookup_cols and not $is_miss
!ll&&!rl&&r
12012
MC/DC50%1/2
$lookup_cols and not $is_miss
$lookup_cols not $is_miss
Truth table66%2/3
A and not(B)
A= $lookup_colsB= not $is_miss
ABresult
0X0
100
111
889  
890 return $is_miss
891 0 ▶ ? $self->_rs_run_async('find', sub { $_[1]->done(undef) }, sub { undef })
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
892 24 ▶ : $self->find_async($lookup, $lattrs);
Branch: 1 branch
BranchTrueFalseTotal
$is_miss ? : 0 24 24
893 }
894  
895 # Resolve a related-object sub-condition down to a condition on THIS source's
896 # own columns, exactly as find() does when folding a related sub-hash into the
897 # main search. Returns ($resolved_cond, $crosstable): $crosstable is true when
898 # the relationship cannot be reduced to a join-free condition on the main table
899 # at all. Note that even when $crosstable is false the individual values in
900 # $resolved_cond may be undef/UNRESOLVABLE_CONDITION -- e.g. a has_many searched
901 # by its own non-key columns resolves join-free to { self_pk => undef }, which
902 # does NOT pin a concrete foreign key. This is the single resolution seam shared
903 # by find()'s complex-condition guard and update_or_create()'s _find_lookup_cond
904 # lookup builder; each caller interprets the result for itself (ADR 0034).
905 20 ▶sub _resolve_related_cond {
Subroutine _resolve_related_cond: called CC=2 SCAR=7.1
906 20 my ($self, $rsrc, $rel_name, $val) = @_;
907  
908 20 ▶ my $relinfo = $rsrc->relationship_info($rel_name)
Branch: 1 branch
BranchTrueFalseTotal
my $relinfo = $rsrc->relationship_info($rel_name) or return undef, undef 20 0 20
909 or return (undef, undef);
910  
911 20 return $rsrc->_resolve_condition( $relinfo->{cond}, $val, $rel_name, $rel_name );
912 }
913  
914 # Predicate over ( $resolved_cond, $crosstable ) as returned by
915 # _resolve_related_cond: true only when the relation reduces to a concrete,
916 # fully-defined condition on THIS source's own columns (a resolvable
917 # belongs_to). A crosstable relation, a non-hashref resolution, an empty
918 # condition, or any undef / UNRESOLVABLE_CONDITION value counts as non-concrete
919 # -- folding such a condition into a lookup would clobber real columns with an
920 # undef foreign key. Shared by find()'s guard and update_or_create()'s lookup-
921 # condition builder, so the two agree on what "usable in a lookup" means (ADR
922 # 0034).
923 19 ▶sub _related_cond_is_concrete {
Subroutine _related_cond_is_concrete: called CC=4 SCAR=16.4
924 19 my ($self, $rel_cond, $crosstable) = @_;
925  
926 return
927 ! $crosstable
928 && ref $rel_cond eq 'HASH'
929 && keys %$rel_cond
930 19 ▶ && ! grep { ! defined $_ } values %$rel_cond;
Condition44%4/9
!$crosstable && ref $rel_cond eq 'HASH' && keys %$rel_cond && !grep({not defined $_;} values %$rel_cond)
!ll&&!rl&&r
0712
not $crosstable and ref $rel_cond eq "HASH" and keys %$rel_cond
!ll&&!rl&&r
0019
not $crosstable and ref $rel_cond eq "HASH"
!ll&&!rl&&r
0019
MC/DC25%1/4
!$crosstable && ref $rel_cond eq 'HASH' && keys %$rel_cond && !grep({not defined $_;} values %$rel_cond)
not $crosstable ref $rel_cond eq "HASH" keys %$rel_cond !grep({not defined $_;} values %$rel_cond)
Truth table40%2/5
not(A) and B and C && not(D)
A= not $crosstableB= ref $rel_cond eq "HASH"C= keys %$rel_condD= !grep({not defined $_;} values %$rel_cond)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
931 }
932  
933 1079 ▶sub _qualify_cond_columns {
Subroutine _qualify_cond_columns: called CC=3 SCAR=11.1
934 1079 my ($self, $cond, $alias) = @_;
935  
936 1079 my %aliased = %$cond;
937 1079 for (keys %aliased) {
938 1096 ▶ $aliased{"$alias.$_"} = delete $aliased{$_}
Branch: 1 branch
BranchTrueFalseTotal
unless $_ =~ /\./ 1096 0 1096
939 if $_ !~ /\./;
940 }
941  
942 1079 return \%aliased;
943 }
944  
945 0 ▶sub _build_unique_cond {
Subroutine _build_unique_cond: not called CC=1 SCAR=6.9
946 0 carp_unique sprintf
947 '_build_unique_cond is a private method, and moreover is about to go '
948 . 'away. Please contact the development team at %s if you believe you '
949 . 'have a genuine use for this method, in order to discuss alternatives.',
950 help_url,
951 ;
952  
953 0 my ($self, $constraint_name, $cond, $croak_on_null) = @_;
954  
955 0 $self->result_source->_minimal_valueset_satisfying_constraint(
956 constraint_name => $constraint_name,
957 values => $cond,
958 carp_on_nulls => !$croak_on_null
959 );
960 }
961  
962  
963 19 ▶sub search_related {
Subroutine search_related: called CC=2 SCAR=6.9
Pod documented
964 19 my ($self, $rel, @args) = @_;
965  
966 19 ▶ assert_no_list_context('->search_related') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 18 19
967  
968 18 return $self->related_resultset($rel)->search(@args);
969 }
970  
971  
972 0 ▶sub search_related_rs {
Subroutine search_related_rs: not called CC=1 SCAR=6.9
Pod documented
973 0 return shift->related_resultset(shift)->search_rs(@_);
974 }
975  
976  
977 1758 ▶sub cursor {
Subroutine cursor: called CC=2 SCAR=6.9
Pod documented
978 1758 my $self = shift;
979  
980 1758 ▶ return $self->{cursor} ||= do {
Condition100%3/3
$self->{"cursor"} ||= do { my $attrs = $self->_resolved_attrs; $self->result_source->storage->select($attrs->{"from"}, $attrs->{"select"}, $attrs->{"where"}, $attrs) }
l!l&&r!l&&!r
7749822
MC/DC100%2/2
$self->{"cursor"} ||= do { my $attrs = $self->_resolved_attrs; $self->result_source->storage->select($attrs->{"from"}, $attrs->{"select"}, $attrs->{"where"}, $attrs) }
$self->{"cursor"} do { my $attrs = $self->_resolved_attrs; $self->result_source->storage->select($attrs->{"from"}, $attrs->{"select"}, $attrs->{"where"}, $attrs) }
Truth table100%3/3
A ||= B
A= $self->{"cursor"}B= do { my $attrs = $self->_resolved_attrs; $self->result_source->storage->select($attrs->{"from"}, $attrs->{"select"}, $attrs->{"where"}, $attrs) }
ABresult
1X1
011
000
981 984 my $attrs = $self->_resolved_attrs;
982 $self->result_source->storage->select(
983 984 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
984 );
985 };
986 }
987  
988  
989 1093 ▶sub single {
Subroutine single: called CC=3 SCAR=11.1
Pod documented
990 1093 my ($self, $where) = @_;
991 1093 ▶ if(@_ > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2) 0 1093 1093
992 0 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
993 }
994  
995 1093 my @select_args = $self->_single_select_args($where);
996  
997 1093 my $data = [ $self->result_source->storage->select_single(@select_args) ];
998  
999 1093 ▶ return undef unless @$data;
Branch: 1 branch
BranchTrueFalseTotal
unless @$data 930 163 1093
1000 163 $self->{_stashed_rows} = [ $data ];
1001 163 $self->_construct_results->[0];
1002 }
1003  
1004 # Build the (from, select, where, attrs) argument list for the single-row
1005 # storage select that backs both single() and single_async(). Factored out so
1006 # the async path issues the identical query (and the same has_many-collapse
1007 # assertion) the synchronous path does.
1008 1158 ▶sub _single_select_args {
Subroutine _single_select_args: called CC=5 SCAR=17.8
1009 1158 my ($self, $where) = @_;
1010  
1011 1158 my $attrs = { %{$self->_resolved_attrs} };
1012  
1013 $self->throw_exception(
1014 'single() can not be used on resultsets collapsing a has_many. Use find( \%cond ) or next() instead'
1015 1158 ▶ ) if $attrs->{collapse};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"collapse"} 0 1158 1158
1016  
1017 1158 ▶ if ($where) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where) 2 1156 1158
1018 2 ▶ if (defined $attrs->{where}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attrs->{'where'}) { } 0 2 2
1019 $attrs->{where} = {
1020 '-and' =>
1021 0 ▶ [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 0 0 0
1022 0 $where, delete $attrs->{where} ]
1023 };
1024 } else {
1025 2 $attrs->{where} = $where;
1026 }
1027 }
1028  
1029 1158 return ($attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs);
1030 }
1031  
1032  
1033 259 ▶sub get_column {
Subroutine get_column: called CC=1 SCAR=0.0
Pod documented
1034 259 my ($self, $column) = @_;
1035 259 my $new = DBIO::ResultSetColumn->new($self, $column);
1036 258 return $new;
1037 }
1038  
1039  
1040 3 ▶sub search_like {
Subroutine search_like: called CC=6 SCAR=18.7
Pod documented
1041 3 my $class = shift;
1042 3 ▶ assert_no_list_context('->search_like') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 2 1 3
1043 1 carp_unique (
1044 'search_like() is deprecated.'
1045 .' Instead use ->search({ x => { -like => "y%" } })'
1046 .' (note the outer pair of {}s - they are important!)'
1047 );
1048 1 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 0 1 1
Condition33%1/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
100
MC/DC0%0/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table33%1/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
1049 1 ▶ my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 1 0 1
1050 1 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
1051 1 return $class->search_rs($query, { %$attrs });
1052 }
1053  
1054  
1055 1 ▶sub slice {
Subroutine slice: called CC=4 SCAR=24.2
Pod documented
1056 1 my ($self, $min, $max) = @_;
1057  
1058 1 ▶ assert_no_list_context('->slice') if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 1 0 1
1059  
1060 0 my $attrs = {}; # = { %{ $self->{attrs} || {} } };
1061 0 ▶ $attrs->{offset} = $self->{attrs}{offset} || 0;
Condition0%0/2
$self->{'attrs'}{'offset'} || 0
l!l
00
MC/DC0%0/1
$self->{'attrs'}{'offset'} || 0
$self->{'attrs'}{'offset'}
Truth table0%0/2
A
A= $self->{'attrs'}{'offset'}
Aresult
11
00
1062 0 $attrs->{offset} += $min;
1063 0 ▶ $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
Branch: 1 branch
BranchTrueFalseTotal
$max ? : 0 0 0
1064 0 return $self->search_rs(undef, $attrs);
1065 }
1066  
1067  
1068 111 ▶sub next {
Subroutine next: called CC=7 SCAR=23.7
Pod documented
1069 111 my ($self) = @_;
1070  
1071 111 ▶ if (my $cache = $self->get_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = $self->get_cache) 0 111 111
1072 0 ▶ $self->{all_cache_position} ||= 0;
Condition0%0/2
$self->{"all_cache_position"} ||= 0
l!l
00
MC/DC0%0/1
$self->{"all_cache_position"} ||= 0
$self->{"all_cache_position"}
Truth table0%0/2
A
A= $self->{"all_cache_position"}
Aresult
11
00
1073 0 return $cache->[$self->{all_cache_position}++];
1074 }
1075  
1076 111 ▶ if ($self->{attrs}{cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"attrs"}{"cache"}) 0 111 111
1077 0 delete $self->{pager};
1078 0 $self->{all_cache_position} = 1;
1079 0 return ($self->all)[0];
1080 }
1081  
1082 0 ▶ return shift(@{$self->{_stashed_results}}) if @{ $self->{_stashed_results}||[] };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"_stashed_results"} or [];} 0 111 111
Condition100%2/2
$self->{'_stashed_results'} || []
l!l
11100
MC/DC100%1/1
$self->{'_stashed_results'} || []
$self->{'_stashed_results'}
Truth table100%2/2
A
A= $self->{'_stashed_results'}
Aresult
11
00
1083  
1084 111 ▶ $self->{_stashed_results} = $self->_construct_results
Branch: 1 branch
BranchTrueFalseTotal
$self->{"_stashed_results"} = $self->_construct_results or return undef 96 13 109
1085 or return undef;
1086  
1087 96 return shift @{$self->{_stashed_results}};
1088 }
1089  
1090 # Constructs as many results as it can in one pass while respecting
1091 # cursor laziness. Several modes of operation:
1092 #
1093 # * Always builds everything present in @{$self->{_stashed_rows}}
1094 # * If called with $fetch_all true - pulls everything off the cursor and
1095 # builds all result structures (or objects) in one pass
1096 # * If $self->_resolved_attrs->{collapse} is true, checks the order_by
1097 # and if the resultset is ordered properly by the left side:
1098 # * Fetches stuff off the cursor until the "master object" changes,
1099 # and saves the last extra row (if any) in @{$self->{_stashed_rows}}
1100 # OR
1101 # * Just fetches, and collapses/constructs everything as if $fetch_all
1102 # was requested (there is no other way to collapse except for an
1103 # eager cursor)
1104 # * If no collapse is requested - just get the next row, construct and
1105 # return
1106 1059 ▶sub _construct_results {
Subroutine _construct_results: called CC=75 SCAR=51.6
1107 1059 my ($self, $fetch_all) = @_;
1108  
1109 1059 my $rsrc = $self->result_source;
1110 1059 my $attrs = $self->_resolved_attrs;
1111  
1112 1058 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not $fetch_all || $attrs->{"order_by"} and $attrs->{"collapse"} and my(@pcols) = $rsrc->primary_columns) 1 1057 1058
Condition88%8/9
not $fetch_all || $attrs->{"order_by"} and $attrs->{"collapse"} and my(@pcols) = $rsrc->primary_columns
!ll&&!rl&&r
105701
not $fetch_all || $attrs->{"order_by"} and $attrs->{"collapse"}
!ll&&!rl&&r
7722851
$fetch_all || $attrs->{'order_by'}
l!l&&r!l&&!r
73537286
MC/DC75%3/4
not $fetch_all || $attrs->{"order_by"} and $attrs->{"collapse"} and my(@pcols) = $rsrc->primary_columns
$fetch_all $attrs->{'order_by'} $attrs->{"collapse"} my(@pcols) = $rsrc->primary_columns
Truth table80%4/5
not(A || B) and C and D
A= $fetch_allB= $attrs->{'order_by'}C= $attrs->{"collapse"}D= my(@pcols) = $rsrc->primary_columns
ABCDresult
1XXX0
01XX0
000X0
00100
00111
1113 ! $fetch_all
1114 and
1115 ! $attrs->{order_by}
1116 and
1117 $attrs->{collapse}
1118 and
1119 my @pcols = $rsrc->primary_columns
1120 ) {
1121 # default order for collapsing unless the user asked for something
1122 1 $attrs->{order_by} = [ map { join '.', $attrs->{alias}, $_} @pcols ];
1123 1 $attrs->{_ordered_for_collapse} = 1;
1124 1 $attrs->{_order_is_artificial} = 1;
1125 }
1126  
1127 # this will be used as both initial raw-row collector AND as a RV of
1128 # _construct_results. Not regrowing the array twice matters a lot...
1129 # a surprising amount actually
1130 1058 my $rows = delete $self->{_stashed_rows};
1131  
1132 1058 my $cursor; # we may not need one at all
1133  
1134 1058 my $did_fetch_all = $fetch_all;
1135  
1136 1058 ▶ if ($fetch_all) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fetch_all) { } 735 323 1058
elsif ($attrs->{'collapse'}) { } 5 318 323
1137 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1138 735 ▶ $rows = [ ($rows ? @$rows : ()), $self->cursor->all ];
Branch: 1 branch
BranchTrueFalseTotal
$rows ? : 0 735 735
1139 }
1140 elsif( $attrs->{collapse} ) {
1141  
1142 # a cursor will need to be closed over in case of collapse
1143 5 $cursor = $self->cursor;
1144  
1145 $attrs->{_ordered_for_collapse} = (
1146 (
1147 $attrs->{order_by}
1148 and
1149 $rsrc->schema
1150 ->storage
1151 ->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
1152 ) ? 1 : 0
1153 4 ▶ ) unless defined $attrs->{_ordered_for_collapse};
Branch: 2 branches
BranchTrueFalseTotal
unless defined $attrs->{"_ordered_for_collapse"} 1 3 4
$attrs->{'order_by'} && $rsrc->schema->storage->_extract_colinfo_of_stable_main_source_order_by_portion($attrs) ? : 1 0 1
Condition33%1/3
$attrs->{"order_by"} and $rsrc->schema->storage->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
!ll&&!rl&&r
001
MC/DC0%0/2
$attrs->{"order_by"} and $rsrc->schema->storage->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
$attrs->{"order_by"} $rsrc->schema->storage->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
Truth table33%1/3
A and B
A= $attrs->{"order_by"}B= $rsrc->schema->storage->_extract_colinfo_of_stable_main_source_order_by_portion($attrs)
ABresult
0X0
100
111
1154  
1155 4 ▶ if (! $attrs->{_ordered_for_collapse}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attrs->{"_ordered_for_collapse"}) 0 4 4
1156 0 $did_fetch_all = 1;
1157  
1158 # instead of looping over ->next, use ->all in stealth mode
1159 # *without* calling a ->reset afterwards
1160 0 ▶ if (! $cursor->is_exhausted) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cursor->is_exhausted) 0 0 0
1161 0 ▶ $rows = [ ($rows ? @$rows : ()), $cursor->all ];
Branch: 1 branch
BranchTrueFalseTotal
$rows ? : 0 0 0
1162 0 $cursor->mark_exhausted;
1163 }
1164 }
1165 }
1166  
1167 1057 ▶ if (! $did_fetch_all and ! @{$rows||[]} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($did_fetch_all or @{$rows or [];}) 108 949 1057
Condition100%5/5
$did_fetch_all or @{$rows or [];}
l!l&&r!l&&!r
735214108
$rows || []
l!l
215107
MC/DC100%2/2
$did_fetch_all or @{$rows or [];}
$did_fetch_all @{$rows or [];}
MC/DC100%1/1
$rows || []
$rows
Truth table100%3/3
A or B
A= $did_fetch_allB= @{$rows or [];}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $rows
Aresult
11
00
1168 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1169 108 ▶ $cursor ||= $self->cursor;
Condition66%2/3
$cursor ||= $self->cursor
l!l&&r!l&&!r
31050
MC/DC0%0/2
$cursor ||= $self->cursor
$cursor $self->cursor
Truth table66%2/3
A ||= B
A= $cursorB= $self->cursor
ABresult
1X1
011
000
1170 108 ▶ if (scalar (my @r = $cursor->next) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar(my(@r) = $cursor->next)) 95 13 108
1171 95 $rows = [ \@r ];
1172 }
1173 }
1174  
1175 1057 ▶ return undef unless @{$rows||[]};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$rows or [];} 581 476 1057
Condition100%2/2
$rows || []
l!l
104512
MC/DC100%1/1
$rows || []
$rows
Truth table100%2/2
A
A= $rows
Aresult
11
00
1176  
1177 # sanity check - people are too clever for their own good
1178 476 ▶ if ($attrs->{collapse} and my $aliastypes = $attrs->{_last_sqlmaker_alias_map} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"collapse"} and my $aliastypes = $attrs->{"_last_sqlmaker_alias_map"}) 12 464 476
Condition66%2/3
$attrs->{"collapse"} and my $aliastypes = $attrs->{"_last_sqlmaker_alias_map"}
!ll&&!rl&&r
464012
MC/DC50%1/2
$attrs->{"collapse"} and my $aliastypes = $attrs->{"_last_sqlmaker_alias_map"}
$attrs->{"collapse"} my $aliastypes = $attrs->{"_last_sqlmaker_alias_map"}
Truth table66%2/3
A and B
A= $attrs->{"collapse"}B= my $aliastypes = $attrs->{"_last_sqlmaker_alias_map"}
ABresult
0X0
100
111
1179  
1180 12 my $multiplied_selectors;
1181 12 for my $sel_alias ( grep { $_ ne $attrs->{alias} } keys %{ $aliastypes->{selecting} } ) {
1182 12 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($aliastypes->{"multiplying"}{$sel_alias} or $aliastypes->{"premultiplied"}{$sel_alias}) 12 0 12
Condition33%1/3
$aliastypes->{"multiplying"}{$sel_alias} or $aliastypes->{"premultiplied"}{$sel_alias}
l!l&&r!l&&!r
1200
MC/DC0%0/2
$aliastypes->{"multiplying"}{$sel_alias} or $aliastypes->{"premultiplied"}{$sel_alias}
$aliastypes->{"multiplying"}{$sel_alias} $aliastypes->{"premultiplied"}{$sel_alias}
Truth table33%1/3
A or B
A= $aliastypes->{"multiplying"}{$sel_alias}B= $aliastypes->{"premultiplied"}{$sel_alias}
ABresult
1X1
011
000
1183 $aliastypes->{multiplying}{$sel_alias}
1184 or
1185 $aliastypes->{premultiplied}{$sel_alias}
1186 ) {
1187 12 $multiplied_selectors->{$_} = 1 for keys %{$aliastypes->{selecting}{$sel_alias}{-seen_columns}}
1188 }
1189 }
1190  
1191 12 for my $i (0 .. $#{$attrs->{as}} ) {
1192 120 my $sel = $attrs->{select}[$i];
1193  
1194 120 ▶ if (ref $sel eq 'SCALAR') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $sel eq 'SCALAR') { } 0 120 120
elsif (ref $sel eq 'REF' and ref $$sel eq 'ARRAY') { } 0 240 240
1195 0 $sel = $$sel;
1196 }
1197 ▶ elsif( ref $sel eq 'REF' and ref $$sel eq 'ARRAY' ) {
Condition33%1/3
ref $sel eq "REF" and ref $$sel eq "ARRAY"
!ll&&!rl&&r
12000
MC/DC0%0/2
ref $sel eq "REF" and ref $$sel eq "ARRAY"
ref $sel eq "REF" ref $$sel eq "ARRAY"
Truth table33%1/3
A and B
A= ref $sel eq "REF"B= ref $$sel eq "ARRAY"
ABresult
0X0
100
111
1198 0 $sel = $$sel->[0];
1199 }
1200  
1201 $self->throw_exception(
1202 'Result collapse not possible - selection from a has_many source redirected to the main object'
1203 120 ▶ ) if ($multiplied_selectors->{$sel} and $attrs->{as}[$i] !~ /\./);
Branch: 1 branch
BranchTrueFalseTotal
if $multiplied_selectors->{$sel} and not $attrs->{"as"}[$i] =~ /\./ 0 120 120
Condition66%2/3
$multiplied_selectors->{$sel} and not $attrs->{"as"}[$i] =~ /\./
!ll&&!rl&&r
48720
MC/DC0%0/2
$multiplied_selectors->{$sel} and not $attrs->{"as"}[$i] =~ /\./
$multiplied_selectors->{$sel} not $attrs->{"as"}[$i] =~ /\./
Truth table66%2/3
A and not(B)
A= $multiplied_selectors->{$sel}B= not $attrs->{"as"}[$i] =~ /\./
ABresult
0X0
100
111
1204 }
1205 }
1206  
1207 # hotspot - skip the setter
1208 476 my $res_class = $self->_result_class;
1209  
1210 476 ▶ my $inflator_cref = $self->{_result_inflator}{cref} ||= do {
Condition66%2/3
$self->{"_result_inflator"}{"cref"} ||= do { $res_class->can("inflate_result") or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method") }
l!l&&r!l&&!r
144620
MC/DC0%0/2
$self->{"_result_inflator"}{"cref"} ||= do { $res_class->can("inflate_result") or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method") }
$self->{"_result_inflator"}{"cref"} do { $res_class->can("inflate_result") or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method") }
Truth table66%2/3
A ||= B
A= $self->{"_result_inflator"}{"cref"}B= do { $res_class->can("inflate_result") or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method") }
ABresult
1X1
011
000
1211 462 ▶ $res_class->can ('inflate_result')
Condition33%1/3
$res_class->can('inflate_result') || $self->throw_exception("Inflator $res_class does not provide an inflate_result() method")
l!l&&r!l&&!r
46200
MC/DC0%0/2
$res_class->can('inflate_result') || $self->throw_exception("Inflator $res_class does not provide an inflate_result() method")
$res_class->can('inflate_result') $self->throw_exception("Inflator $res_class does not provide an inflate_result() method")
Truth table33%1/3
A || B
A= $res_class->can('inflate_result')B= $self->throw_exception("Inflator $res_class does not provide an inflate_result() method")
ABresult
1X1
011
000
1212 or $self->throw_exception("Inflator $res_class does not provide an inflate_result() method");
1213 };
1214  
1215 476 my $infmap = $attrs->{as};
1216  
1217 $self->{_result_inflator}{is_core_row} = ( (
1218 $inflator_cref
1219 ==
1220 ( \&DBIO::Row::inflate_result || die "No ::Row::inflate_result() - can't happen" )
1221 476 ▶ ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_core_row};
Branch: 2 branches
BranchTrueFalseTotal
unless defined $self->{"_result_inflator"}{"is_core_row"} 462 14 476
$inflator_cref == (\&DBIO::Row::inflate_result || die(q[No ::Row::inflate_result() - can't happen])) ? : 453 9 462
Condition50%1/2
\&DBIO::Row::inflate_result || die(q[No ::Row::inflate_result() - can't happen])
l!l
4620
MC/DC0%0/1
\&DBIO::Row::inflate_result || die(q[No ::Row::inflate_result() - can't happen])
\&DBIO::Row::inflate_result
Truth table50%1/2
A
A= \&DBIO::Row::inflate_result
Aresult
11
00
1222  
1223 $self->{_result_inflator}{is_hri} = ( (
1224 ! $self->{_result_inflator}{is_core_row}
1225 and
1226 $inflator_cref == (
1227 require DBIO::ResultClass::HashRefInflator
1228 &&
1229 DBIO::ResultClass::HashRefInflator->can('inflate_result')
1230 )
1231 476 ▶ ) ? 1 : 0 ) unless defined $self->{_result_inflator}{is_hri};
Branch: 2 branches
BranchTrueFalseTotal
unless defined $self->{"_result_inflator"}{"is_hri"} 462 14 476
!$self->{'_result_inflator'}{'is_core_row'} && $inflator_cref == (require DBIO::ResultClass::HashRefInflator && 'DBIO::ResultClass::HashRefInflator'->can('inflate_result')) ? : 6 456 462
Condition66%4/6
not $self->{"_result_inflator"}{"is_core_row"} and $inflator_cref == (require DBIO::ResultClass::HashRefInflator && "DBIO::ResultClass::HashRefInflator"->can("inflate_result"))
!ll&&!rl&&r
45336
require DBIO::ResultClass::HashRefInflator && 'DBIO::ResultClass::HashRefInflator'->can('inflate_result')
!ll&&!rl&&r
009
MC/DC100%2/2
not $self->{"_result_inflator"}{"is_core_row"} and $inflator_cref == (require DBIO::ResultClass::HashRefInflator && "DBIO::ResultClass::HashRefInflator"->can("inflate_result"))
not $self->{"_result_inflator"}{"is_core_row"} $inflator_cref == (require DBIO::ResultClass::HashRefInflator && "DBIO::ResultClass::HashRefInflator"->can("inflate_result"))
MC/DC0%0/2
require DBIO::ResultClass::HashRefInflator && 'DBIO::ResultClass::HashRefInflator'->can('inflate_result')
require DBIO::ResultClass::HashRefInflator 'DBIO::ResultClass::HashRefInflator'->can('inflate_result')
Truth table100%3/3
not(A) and B
A= not $self->{"_result_inflator"}{"is_core_row"}B= $inflator_cref == (require DBIO::ResultClass::HashRefInflator && "DBIO::ResultClass::HashRefInflator"->can("inflate_result"))
ABresult
0X0
100
111
Truth table33%1/3
A && B
A= require DBIO::ResultClass::HashRefInflatorB= 'DBIO::ResultClass::HashRefInflator'->can('inflate_result')
ABresult
0X0
100
111
1232  
1233  
1234 476 ▶ if ($attrs->{_simple_passthrough_construction}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{'_simple_passthrough_construction'}) { } 461 15 476
1235 # construct a much simpler array->hash folder for the one-table HRI cases right here
1236 461 ▶ if ($self->{_result_inflator}{is_hri}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_result_inflator'}{'is_hri'}) { } 7 454 461
elsif ($self->{'_result_inflator'}{'is_core_row'} and @$rows < 60) { } 451 3 454
1237 7 for my $r (@$rows) {
1238 7 $r = { map { $infmap->[$_] => $r->[$_] } 0..$#$infmap };
1239 }
1240 }
1241 # FIXME SUBOPTIMAL this is a very very very hot spot
1242 # while rather optimal we can *still* do much better, by
1243 # building a smarter Row::inflate_result(), and
1244 # switch to feeding it data via a much leaner interface
1245 #
1246 # crude unscientific benchmarking indicated the shortcut eval is not worth it for
1247 # this particular resultset size
1248 ▶ elsif ( $self->{_result_inflator}{is_core_row} and @$rows < 60 ) {
Condition66%2/3
$self->{"_result_inflator"}{"is_core_row"} and @$rows < 60
!ll&&!rl&&r
30451
MC/DC50%1/2
$self->{"_result_inflator"}{"is_core_row"} and @$rows < 60
$self->{"_result_inflator"}{"is_core_row"} @$rows < 60
Truth table66%2/3
A and B
A= $self->{"_result_inflator"}{"is_core_row"}B= @$rows < 60
ABresult
0X0
100
111
1249 451 for my $r (@$rows) {
1250 594 $r = $inflator_cref->($res_class, $rsrc, { map { $infmap->[$_] => $r->[$_] } (0..$#$infmap) } );
1251 }
1252 }
1253 else {
1254 eval sprintf (
1255 ( $self->{_result_inflator}{is_core_row}
1256 ? '$_ = $inflator_cref->($res_class, $rsrc, { %s }) for @$rows'
1257 # a custom inflator may be a multiplier/reductor - put it in direct list ctx
1258 : '@$rows = map { $inflator_cref->($res_class, $rsrc, { %s } ) } @$rows'
1259 ),
1260 3 ▶ ( join (', ', map { "\$infmap->[$_] => \$_->[$_]" } 0..$#$infmap ) )
Branch: 2 branches
BranchTrueFalseTotal
eval sprintf($self->{"_result_inflator"}{"is_core_row"} ? "\$_ = \$inflator_cref->(\$res_class, \$rsrc, { %s }) for \@\$rows" : "\@\$rows = map { \$inflator_cref->(\$res_class, \$rsrc, { %s } ) } \@\$rows", CORE::join(", ", map({"\$infmap->[$_] => \$_->[$_]";} 0 .. $infmap->$#*))) . '; 1' or die 3 0 3
$self->{'_result_inflator'}{'is_core_row'} ? : 0 3 3
1261 ) . '; 1' or die;
1262 }
1263 }
1264 else {
1265 my $parser_type =
1266 $self->{_result_inflator}{is_hri} ? 'hri'
1267 15 ▶ : $self->{_result_inflator}{is_core_row} ? 'classic_pruning'
Branch: 2 branches
BranchTrueFalseTotal
$self->{'_result_inflator'}{'is_hri'} ? : 0 15 15
$self->{'_result_inflator'}{'is_core_row'} ? : 15 0 15
1268 : 'classic_nonpruning'
1269 ;
1270  
1271 # $args and $attrs to _mk_row_parser are separated to delineate what is
1272 # core collapser stuff and what is dbic $rs specific
1273 13 @{$self->{_row_parser}{$parser_type}}{qw(cref nullcheck)} = $rsrc->_mk_row_parser({
1274 eval => 1,
1275 inflate_map => $infmap,
1276 collapse => $attrs->{collapse},
1277 premultiplied => $attrs->{_main_source_premultiplied},
1278 hri_style => $self->{_result_inflator}{is_hri},
1279 prune_null_branches => $self->{_result_inflator}{is_hri} || $self->{_result_inflator}{is_core_row},
1280 15 ▶ }, $attrs) unless $self->{_row_parser}{$parser_type}{cref};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_row_parser"}{$parser_type}{"cref"} 13 2 15
Condition33%1/3
$self->{'_result_inflator'}{'is_hri'} || $self->{'_result_inflator'}{'is_core_row'}
l!l&&r!l&&!r
0130
MC/DC0%0/2
$self->{'_result_inflator'}{'is_hri'} || $self->{'_result_inflator'}{'is_core_row'}
$self->{'_result_inflator'}{'is_hri'} $self->{'_result_inflator'}{'is_core_row'}
Truth table33%1/3
A || B
A= $self->{'_result_inflator'}{'is_hri'}B= $self->{'_result_inflator'}{'is_core_row'}
ABresult
1X1
011
000
1281  
1282 # column_info metadata historically hasn't been too reliable.
1283 # We need to start fixing this somehow (the collapse resolver
1284 # can't work without it). Add an explicit check for the *main*
1285 # result, hopefully this will gradually weed out such errors
1286 #
1287 # FIXME - this is a temporary kludge that reduces performance
1288 # It is however necessary for the time being
1289 15 my ($unrolled_non_null_cols_to_check, $err);
1290  
1291 15 ▶ if (my $check_non_null_cols = $self->{_row_parser}{$parser_type}{nullcheck} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $check_non_null_cols = $self->{"_row_parser"}{$parser_type}{"nullcheck"}) 12 3 15
1292  
1293 12 $err =
1294 'Collapse aborted due to invalid ResultSource metadata - the following '
1295 . 'selections are declared non-nullable but NULLs were retrieved: '
1296 ;
1297  
1298 12 my @violating_idx;
1299 12 COL: for my $i (@$check_non_null_cols) {
1300 12 ▶ ! defined $_->[$i] and push @violating_idx, $i and next COL for @$rows;
Branch: 1 branch
BranchTrueFalseTotal
not defined $_->[$i] and push @violating_idx, $i and next COL 0 19 19
Condition33%1/3
not defined $_->[$i] and push @violating_idx, $i
!ll&&!rl&&r
1900
MC/DC0%0/2
not defined $_->[$i] and push @violating_idx, $i
not defined $_->[$i] push @violating_idx, $i
Truth table33%1/3
not(A) and B
A= not defined $_->[$i]B= push @violating_idx, $i
ABresult
0X0
100
111
1301 }
1302  
1303 0 ▶ $self->throw_exception( $err . join (', ', map { "'$infmap->[$_]'" } @violating_idx ) )
Branch: 1 branch
BranchTrueFalseTotal
if @violating_idx 0 12 12
1304 if @violating_idx;
1305  
1306 12 $unrolled_non_null_cols_to_check = join (',', @$check_non_null_cols);
1307  
1308 12 ▶ utf8::upgrade($unrolled_non_null_cols_to_check)
Branch: 1 branch
BranchTrueFalseTotal
if &stresstest_utf8_upgrade_generated_collapser_source() 0 12 12
1309 if stresstest_utf8_upgrade_generated_collapser_source;
1310 }
1311  
1312 my $next_cref =
1313 ($did_fetch_all or ! $attrs->{collapse}) ? undef
1314 : defined $unrolled_non_null_cols_to_check ? eval sprintf <<'EOS', $unrolled_non_null_cols_to_check
1315 sub {
1316 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1317 my @r = $cursor->next or return;
1318 if (my @violating_idx = grep { ! defined $r[$_] } (%s) ) {
1319 $self->throw_exception( $err . CORE::join (', ', map { "'$infmap->[$_]'" } @violating_idx ) )
1320 }
1321 \@r
1322 }
1323 EOS
1324 0 ▶ : sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1325 # FIXME SUBOPTIMAL - we can do better, cursor->next/all (well diff. methods) should return a ref
1326 0 ▶ my @r = $cursor->next or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = $cursor->next or return 0 0 0
1327 \@r
1328 0 }
1329 15 ▶ ;
Branch: 2 branches
BranchTrueFalseTotal
$did_fetch_all || !$attrs->{'collapse'} ? : 12 3 15
defined $unrolled_non_null_cols_to_check ? : 3 0 3
Condition100%3/3
$did_fetch_all or not $attrs->{"collapse"}
l!l&&r!l&&!r
1113
MC/DC100%2/2
$did_fetch_all or not $attrs->{"collapse"}
$did_fetch_all not $attrs->{"collapse"}
Truth table100%3/3
A or not(B)
A= $did_fetch_allB= not $attrs->{"collapse"}
ABresult
1X1
011
000
1330  
1331 $self->{_row_parser}{$parser_type}{cref}->(
1332 $rows,
1333 15 ▶ $next_cref ? ( $next_cref, $self->{_stashed_rows} = [] ) : (),
Branch: 1 branch
BranchTrueFalseTotal
$next_cref ? : 3 12 15
1334 );
1335  
1336 # simple in-place substitution, does not regrow $rows
1337 15 ▶ if ($self->{_result_inflator}{is_core_row}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_result_inflator'}{'is_core_row'}) { } 15 0 15
elsif (not $self->{'_result_inflator'}{'is_hri'}) { } 0 0 0
1338 15 $_ = $inflator_cref->($res_class, $rsrc, @$_) for @$rows
1339 }
1340 # Special-case multi-object HRI - there is no $inflator_cref pass at all
1341 elsif ( ! $self->{_result_inflator}{is_hri} ) {
1342 # the inflator may be a multiplier/reductor - put it in list ctx
1343 0 @$rows = map { $inflator_cref->($res_class, $rsrc, @$_) } @$rows;
1344 }
1345 }
1346  
1347 # The @$rows check seems odd at first - why wouldn't we want to warn
1348 # regardless? The issue is things like find() etc, where the user
1349 # *knows* only one result will come back. In these cases the ->all
1350 # is not a pessimization, but rather something we actually want
1351 476 ▶ carp_unique(
Branch: 1 branch
BranchTrueFalseTotal
if not $fetch_all and @$rows > 1 0 476 476
Condition66%2/3
not $fetch_all and @$rows > 1
!ll&&!rl&&r
1673090
MC/DC0%0/2
not $fetch_all and @$rows > 1
not $fetch_all @$rows > 1
Truth table66%2/3
not(A) and B
A= not $fetch_allB= @$rows > 1
ABresult
0X0
100
111
1352 'Unable to properly collapse has_many results in iterator mode due '
1353 . 'to order criteria - performed an eager cursor slurp underneath. '
1354 . 'Consider using ->all() instead'
1355 ) if ( ! $fetch_all and @$rows > 1 );
1356  
1357 # Rows constructed from a context-bound resultset inherit the pinned
1358 # async context, so $rs->with_context($ctx)->first_async->then(sub {
1359 # $_[0]->update_async }) writes back on the same pinned connection instead of
1360 # the pool. The stamp cascades into eagerly-prefetched children (their related
1361 # resultsets and cached child rows) so a prefetched child fetched off a bound
1362 # parent stays pinned too (karr k195). Only Row objects can carry it (HRI
1363 # hashrefs cannot), and only when a context is actually bound -- otherwise this
1364 # loop never runs and the sync/pooled path is bit-for-bit unchanged. A result
1365 # class with its own inflate_result still hands back Row objects, so what it
1366 # built is asked rather than assumed from the inflator (karr k325).
1367 476 ▶ if ( my $ctx = $self->{_async_context} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ctx = $self->{"_async_context"}) 37 439 476
1368 37 my $is_core_row = $self->{_result_inflator}{is_core_row};
1369 37 for (@$rows) {
1370 41 ▶ $_->_bind_async_context($ctx)
Branch: 1 branch
BranchTrueFalseTotal
if $is_core_row or builtin::blessed($_) and $_->can("_bind_async_context") 41 0 41
Condition50%3/6
$is_core_row or builtin::blessed($_) and $_->can("_bind_async_context")
l!l&&r!l&&!r
3920
builtin::blessed($_) and $_->can("_bind_async_context")
!ll&&!rl&&r
002
MC/DC0%0/3
$is_core_row or builtin::blessed($_) and $_->can("_bind_async_context")
$is_core_row builtin::blessed($_) $_->can("_bind_async_context")
Truth table50%2/4
A or B and C
A= $is_core_rowB= builtin::blessed($_)C= $_->can("_bind_async_context")
ABCresult
1XX1
0111
00X0
0100
1371 if $is_core_row or ( blessed $_ and $_->can('_bind_async_context') );
1372 }
1373 }
1374  
1375 476 return $rows;
1376 }
1377  
1378  
1379 19735 ▶sub result_class {
Subroutine result_class: called CC=8 SCAR=22.2
Pod documented
1380 19735 my ($self, $result_class) = @_;
1381 19735 ▶ if ($result_class) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class) 14654 5081 19735
1382  
1383 # don't fire this for an object
1384 14654 ▶ if (! ref $result_class) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $result_class) 14654 0 14654
1385  
1386 # DBIx::Class::Helper::ResultSet::ResultClassDWIM resolved a leading '::'
1387 # against the ResultClass namespace. DBIO does not adopt that idiom, but
1388 # the string used to travel straight into ensure_class_loaded and die
1389 # with "Can't locate /HRI.pm" out of Class::C3::Componentised, which says
1390 # nothing about DBIO or about what is supported instead.
1391 14654 ▶ $self->throw_exception(
Branch: 2 branches
BranchTrueFalseTotal
if $result_class =~ /^::/ 4 14650 14654
$result_class eq '::HRI' ? : 3 1 4
1392 "result_class '$result_class' uses the '::'-prefixed shorthand of "
1393 . "DBIx::Class::Helper::ResultSet::ResultClassDWIM, which DBIO does not "
1394 . "implement -- pass the fully qualified class name instead"
1395 . ( $result_class eq '::HRI'
1396 ? " ('DBIO::ResultClass::HashRefInflator', which \$rs->hri sets for you)"
1397 : ''
1398 )
1399 ) if $result_class =~ /^::/;
1400  
1401 14650 $self->ensure_class_loaded($result_class);
1402 }
1403  
1404 14643 ▶ if ($self->get_cache) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->get_cache) { } 0 14643 14643
elsif ($self->{'cursor'} and $self->{'cursor'}->position) { } 0 29286 29286
1405 0 carp_unique('Changing the result_class of a ResultSet instance with cached results is a noop - the cache contents will not be altered');
1406 }
1407 ▶ elsif ($self->{cursor} && $self->{cursor}->position) {
Condition33%1/3
$self->{"cursor"} and $self->{"cursor"}->position
!ll&&!rl&&r
1464300
MC/DC0%0/2
$self->{"cursor"} and $self->{"cursor"}->position
$self->{"cursor"} $self->{"cursor"}->position
Truth table33%1/3
A and B
A= $self->{"cursor"}B= $self->{"cursor"}->position
ABresult
0X0
100
111
1408 0 $self->throw_exception('Changing the result_class of a ResultSet instance with an active cursor is not supported');
1409 }
1410  
1411 14643 $self->_result_class($result_class);
1412  
1413 14643 delete $self->{_result_inflator};
1414 }
1415 19724 $self->_result_class;
1416 }
1417  
1418  
1419 154 ▶sub count {
Subroutine count: called CC=8 SCAR=20.8
Pod documented
1420 154 my $self = shift;
1421 154 ▶ return $self->search_rs(@_)->count if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 9 145 154
1422 145 ▶ return scalar @{ $self->get_cache } if $self->get_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_cache 9 136 145
1423  
1424 136 my $attrs = { %{ $self->_resolved_attrs } };
1425  
1426 # this is a little optimization - it is faster to do the limit
1427 # adjustments in software, instead of a subquery
1428 136 my ($rows, $offset) = delete @{$attrs}{qw/rows offset/};
1429  
1430 136 my $crs;
1431 136 ▶ if ($self->_has_resolved_attr (qw/collapse group_by/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_resolved_attr('collapse', 'group_by')) { } 4 132 136
1432 4 $crs = $self->_count_subq_rs ($attrs);
1433 }
1434 else {
1435 132 $crs = $self->_count_rs ($attrs);
1436 }
1437 132 my $count = $crs->next;
1438  
1439 129 ▶ $count -= $offset if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 6 123 129
1440 129 ▶ $count = $rows if $rows and $rows < $count;
Branch: 1 branch
BranchTrueFalseTotal
if $rows and $rows < $count 2 127 129
Condition100%3/3
$rows and $rows < $count
!ll&&!rl&&r
11892
MC/DC100%2/2
$rows and $rows < $count
$rows $rows < $count
Truth table100%3/3
A and B
A= $rowsB= $rows < $count
ABresult
0X0
100
111
1441 129 ▶ $count = 0 if ($count < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $count < 0 0 129 129
1442  
1443 129 return $count;
1444 }
1445  
1446  
1447 37 ▶sub count_rs {
Subroutine count_rs: called CC=3 SCAR=11.0
Pod documented
1448 37 my $self = shift;
1449 37 ▶ return $self->search(@_)->count_rs if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 4 33 37
1450  
1451 # this may look like a lack of abstraction (count() does about the same)
1452 # but in fact an _rs *must* use a subquery for the limits, as the
1453 # software based limiting can not be ported if this $rs is to be used
1454 # in a subquery itself (i.e. ->as_query)
1455 33 ▶ if ($self->_has_resolved_attr (qw/collapse group_by offset rows/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_resolved_attr('collapse', 'group_by', 'offset', 'rows')) { } 15 18 33
1456 15 return $self->_count_subq_rs($self->{_attrs});
1457 }
1458 else {
1459 18 return $self->_count_rs($self->{_attrs});
1460 }
1461 }
1462  
1463 #
1464 # returns a ResultSetColumn object tied to the count query
1465 #
1466 167 ▶sub _count_rs {
Subroutine _count_rs: called CC=2 SCAR=6.9
1467 167 my ($self, $attrs) = @_;
1468  
1469 167 my $rsrc = $self->result_source;
1470  
1471 167 my $tmp_attrs = { %$attrs };
1472 # take off any limits, record_filter is cdbi, and no point of ordering nor locking a count
1473 167 delete @{$tmp_attrs}{qw/rows offset order_by record_filter for/};
1474  
1475 # overwrite the selector (supplied by the storage)
1476 167 my $count_rs = $rsrc->resultset_class->new($rsrc, {
1477 %$tmp_attrs,
1478 select => $rsrc->storage->_count_select ($rsrc, $attrs),
1479 as => 'count',
1480 });
1481  
1482 # ADR 0045 / karr k281: the count of a context-bound resultset keeps the pin
1483 # (get_column passes it on to the ResultSetColumn).
1484 163 ▶ $count_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 8 155 163
1485  
1486 163 return $count_rs->get_column ('count');
1487 }
1488  
1489 #
1490 # same as above but uses a subquery
1491 #
1492 19 ▶sub _count_subq_rs {
Subroutine _count_subq_rs: called CC=20 SCAR=30.6
1493 19 my ($self, $attrs) = @_;
1494  
1495 19 my $rsrc = $self->result_source;
1496  
1497 19 my $sub_attrs = { %$attrs };
1498 # extra selectors do not go in the subquery and there is no point of ordering it, nor locking it
1499 19 delete @{$sub_attrs}{qw/collapse columns as select order_by for/};
1500  
1501 # if we multi-prefetch we group_by something unique, as this is what we would
1502 # get out of the rs via ->next/->all. We *DO WANT* to clobber old group_by regardless
1503 19 ▶ if ( $attrs->{collapse} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"collapse"}) 2 17 19
1504 2 $sub_attrs->{group_by} = [ map { "$attrs->{alias}.$_" } @{
1505 2 ▶ $rsrc->_identifying_column_set || $self->throw_exception(
Condition33%1/3
$rsrc->_identifying_column_set || $self->throw_exception('Unable to construct a unique group_by criteria properly collapsing the has_many prefetch before count()')
l!l&&r!l&&!r
200
MC/DC0%0/2
$rsrc->_identifying_column_set || $self->throw_exception('Unable to construct a unique group_by criteria properly collapsing the has_many prefetch before count()')
$rsrc->_identifying_column_set $self->throw_exception('Unable to construct a unique group_by criteria properly collapsing the has_many prefetch before count()')
Truth table33%1/3
A || B
A= $rsrc->_identifying_column_setB= $self->throw_exception('Unable to construct a unique group_by criteria properly collapsing the has_many prefetch before count()')
ABresult
1X1
011
000
1506 'Unable to construct a unique group_by criteria properly collapsing the '
1507 . 'has_many prefetch before count()'
1508 );
1509 } ]
1510 }
1511  
1512 # Calculate subquery selector
1513 19 ▶ if (my $g = $sub_attrs->{group_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $g = $sub_attrs->{'group_by'}) { } 15 4 19
1514  
1515 15 my $sql_maker = $rsrc->storage->sql_maker;
1516  
1517 # necessary as the group_by may refer to aliased functions
1518 15 my $sel_index;
1519 15 for my $sel (@{$attrs->{select}}) {
1520 $sel_index->{$sel->{-as}} = $sel
1521 88 ▶ if (ref $sel eq 'HASH' and $sel->{-as});
Branch: 1 branch
BranchTrueFalseTotal
if ref $sel eq "HASH" and $sel->{"-as"} 4 84 88
Condition100%3/3
ref $sel eq "HASH" and $sel->{"-as"}
!ll&&!rl&&r
8134
MC/DC100%2/2
ref $sel eq "HASH" and $sel->{"-as"}
ref $sel eq "HASH" $sel->{"-as"}
Truth table100%3/3
A and B
A= ref $sel eq "HASH"B= $sel->{"-as"}
ABresult
0X0
100
111
1522 }
1523  
1524 # anything from the original select mentioned on the group-by needs to make it to the inner selector
1525 # also look for named aggregates referred in the having clause
1526 # having often contains scalarrefs - thus parse it out entirely
1527 15 my @parts = @$g;
1528 15 ▶ if ($attrs->{having}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"having"}) 2 13 15
1529 2 local $sql_maker->{having_bind};
1530 2 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
1531 2 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
1532 2 ▶ unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sql_maker->{"quote_char"} and length $sql_maker->{"quote_char"}) 0 2 2
Condition33%1/3
defined $sql_maker->{"quote_char"} and length $sql_maker->{"quote_char"}
!ll&&!rl&&r
002
MC/DC0%0/2
defined $sql_maker->{"quote_char"} and length $sql_maker->{"quote_char"}
defined $sql_maker->{"quote_char"} length $sql_maker->{"quote_char"}
Truth table33%1/3
A and B
A= defined $sql_maker->{"quote_char"}B= length $sql_maker->{"quote_char"}
ABresult
0X0
100
111
1533 0 $sql_maker->{quote_char} = [ "\x00", "\xFF" ];
1534 # if we don't unset it we screw up retarded but unfortunately working
1535 # 'MAX(foo.bar)' => { '>', 3 }
1536 0 $sql_maker->{name_sep} = '';
1537 }
1538  
1539 2 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
1540  
1541 2 my $having_sql = $sql_maker->_parse_rs_attrs ({ having => $attrs->{having} });
1542 2 my %seen_having;
1543  
1544 # search for both a proper quoted qualified string, for a naive unquoted scalarref
1545 # and if all fails for an utterly naive quoted scalar-with-function
1546 2 ▶ while ($having_sql =~ /
Branch: 1 branch
BranchTrueFalseTotal
if ($having_sql =~ / $rquote $sep $lquote (.+?) $rquote | [\s,] \w+ \. (\w+) [\s,] | [\s,] $lquote (.+?) $rquote [\s,] /gx) 3 2 5
1547 $rquote $sep $lquote (.+?) $rquote
1548 |
1549 [\s,] \w+ \. (\w+) [\s,]
1550 |
1551 [\s,] $lquote (.+?) $rquote [\s,]
1552 /gx) {
1553 3 ▶ my $part = $1 || $2 || $3; # one of them matched if we got here
Condition33%2/6
$1 || $2 || $3
l!l&&r!l&&!r
030
$1 or $2
l!l&&r!l&&!r
003
MC/DC0%0/3
$1 || $2 || $3
$1 $2 $3
Truth table25%1/4
A or B || C
A= $1B= $2C= $3
ABCresult
1XX1
01X1
0011
0000
1554 3 ▶ unless ($seen_having{$part}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen_having{$part}++) 2 1 3
1555 2 push @parts, $part;
1556 }
1557 }
1558 }
1559  
1560 15 for (@parts) {
1561 24 ▶ my $colpiece = $sel_index->{$_} || $_;
Condition66%2/3
$sel_index->{$_} || $_
l!l&&r!l&&!r
2220
MC/DC0%0/2
$sel_index->{$_} || $_
$sel_index->{$_} $_
Truth table66%2/3
A || B
A= $sel_index->{$_}B= $_
ABresult
1X1
011
000
1562  
1563 # unqualify join-based group_by's. Arcane but possible query
1564 # also horrible horrible hack to alias a column (not a func.)
1565 24 ▶ if ($colpiece =~ /\./ && $colpiece !~ /^$attrs->{alias}\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($colpiece =~ /\./ and not $colpiece =~ /^$attrs->{"alias"}\./) 2 22 24
Condition100%3/3
$colpiece =~ /\./ and not $colpiece =~ /^$attrs->{"alias"}\./
!ll&&!rl&&r
6162
MC/DC100%2/2
$colpiece =~ /\./ and not $colpiece =~ /^$attrs->{"alias"}\./
$colpiece =~ /\./ not $colpiece =~ /^$attrs->{"alias"}\./
Truth table100%3/3
A and not(B)
A= $colpiece =~ /\./B= not $colpiece =~ /^$attrs->{"alias"}\./
ABresult
0X0
100
111
1566 2 my $as = $colpiece;
1567 2 $as =~ s/\./__/;
1568 2 $colpiece = \ sprintf ('%s AS %s', map { $sql_maker->_quote ($_) } ($colpiece, $as) );
1569 }
1570 24 push @{$sub_attrs->{select}}, $colpiece;
1571 }
1572 }
1573 else {
1574 4 my @pcols = map { "$attrs->{alias}.$_" } ($rsrc->primary_columns);
1575 4 ▶ $sub_attrs->{select} = @pcols ? \@pcols : [ 1 ];
Branch: 1 branch
BranchTrueFalseTotal
@pcols ? : 4 0 4
1576 }
1577  
1578 19 my $sub_rs = $rsrc->resultset_class->new ($rsrc, $sub_attrs);
1579  
1580 # ADR 0045 / karr k281: the count of a context-bound resultset keeps the pin
1581 # (as_subselect_rs, search and get_column below each pass it on).
1582 19 ▶ $sub_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 4 15 19
1583  
1584 19 return $sub_rs
1585 ->as_subselect_rs
1586 ->search ({}, { columns => { count => $rsrc->storage->_count_select ($rsrc, $attrs) } })
1587 ->get_column ('count');
1588 }
1589  
1590  
1591  
1592 3 ▶sub count_literal { shift->search_literal(@_)->count; }
Subroutine count_literal: called CC=1 SCAR=0.0
Pod documented
1593  
1594  
1595 5 ▶sub count_literal_async { shift->search_literal(@_)->count_async; }
Subroutine count_literal_async: called CC=1 SCAR=0.0
Pod documented
1596  
1597  
1598 649 ▶sub all {
Subroutine all: called CC=5 SCAR=16.2
Pod documented
1599 649 my $self = shift;
1600 649 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 649 649
1601 0 $self->throw_exception("all() doesn't take any arguments, you probably wanted ->search(...)->all()");
1602 }
1603  
1604 649 delete @{$self}{qw/_stashed_rows _stashed_results/};
1605  
1606 649 ▶ if (my $c = $self->get_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $c = $self->get_cache) 27 622 649
1607 27 return @$c;
1608 }
1609  
1610 622 $self->cursor->reset;
1611  
1612 622 ▶ my $objs = $self->_construct_results('fetch_all') || [];
Condition100%2/2
$self->_construct_results('fetch_all') || []
l!l
115507
MC/DC100%1/1
$self->_construct_results('fetch_all') || []
$self->_construct_results('fetch_all')
Truth table100%2/2
A
A= $self->_construct_results('fetch_all')
Aresult
11
00
1613  
1614 622 ▶ $self->set_cache($objs) if $self->{attrs}{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"attrs"}{"cache"} 4 618 622
1615  
1616 622 return @$objs;
1617 }
1618  
1619  
1620 22 ▶sub reset {
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
1621 22 my ($self) = @_;
1622  
1623 22 delete @{$self}{qw/_stashed_rows _stashed_results/};
1624 22 $self->{all_cache_position} = 0;
1625 22 $self->cursor->reset;
1626 21 return $self;
1627 }
1628  
1629  
1630 22 ▶sub first {
Subroutine first: called CC=1 SCAR=0.0
Pod documented
1631 22 return $_[0]->reset->next;
1632 }
1633  
1634 # Shared dispatch for the ResultSet/Row *_async methods (ADR 0030/0031).
1635 # Mirrors the storage-level _run_async three-way contract one tier up:
1636 #
1637 # * a live embedded async backend -> route the read/write through the
1638 # storage's *_async op and inflate the raw result in the Future's ->then,
1639 # so it is genuinely non-blocking on a real backend (real async)
1640 # * the 'immediate' mode -> run the ordinary synchronous method and
1641 # (mode chosen, no backend) wrap its result in an immediately-
1642 # resolved Future via future_class
1643 # * a sync instance -> croak loudly: *_async was called but no
1644 # (no async mode chosen) async mode was selected at connect time
1645 #
1646 # $backend_build builds the real-async Future given ($backend, $future_class);
1647 # $sync_run is the synchronous fallback invoked for the immediate mode.
1648 # $validate (optional) checks the arguments of the call; it runs once the
1649 # backend (or bound context) is known and its return list is passed to
1650 # $backend_build after ($backend, $fc). In the immediate mode $sync_run validates.
1651 #
1652 # Runtime failures arrive as a failed Future, misuse as an exception: on the
1653 # pooled path whatever fails while the backend is resolved or the statement is
1654 # built fails the Future (of the storage's future_class) with the message as
1655 # thrown; misuse throws at the call -- a bound context that is expired or
1656 # foreign (ADR 0045), a connection without an async mode, and whatever
1657 # $validate throws (an invalid option, no data, a missing capability).
1658 373 ▶sub _rs_run_async {
Subroutine _rs_run_async: called CC=12 SCAR=24.9
1659 373 my ($self, $name, $backend_build, $sync_run, $validate) = @_;
1660  
1661 373 my $storage = $self->result_source->storage;
1662 373 my $fc = $storage->future_class;
1663  
1664 # An explicitly bound pinned context (from txn_do_async / pipeline)
1665 # takes precedence over the pooled backend, so RS async inside a transaction
1666 # or pipeline runs on the pinned connection instead of a sibling pool
1667 # connection outside it. A carried-but-expired context -- either a pipeline
1668 # context after its synchronous batch coderef returned or a transaction
1669 # context after its terminal path -- must NOT silently fall back to the pool;
1670 # it fails loudly (ADR 0045 / dbio-async ADR 0003). No context bound => the
1671 # historical path below, bit-for-bit.
1672 373 ▶ if (my $ctx = $self->_async_context) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ctx = $self->_async_context) 125 248 373
1673 125 _assert_async_context_active($self, $ctx, $name);
1674 98 $storage->_assert_async_context_owner($ctx);
1675 95 ▶ return $backend_build->($ctx, $fc, $validate ? $validate->() : ());
Branch: 1 branch
BranchTrueFalseTotal
$validate ? : 2 93 95
1676 }
1677  
1678 # On the pooled path an exception from getting the backend or building the
1679 # statement (the owner cannot connect for its sql_maker, say) is a runtime
1680 # failure and arrives as a failed Future, as the message was thrown (k403).
1681 # Misuse above and below stays an exception at the call.
1682 248 my ($backend, $error);
1683 {
1684 248 local $@;
1685 248 my $ok = eval { $backend = $storage->_async_storage; 1 };
1686 248 ▶ $error = $@ unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 248 248
1687 }
1688 248 ▶ return $fc->fail($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 0 248 248
1689  
1690 248 ▶ if ($backend) {
Branch: 1 branch
BranchTrueFalseTotal
if ($backend) 204 44 248
1691 # What is misuse of the call is checked by $validate, outside the net, and
1692 # throws at the call; what it returns goes on to $backend_build.
1693 204 ▶ my @validated = $validate ? $validate->() : ();
Branch: 1 branch
BranchTrueFalseTotal
$validate ? : 11 193 204
1694 199 my ($future, $build_error);
1695 {
1696 199 local $@;
1697 199 my $ok = eval {
1698 # A Future derived from the storage's own is reported to the pool (k397).
1699 $future = $backend->can('_note_pooled_derivation')
1700 199 ▶ ? $backend->_note_pooled_derivation(sub { $backend_build->($backend, $fc, @validated) })
Subroutine __ANON__: called CC=1 SCAR=0.0
1701 199 ▶ : $backend_build->($backend, $fc, @validated);
Branch: 1 branch
BranchTrueFalseTotal
$backend->can('_note_pooled_derivation') ? : 199 0 199
1702 197 1;
1703 };
1704 199 ▶ $build_error = $@ unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 197 199
1705 }
1706 199 ▶ return $fc->fail($build_error) if defined $build_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $build_error 2 197 199
1707 197 return $future;
1708 }
1709  
1710 $self->throw_exception(
1711 44 ▶ "not an async connection -- connect with { async => ... } to use ${name}_async"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $storage->_async_mode 15 29 44
1712 ) unless defined $storage->_async_mode;
1713  
1714 29 my @r = eval { $sync_run->() };
1715 29 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 10 19 29
1716 # Inside an immediate txn_do_async this is a statement of the transaction
1717 # like any other: its failure fails it, awaited or not (karr k331).
1718 10 $storage->_note_immediate_failure($error);
1719 10 return $fc->fail($error);
1720 }
1721 19 return $fc->done(@r);
1722 }
1723  
1724 # Shared active-context assertion for the RS/Row/RSC async paths. A bound
1725 # pinned context that has been invalidated -- a pipeline context after its batch
1726 # coderef or a transaction context after its terminal path -- must refuse loudly
1727 # rather than route work onto a connection already back in the pool.
1728 125 ▶sub _assert_async_context_active {
Subroutine _assert_async_context_active: called CC=3 SCAR=11.0
1729 125 my ($invocant, $ctx, $name) = @_;
1730 125 ▶ return if !$ctx->can('_context_active') || $ctx->_context_active;
Branch: 1 branch
BranchTrueFalseTotal
if not $ctx->can("_context_active") or $ctx->_context_active 98 27 125
Condition66%2/3
not $ctx->can("_context_active") or $ctx->_context_active
l!l&&r!l&&!r
09827
MC/DC50%1/2
not $ctx->can("_context_active") or $ctx->_context_active
not $ctx->can("_context_active") $ctx->_context_active
Truth table66%2/3
not(A) or B
A= not $ctx->can("_context_active")B= $ctx->_context_active
ABresult
1X1
011
000
1731 27 $invocant->throw_exception(
1732 "the async context bound to this result is no longer active; ${name}_async "
1733 . "cannot be routed onto it. Pipeline contexts stop accepting work when their "
1734 . "synchronous batch coderef returns; transaction contexts stop on their "
1735 . "terminal BEGIN / COMMIT / ROLLBACK path. Issue the async work while its "
1736 . "owning context remains active, not from a resultset held past it."
1737 );
1738 }
1739  
1740 # An operation that cannot be expressed as a single pinned async statement
1741 # (Row multi-create/cascade, upsert cascade/fallback/count) must NOT silently
1742 # run through the synchronous storage while a pinned context is bound -- that
1743 # would execute on a pooled sync connection OUTSIDE the pinned
1744 # transaction/pipeline (consequence 4). Refuse, named. With no context this is
1745 # the historical "punt to sync and resolve immediately" path, unchanged.
1746 #
1747 # In the 'immediate' mode the context is the storage itself (ADR 0055), and
1748 # the fallback would run inside the transaction. The refusal stands there too,
1749 # so that a bound resultset behaves the same in every async mode; only the
1750 # reason given is the one that is true there (karr k282).
1751 5 ▶sub _async_ctx_or_sync_punt {
Subroutine _async_ctx_or_sync_punt: called CC=6 SCAR=18.5
1752 5 my ($self, $fc, $op, $why, $sync_cref) = @_;
1753 5 ▶ if (my $ctx = $self->_async_context) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ctx = $self->_async_context) 2 3 5
1754 2 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $ctx == $self->result_source->storage 1 1 2
1755 "${op}_async cannot run on a bound async context: it is not expressible "
1756 . "as a single pinned statement ($why). In the 'immediate' mode the "
1757 . "synchronous fallback would run inside the transaction, but a bound "
1758 . "object refuses it in every async mode alike. Restructure so this runs "
1759 . "unbound -- in this mode that is still inside the transaction."
1760 ) if $ctx == $self->result_source->storage;
1761  
1762 1 ▶ my $where = $ctx->can('in_txn') && $ctx->in_txn ? 'transaction' : 'pipeline';
Branch: 1 branch
BranchTrueFalseTotal
$ctx->can('in_txn') && $ctx->in_txn ? : 1 0 1
Condition33%1/3
$ctx->can("in_txn") and $ctx->in_txn
!ll&&!rl&&r
001
MC/DC0%0/2
$ctx->can("in_txn") and $ctx->in_txn
$ctx->can("in_txn") $ctx->in_txn
Truth table33%1/3
A and B
A= $ctx->can("in_txn")B= $ctx->in_txn
ABresult
0X0
100
111
1763 1 $self->throw_exception(
1764 "${op}_async cannot run on a bound async context: it is not expressible "
1765 . "as a single pinned statement ($why), and the synchronous fallback would "
1766 . "run outside the pinned $where. Restructure so this runs outside the "
1767 . "context, or perform the equivalent explicit steps on the context."
1768 );
1769 }
1770 3 my $r = eval { $sync_cref->() };
1771 3 ▶ return $@ ? $fc->fail($@) : $fc->done($r);
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 3 3
1772 }
1773  
1774 # Inflate raw fetched rows (arrayrefs in $attrs->{select} order, exactly what a
1775 # real cursor's ->all would yield) into result objects with full fetch_all
1776 # collapse/prefetch parity, by feeding them to the very same
1777 # _construct_results('fetch_all') the synchronous ->all path uses. A pre-filled
1778 # cursor stands in for the storage cursor so no synchronous query is issued;
1779 # _construct_results pulls the rows from it via ->all just as it would from a
1780 # real eager cursor, then runs the identical collapser/inflator. Returns the
1781 # arrayref of constructed result objects (possibly empty).
1782 113 ▶sub _inflate_fetched_rows {
Subroutine _inflate_fetched_rows: called CC=2 SCAR=6.9
1783 113 my ($self, $raw_rows) = @_;
1784  
1785 113 delete @{$self}{qw/_stashed_rows _stashed_results/};
1786 113 local $self->{cursor} = DBIO::ResultSet::_PrefetchedCursor->new($raw_rows);
1787 113 ▶ return $self->_construct_results('fetch_all') || [];
Condition100%2/2
$self->_construct_results('fetch_all') || []
l!l
5261
MC/DC100%1/1
$self->_construct_results('fetch_all') || []
$self->_construct_results('fetch_all')
Truth table100%2/2
A
A= $self->_construct_results('fetch_all')
Aresult
11
00
1788 }
1789  
1790  
1791 140 ▶sub all_async {
Subroutine all_async: called CC=2 SCAR=7.0
Pod documented
1792 140 my $self = shift;
1793 140 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 140 140
1794 0 $self->throw_exception("all_async() doesn't take any arguments, you probably wanted ->search(...)->all_async()");
1795 }
1796  
1797 return $self->_rs_run_async('all',
1798 106 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1799 106 my ($backend, $fc) = @_;
1800  
1801 106 ▶ if (my $c = $self->get_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $c = $self->get_cache) 2 104 106
1802 2 return $fc->done(@$c);
1803 }
1804  
1805 104 my $attrs = $self->_resolved_attrs;
1806 return $backend->select_async(
1807 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs,
1808 102 ▶ )->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1809 102 my @raw = @_;
1810 102 my $objs = $self->_inflate_fetched_rows(\@raw);
1811 102 ▶ $self->set_cache($objs) if $self->{attrs}{cache};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"attrs"}{"cache"} 0 102 102
1812 # Resolve with the object LIST via an explicit Future, not a bare
1813 # `return @$objs`. A real Future's ->then invokes a non-Future-returning
1814 # callback in SCALAR context, so `return @$objs` would collapse to the
1815 # element count (the DBIO::Future::Immediate shim's ->then uses list
1816 # context, which hid this until the first live real-async run). Matches
1817 # the get_cache branch above, which already returns $fc->done(@$c).
1818 102 return $fc->done(@$objs);
1819 104 });
1820 },
1821 2 ▶ sub { $self->all },
Subroutine __ANON__: called CC=1 SCAR=0.0
1822 140 );
1823 }
1824  
1825  
1826 11 ▶sub first_async {
Subroutine first_async: called CC=1 SCAR=0.0
Pod documented
1827 11 my $self = shift;
1828  
1829 return $self->_rs_run_async('first',
1830 10 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1831 10 my ($backend, $fc) = @_;
1832  
1833 10 my $attrs = $self->_resolved_attrs;
1834 return $backend->select_async(
1835 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs,
1836 10 ▶ )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1837 10 my @raw = @_;
1838 10 my $objs = $self->_inflate_fetched_rows(\@raw);
1839 10 return $objs->[0];
1840 10 });
1841 },
1842 1 ▶ sub { $self->first },
Subroutine __ANON__: called CC=1 SCAR=0.0
1843 11 );
1844 }
1845  
1846  
1847 8 ▶sub single_async {
Subroutine single_async: called CC=2 SCAR=7.2
Pod documented
1848 8 my ($self, @args) = @_;
1849 8 ▶ if (@args > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args > 1) 0 8 8
1850 0 $self->throw_exception('single() only takes search conditions, no attributes. You want ->search( $cond, $attrs )->single()');
1851 }
1852  
1853 return $self->_rs_run_async('single',
1854 8 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1855 8 my ($backend, $fc) = @_;
1856  
1857 8 my @select_args = $self->_single_select_args($args[0]);
1858 8 ▶ return $backend->select_single_async(@select_args)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1859 8 my ($raw_row) = @_;
1860 8 ▶ return undef unless defined $raw_row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw_row 0 8 8
1861 8 $self->{_stashed_rows} = [ $raw_row ];
1862 8 return $self->_construct_results->[0];
1863 8 });
1864 },
1865 0 ▶ sub { $self->single(@args) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1866 8 );
1867 }
1868  
1869  
1870 64 ▶sub find_async {
Subroutine find_async: called CC=1 SCAR=0.0
Pod documented
1871 64 my $self = shift;
1872 64 my @args = @_;
1873 64 my ($final_cond, $attrs, $is_miss) = $self->_resolve_find_query(@args);
1874  
1875 return $self->_rs_run_async('find',
1876 59 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1877 59 my ($backend, $fc) = @_;
1878 59 ▶ return $fc->done(undef) if $is_miss;
Branch: 1 branch
BranchTrueFalseTotal
if $is_miss 1 58 59
1879  
1880 58 my $rs = $self->search($final_cond, {result_class => $self->result_class, %$attrs});
1881  
1882 58 ▶ if ($rs->_resolved_attrs->{collapse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rs->_resolved_attrs->{'collapse'}) { } 1 57 58
1883 1 my $rattrs = $rs->_resolved_attrs;
1884 return $backend->select_async(
1885 $rattrs->{from}, $rattrs->{select}, $rattrs->{where}, $rattrs,
1886 1 ▶ )->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1887 1 my @raw = @_;
1888 1 my $objs = $rs->_inflate_fetched_rows(\@raw);
1889 1 ▶ carp "Query returned more than one row" if @$objs > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$objs > 1 0 1 1
1890 1 return $objs->[0];
1891 1 });
1892 }
1893 else {
1894 57 my @select_args = $rs->_single_select_args;
1895 57 ▶ return $backend->select_single_async(@select_args)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1896 57 my ($raw_row) = @_;
1897 57 ▶ return undef unless defined $raw_row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw_row 15 42 57
1898 42 $rs->{_stashed_rows} = [ $raw_row ];
1899 42 return $rs->_construct_results->[0];
1900 57 });
1901 }
1902 },
1903 2 ▶ sub { $self->find(@args) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1904 63 );
1905 }
1906  
1907  
1908 33 ▶sub count_async {
Subroutine count_async: called CC=2 SCAR=7.2
Pod documented
1909 33 my $self = shift;
1910 33 ▶ return $self->search_rs(@_)->count_async if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 4 29 33
1911  
1912 return $self->_rs_run_async('count',
1913 17 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
1914 17 my ($backend, $fc) = @_;
1915  
1916 0 ▶ return $fc->done( scalar @{ $self->get_cache } ) if $self->get_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_cache 0 17 17
1917  
1918 17 my $attrs = { %{ $self->_resolved_attrs } };
1919  
1920 # software-side limit adjustment, identical to count()
1921 17 my ($rows, $offset) = delete @{$attrs}{qw/rows offset/};
1922  
1923 17 ▶ my $crs = $self->_has_resolved_attr (qw/collapse group_by/)
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_resolved_attr('collapse', 'group_by') ? : 0 17 17
1924 ? $self->_count_subq_rs ($attrs)
1925 : $self->_count_rs ($attrs);
1926  
1927 16 my $cattrs = $crs->_resultset->_resolved_attrs;
1928  
1929 return $backend->select_single_async(
1930 $cattrs->{from}, $cattrs->{select}, $cattrs->{where}, $cattrs,
1931 15 ▶ )->then(sub {
Subroutine __ANON__: called CC=9 SCAR=24.8
1932 15 my ($raw) = @_;
1933 15 ▶ my $count = (defined $raw && ref $raw eq 'ARRAY') ? ($raw->[0] // 0) : ($raw // 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $raw && ref $raw eq 'ARRAY' ? : 13 2 15
Condition57%4/7
defined $raw and ref $raw eq "ARRAY"
!ll&&!rl&&r
2013
$raw->[0] // 0
l!l
130
$raw // 0
l!l
02
MC/DC50%1/2
defined $raw and ref $raw eq "ARRAY"
defined $raw ref $raw eq "ARRAY"
MC/DC0%0/1
$raw->[0] // 0
$raw->[0]
MC/DC0%0/1
$raw // 0
$raw
Truth table66%2/3
A and B
A= defined $rawB= ref $raw eq "ARRAY"
ABresult
0X0
100
111
Truth table50%1/2
A
A= $raw->[0]
Aresult
11
00
Truth table50%1/2
A
A= $raw
Aresult
11
00
1934  
1935 15 ▶ $count -= $offset if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 15 15
1936 15 ▶ $count = $rows if $rows and $rows < $count;
Branch: 1 branch
BranchTrueFalseTotal
if $rows and $rows < $count 0 15 15
Condition33%1/3
$rows and $rows < $count
!ll&&!rl&&r
1500
MC/DC0%0/2
$rows and $rows < $count
$rows $rows < $count
Truth table33%1/3
A and B
A= $rowsB= $rows < $count
ABresult
0X0
100
111
1937 15 ▶ $count = 0 if ($count < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $count < 0 0 15 15
1938  
1939 15 return $count;
1940 16 });
1941 },
1942 8 ▶ sub { $self->count },
Subroutine __ANON__: called CC=1 SCAR=0.0
1943 29 );
1944 }
1945  
1946  
1947 54 ▶sub create_async {
Subroutine create_async: called CC=1 SCAR=0.0
Pod documented
1948 54 my ($self, @args) = @_;
1949  
1950 return $self->_rs_run_async('create',
1951 51 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1952 51 my ($backend, $fc) = @_;
1953 51 return $self->new_result($args[0])->insert_async;
1954 },
1955 2 ▶ sub { $self->create(@args) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1956 54 );
1957 }
1958  
1959 {
1960 # A stand-in cursor carrying already-fetched raw rows into
1961 # _construct_results('fetch_all') without issuing any synchronous query. Only
1962 # ->all (and ->reset/->next for safety) are exercised by the fetch_all path.
1963 package DBIO::ResultSet::_PrefetchedCursor;
1964  
1965 113 ▶ sub new {
Subroutine new: called CC=2 SCAR=7.2
1966 113 my ($class, $rows) = @_;
1967 113 ▶ return bless { rows => $rows || [] }, $class;
Condition50%1/2
$rows || []
l!l
1130
MC/DC0%0/1
$rows || []
$rows
Truth table50%1/2
A
A= $rows
Aresult
11
00
1968 }
1969  
1970 113 ▶ sub all {
Subroutine all: called CC=1 SCAR=0.0
1971 113 my $self = shift;
1972 113 return @{ $self->{rows} };
1973 }
1974  
1975 0 ▶ sub reset { $_[0]->{rows} = []; return $_[0] }
Subroutine reset: not called CC=1 SCAR=6.9
1976  
1977 0 ▶ sub next { return () }
Subroutine next: not called CC=1 SCAR=6.9
1978 }
1979  
1980 # The release for a statement over an unrestricted resultset (condition true):
1981 # only the call says it, with { all => 1 }. rows/offset restrict.
1982 379 ▶sub _assert_restricted_or_all {
Subroutine _assert_restricted_or_all: called CC=8 SCAR=20.8
1983 1722 my ($self, $op, $options) = @_;
1984  
1985 1722 ▶ if (defined $options) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options) 1135 587 1722
1986 1135 ▶ $self->throw_exception("$op options must be a hash")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $options eq "HASH" 1 1134 1135
1987 unless ref $options eq 'HASH';
1988 1134 my @unknown = grep { $_ ne 'all' } sort keys %$options;
1989 1134 ▶ $self->throw_exception("$op does not know the option(s): " . join(', ', @unknown))
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 2 1132 1134
1990 if @unknown;
1991 1132 ▶ return if $options->{all};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"all"} 1130 2 1132
1992 }
1993  
1994 589 ▶ return if $self->_has_resolved_attr(qw/rows offset/);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_resolved_attr("rows", "offset") 1 588 589
1995  
1996 588 my ($sql) = $self->result_source->storage->sql_maker->_recurse_where($self->{cond});
1997 588 ▶ return if defined $sql and length $sql;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sql and length $sql 561 27 588
Condition66%2/3
defined $sql and length $sql
!ll&&!rl&&r
270561
MC/DC50%1/2
defined $sql and length $sql
defined $sql length $sql
Truth table66%2/3
A and B
A= defined $sqlB= length $sql
ABresult
0X0
100
111
1998  
1999 27 $self->throw_exception("$op on an unrestricted resultset: pass { all => 1 }");
2000 }
2001  
2002 # _rs_update_delete
2003 #
2004 # Determines whether and what type of subquery is required for the $rs operation.
2005 # If grouping is necessary either supplies its own, or verifies the current one
2006 # After all is done delegates to the proper storage method.
2007  
2008 1146 ▶sub _rs_update_delete {
Subroutine _rs_update_delete: called CC=23 SCAR=44.4
2009 1146 my ($self, $op, $values) = @_;
2010  
2011 1146 my $rsrc = $self->result_source;
2012 1146 my $storage = $rsrc->schema->storage;
2013  
2014 1146 my $attrs = { %{$self->_resolved_attrs} };
2015  
2016 1146 my $join_classifications;
2017 1146 my ($existing_group_by) = delete @{$attrs}{qw(group_by _grouped_by_distinct)};
2018  
2019 # do we need a subquery for any reason?
2020 my $needs_subq = (
2021 defined $existing_group_by
2022 or
2023 # if {from} is unparseable wrap a subq
2024 1146 ▶ ref($attrs->{from}) ne 'ARRAY'
Condition50%3/6
defined $existing_group_by || ref $attrs->{'from'} ne 'ARRAY' || $self->_has_resolved_attr('rows', 'offset')
l!l&&r!l&&!r
011145
defined $existing_group_by or ref $attrs->{"from"} ne "ARRAY"
l!l&&r!l&&!r
001146
MC/DC33%1/3
defined $existing_group_by || ref $attrs->{'from'} ne 'ARRAY' || $self->_has_resolved_attr('rows', 'offset')
defined $existing_group_by ref $attrs->{"from"} ne "ARRAY" $self->_has_resolved_attr('rows', 'offset')
Truth table50%2/4
A or B || C
A= defined $existing_group_byB= ref $attrs->{"from"} ne "ARRAY"C= $self->_has_resolved_attr('rows', 'offset')
ABCresult
1XX1
01X1
0011
0000
2025 or
2026 # limits call for a subq
2027 $self->_has_resolved_attr(qw/rows offset/)
2028 );
2029  
2030 # simplify the joinmap, so we can further decide if a subq is necessary
2031 1146 ▶ if (!$needs_subq and @{$attrs->{from}} > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $needs_subq and @{$attrs->{"from"};} > 1) 0 1146 1146
Condition66%2/3
not $needs_subq and @{$attrs->{"from"};} > 1
!ll&&!rl&&r
111450
MC/DC0%0/2
not $needs_subq and @{$attrs->{"from"};} > 1
not $needs_subq @{$attrs->{"from"};} > 1
Truth table66%2/3
not(A) and B
A= not $needs_subqB= @{$attrs->{"from"};} > 1
ABresult
0X0
100
111
2032  
2033 0 ($attrs->{from}, $join_classifications) =
2034 $storage->_prune_unused_joins ($attrs);
2035  
2036 # any non-pruneable non-local restricting joins imply subq
2037 0 ▶ $needs_subq = grep { $_ ne $attrs->{alias} } keys %{ $join_classifications->{restricting} || {} };
Condition0%0/2
$join_classifications->{'restricting'} || {}
l!l
00
MC/DC0%0/1
$join_classifications->{'restricting'} || {}
$join_classifications->{'restricting'}
Truth table0%0/2
A
A= $join_classifications->{'restricting'}
Aresult
11
00
2038 }
2039  
2040 # check if the head is composite (by now all joins are thrown out unless $needs_subq)
2041 $needs_subq ||= (
2042 (ref $attrs->{from}[0]) ne 'HASH'
2043 or
2044 ref $attrs->{from}[0]{ $attrs->{from}[0]{-alias} }
2045 1146 ▶ );
Condition83%5/6
$needs_subq ||= ref $attrs->{"from"}[0] ne "HASH" || ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"}}
l!l&&r!l&&!r
1281864
ref $attrs->{'from'}[0] ne 'HASH' || ref $attrs->{'from'}[0]{$attrs->{'from'}[0]{'-alias'}}
l!l&&r!l&&!r
0281864
MC/DC0%0/3
$needs_subq ||= ref $attrs->{"from"}[0] ne "HASH" || ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"}}
$needs_subq ref $attrs->{'from'}[0] ne 'HASH' ref $attrs->{'from'}[0]{$attrs->{'from'}[0]{'-alias'}}
Truth table0%0/4
A ||= B || C
A= $needs_subqB= ref $attrs->{'from'}[0] ne 'HASH'C= ref $attrs->{'from'}[0]{$attrs->{'from'}[0]{'-alias'}}
ABCresult
1XX1
01X1
0011
0000
2046  
2047 1146 my ($cond, $guard);
2048 # do we need anything like a subquery?
2049 1146 ▶ if (! $needs_subq) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $needs_subq) { } 864 282 1146
2050 # Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
2051 # a condition containing 'me' or other table prefixes will not work
2052 # at all. Tell SQLMaker to dequalify idents via a gross hack.
2053 864 $cond = do {
2054 864 my $sqla = $rsrc->storage->sql_maker;
2055 864 local $sqla->{_dequalify_idents} = 1;
2056 864 \[ $sqla->_recurse_where($self->{cond}) ];
2057 };
2058 }
2059 else {
2060 # we got this far - means it is time to wrap a subquery
2061 282 ▶ my $idcols = $rsrc->_identifying_column_set || $self->throw_exception(
Condition33%1/3
$rsrc->_identifying_column_set || $self->throw_exception(sprintf(q[Unable to perform complex resultset %s() without an identifying set of columns on source '%s'], $op, $rsrc->source_name))
l!l&&r!l&&!r
28200
MC/DC0%0/2
$rsrc->_identifying_column_set || $self->throw_exception(sprintf(q[Unable to perform complex resultset %s() without an identifying set of columns on source '%s'], $op, $rsrc->source_name))
$rsrc->_identifying_column_set $self->throw_exception(sprintf(q[Unable to perform complex resultset %s() without an identifying set of columns on source '%s'], $op, $rsrc->source_name))
Truth table33%1/3
A || B
A= $rsrc->_identifying_column_setB= $self->throw_exception(sprintf(q[Unable to perform complex resultset %s() without an identifying set of columns on source '%s'], $op, $rsrc->source_name))
ABresult
1X1
011
000
2062 sprintf(
2063 "Unable to perform complex resultset %s() without an identifying set of columns on source '%s'",
2064 $op,
2065 $rsrc->source_name,
2066 )
2067 );
2068  
2069 # make a new $rs selecting only the PKs (that's all we really need for the subq)
2070 282 delete $attrs->{$_} for qw/select as collapse/;
2071 282 $attrs->{columns} = [ map { "$attrs->{alias}.$_" } @$idcols ];
2072  
2073 # this will be consumed by the pruner waaaaay down the stack
2074 282 $attrs->{_force_prune_multiplying_joins} = 1;
2075  
2076 282 my $subrs = (ref $self)->new($rsrc, $attrs);
2077  
2078 282 ▶ if (@$idcols == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@$idcols == 1) { } 282 0 282
elsif ($storage->_use_multicolumn_in) { } 0 0 0
2079 282 $cond = { $idcols->[0] => { -in => $subrs->as_query } };
2080 }
2081 elsif ($storage->_use_multicolumn_in) {
2082 # no syntax for calling this properly yet
2083 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
2084 0 $cond = $storage->sql_maker->_where_op_multicolumn_in (
2085 $idcols, # how do I convey a list of idents...? can binds reside on lhs?
2086 $subrs->as_query
2087 ),
2088 }
2089 else {
2090 # if all else fails - get all primary keys and operate over a ORed set
2091 # wrap in a transaction for consistency
2092 # this is where the group_by/multiplication starts to matter
2093 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($existing_group_by or keys %{$join_classifications->{"multiplying"} or {};}) 0 0 0
Condition0%0/3
$existing_group_by or keys %{$join_classifications->{"multiplying"} or {};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$existing_group_by or keys %{$join_classifications->{"multiplying"} or {};}
$existing_group_by keys %{$join_classifications->{"multiplying"} or {};}
Truth table0%0/3
A or B
A= $existing_group_byB= keys %{$join_classifications->{"multiplying"} or {};}
ABresult
1X1
011
000
2094 $existing_group_by
2095 or
2096 # we do not need to check pre-multipliers, since if the premulti is there, its
2097 # parent (who is multi) will be there too
2098 0 ▶ keys %{ $join_classifications->{multiplying} || {} }
Condition0%0/2
$join_classifications->{'multiplying'} || {}
l!l
00
MC/DC0%0/1
$join_classifications->{'multiplying'} || {}
$join_classifications->{'multiplying'}
Truth table0%0/2
A
A= $join_classifications->{'multiplying'}
Aresult
11
00
2099 ) {
2100 # make sure if there is a supplied group_by it matches the columns compiled above
2101 # perfectly. Anything else can not be sanely executed on most databases so croak
2102 # right then and there
2103 0 ▶ if ($existing_group_by) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing_group_by) 0 0 0
2104 my @current_group_by = map
2105 0 ▶ { $_ =~ /\./ ? $_ : "$attrs->{alias}.$_" }
Branch: 1 branch
BranchTrueFalseTotal
$_ =~ /\./ ? : 0 0 0
2106 @$existing_group_by
2107 ;
2108  
2109 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (CORE::join("\0", sort(@current_group_by)) ne CORE::join("\0", sort(@{$attrs->{"columns"};}))) 0 0 0
2110 join ("\x00", sort @current_group_by)
2111 ne
2112 0 join ("\x00", sort @{$attrs->{columns}} )
2113 ) {
2114 0 $self->throw_exception (
2115 "You have just attempted a $op operation on a resultset which does group_by"
2116 . ' on columns other than the primary keys, while DBIO internally needs to retrieve'
2117 . ' the primary keys in a subselect. All sane RDBMS engines do not support this'
2118 . ' kind of queries. Please retry the operation with a modified group_by or'
2119 . ' without using one at all.'
2120 );
2121 }
2122 }
2123  
2124 0 $subrs = $subrs->search({}, { group_by => $attrs->{columns} });
2125 }
2126  
2127 0 $guard = $storage->txn_scope_guard;
2128  
2129 0 for my $row ($subrs->cursor->all) {
2130 push @$cond, { map
2131 0 { $idcols->[$_] => $row->[$_] }
2132 (0 .. $#$idcols)
2133 };
2134 }
2135 }
2136 }
2137  
2138 1146 ▶ my $res = $cond ? $storage->$op (
Branch: 2 branches
BranchTrueFalseTotal
$cond ? : 1146 0 1146
$op eq 'update' ? : 11 1135 1146
2139 $rsrc,
2140 $op eq 'update' ? $values : (),
2141 $cond,
2142 ) : '0E0';
2143  
2144 1146 ▶ $guard->commit if $guard;
Branch: 1 branch
BranchTrueFalseTotal
if $guard 0 1146 1146
2145  
2146 1146 return $res;
2147 }
2148  
2149  
2150 19 ▶sub update {
Subroutine update: called CC=3 SCAR=11.1
Pod documented
2151 19 my ($self, $values, $options) = @_;
2152 19 ▶ $self->throw_exception('Values for update must be a hash')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "HASH" 0 19 19
2153 unless ref $values eq 'HASH';
2154 19 $self->_assert_restricted_or_all('update', $options);
2155  
2156 # no row is involved: every value goes to the storage as it is
2157 12 assert_column_value($_, $values->{$_}) for sort keys %$values;
2158  
2159 11 return $self->_rs_update_delete ('update', $values);
2160 }
2161  
2162  
2163 10 ▶sub update_all {
Subroutine update_all: called CC=3 SCAR=11.0
Pod documented
2164 10 my ($self, $values, $options) = @_;
2165 10 ▶ $self->throw_exception('Values for update_all must be a hash')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "HASH" 0 10 10
2166 unless ref $values eq 'HASH';
2167 10 $self->_assert_restricted_or_all('update_all', $options);
2168  
2169 3 my $guard = $self->result_source->schema->txn_scope_guard;
2170 3 $_->update({%$values}) for $self->all; # shallow copy - update will mangle it
2171 3 $guard->commit;
2172 3 return 1;
2173 }
2174  
2175  
2176 1144 ▶sub delete {
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
2177 1144 my ($self, $options) = @_;
2178 1144 $self->_assert_restricted_or_all('delete', $options);
2179  
2180 1135 return $self->_rs_update_delete ('delete');
2181 }
2182  
2183  
2184 549 ▶sub delete_all {
Subroutine delete_all: called CC=2 SCAR=6.9
Pod documented
2185 549 my ($self, $options) = @_;
2186 549 $self->_assert_restricted_or_all('delete_all', $options);
2187  
2188 542 my $guard = $self->result_source->schema->txn_scope_guard;
2189 542 $_->delete for $self->all;
2190 542 $guard->commit;
2191 542 return 1;
2192 }
2193  
2194  
2195 22 ▶sub populate {
Subroutine populate: called CC=86 SCAR=67.8
Pod documented
2196 22 my $self = shift;
2197  
2198 # this is naive and just a quick check
2199 # the types will need to be checked more thoroughly when the
2200 # multi-source populate gets added
2201 my $data = (
2202 ref $_[0] eq 'ARRAY'
2203 and
2204 22 ▶ ( @{$_[0]} or return )
Branch: 1 branch
BranchTrueFalseTotal
my $data = ref $_[0] eq "ARRAY" && (@{$_[0];} || (return)) && (ref $_[0][0] eq "HASH" || ref $_[0][0] eq "ARRAY") && $_[0] or $self->throw_exception("Populate expects an arrayref of hashrefs or arrayref of arrayrefs") 22 0 22
Condition42%6/14
ref $_[0] eq 'ARRAY' && (@{$_[0];} || (return)) && (ref $_[0][0] eq 'HASH' || ref $_[0][0] eq 'ARRAY') && $_[0]
!ll&&!rl&&r
0022
ref $_[0] eq "ARRAY" and @{$_[0];} || (return) and ref $_[0][0] eq "HASH" || ref $_[0][0] eq "ARRAY"
!ll&&!rl&&r
0022
ref $_[0] eq "ARRAY" and @{$_[0];} || (return)
!ll&&!rl&&r
0022
@{$_[0];} or return
l!l
220
ref $_[0][0] eq "HASH" or ref $_[0][0] eq "ARRAY"
l!l&&r!l&&!r
1930
MC/DC0%0/5
ref $_[0] eq 'ARRAY' && (@{$_[0];} || (return)) && (ref $_[0][0] eq 'HASH' || ref $_[0][0] eq 'ARRAY') && $_[0]
ref $_[0] eq "ARRAY" @{$_[0];} ref $_[0][0] eq "HASH" ref $_[0][0] eq "ARRAY" $_[0]
Truth table28%2/7
A and B and C or D && E
A= ref $_[0] eq "ARRAY"B= @{$_[0];}C= ref $_[0][0] eq "HASH"D= ref $_[0][0] eq "ARRAY"E= $_[0]
ABCDEresult
0XXXX0
10XXX0
1100X0
111X00
110100
111X11
110111
2205 and
2206 ( ref $_[0][0] eq 'HASH' or ref $_[0][0] eq 'ARRAY' )
2207 and
2208 $_[0]
2209 ) or $self->throw_exception('Populate expects an arrayref of hashrefs or arrayref of arrayrefs');
2210  
2211 # FIXME - no cref handling
2212 # At this point assume either hashes or arrays
2213  
2214 22 ▶ if(defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) 5 17 22
2215 5 my (@results, $guard);
2216  
2217 5 ▶ if (ref $data->[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data->[0] eq 'ARRAY') { } 0 5 5
2218 # column names only, nothing to do
2219 0 ▶ return if @$data == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$data == 1 0 0 0
2220  
2221 0 ▶ $guard = $self->result_source->schema->storage->txn_scope_guard
Branch: 1 branch
BranchTrueFalseTotal
if @$data > 2 0 0 0
2222 if @$data > 2;
2223  
2224 @results = map
2225 0 { my $vals = $_; $self->new_result({ map { $data->[0][$_] => $vals->[$_] } 0..$#{$data->[0]} })->insert }
2226 0 @{$data}[1 .. $#$data]
2227 ;
2228 }
2229 else {
2230  
2231 5 ▶ $guard = $self->result_source->schema->storage->txn_scope_guard
Branch: 1 branch
BranchTrueFalseTotal
if @$data > 1 2 3 5
2232 if @$data > 1;
2233  
2234 5 @results = map { $self->new_result($_)->insert } @$data;
2235 }
2236  
2237 2 ▶ $guard->commit if $guard;
Branch: 1 branch
BranchTrueFalseTotal
if $guard 2 0 2
2238 2 ▶ return wantarray ? @results : \@results;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
2239 }
2240  
2241 # we have to deal with *possibly incomplete* related data
2242 # this means we have to walk the data structure twice
2243 # whether we want this or not
2244 # jnap, I hate you ;)
2245 17 my $rsrc = $self->result_source;
2246 17 my $rel_info = { map { $_ => $rsrc->relationship_info($_) } $rsrc->relationships };
2247  
2248 17 my ($colinfo, $colnames, $slices_with_rels);
2249 17 my $data_start = 0;
2250  
2251 DATA_SLICE:
2252 17 for my $i (0 .. $#$data) {
2253  
2254 28 my $current_slice_seen_rel_infos;
2255  
2256 ### Determine/Supplement collists
2257 ### BEWARE - This is a hot piece of code, a lot of weird idioms were used
2258 28 ▶ if( ref $data->[$i] eq 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data->[$i] eq 'ARRAY') { } 6 22 28
elsif (ref $data->[$i] eq 'HASH') { } 22 0 22
2259  
2260 # positional(!) explicit column list
2261 6 ▶ if ($i == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i == 0) { } 3 3 6
2262 # column names only, nothing to do
2263 3 ▶ return if @$data == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$data == 1 0 3 3
2264  
2265 $colinfo->{$data->[0][$_]} = { pos => $_, name => $data->[0][$_] } and push @$colnames, $data->[0][$_]
2266 3 ▶ for 0 .. $#{$data->[0]};
Branch: 1 branch
BranchTrueFalseTotal
$$colinfo{$data->[0][$_]} = {"pos", $_, "name", $data->[0][$_]} and push @$colnames, $data->[0][$_] 7 0 7
2267  
2268 3 $data_start = 1;
2269  
2270 3 next DATA_SLICE;
2271 }
2272 else {
2273 3 for (values %$colinfo) {
2274 7 ▶ if ($_->{is_rel} ||= (
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{"is_rel"} ||= $$rel_info{$_->{"name"}} && (ref $data->[$i][$_->{"pos"}] eq "ARRAY" || ref $data->[$i][$_->{"pos"}] eq "HASH" || defined builtin::blessed($data->[$i][$_->{"pos"}]) && $data->[$i][$_->{"pos"}]->isa("DBIO::Row")) && 1) 0 7 7
Condition41%7/17
$_->{"is_rel"} ||= $$rel_info{$_->{"name"}} && (ref $data->[$i][$_->{"pos"}] eq "ARRAY" || ref $data->[$i][$_->{"pos"}] eq "HASH" || defined builtin::blessed($data->[$i][$_->{"pos"}]) && $data->[$i][$_->{"pos"}]->isa("DBIO::Row")) && 1
l!l&&r!l&&!r
007
$$rel_info{$_->{'name'}} && (ref $data->[$i][$_->{'pos'}] eq 'ARRAY' || ref $data->[$i][$_->{'pos'}] eq 'HASH' || defined builtin::blessed($data->[$i][$_->{'pos'}]) && $data->[$i][$_->{'pos'}]->isa('DBIO::Row')) && 1
!ll
70
$$rel_info{$_->{"name"}} and ref $data->[$i][$_->{"pos"}] eq "ARRAY" || ref $data->[$i][$_->{"pos"}] eq "HASH" || defined builtin::blessed($data->[$i][$_->{"pos"}]) && $data->[$i][$_->{"pos"}]->isa("DBIO::Row")
!ll&&!rl&&r
520
ref $data->[$i][$_->{"pos"}] eq "ARRAY" or ref $data->[$i][$_->{"pos"}] eq "HASH" or defined builtin::blessed($data->[$i][$_->{"pos"}]) and $data->[$i][$_->{"pos"}]->isa("DBIO::Row")
l!l&&r!l&&!r
002
ref $data->[$i][$_->{"pos"}] eq "ARRAY" or ref $data->[$i][$_->{"pos"}] eq "HASH"
l!l&&r!l&&!r
002
defined builtin::blessed($data->[$i][$_->{"pos"}]) and $data->[$i][$_->{"pos"}]->isa("DBIO::Row")
!ll&&!rl&&r
200
MC/DC0%0/6
$_->{"is_rel"} ||= $$rel_info{$_->{"name"}} && (ref $data->[$i][$_->{"pos"}] eq "ARRAY" || ref $data->[$i][$_->{"pos"}] eq "HASH" || defined builtin::blessed($data->[$i][$_->{"pos"}]) && $data->[$i][$_->{"pos"}]->isa("DBIO::Row")) && 1
$_->{"is_rel"} $$rel_info{$_->{"name"}} ref $data->[$i][$_->{"pos"}] eq "ARRAY" ref $data->[$i][$_->{"pos"}] eq "HASH" defined builtin::blessed($data->[$i][$_->{"pos"}]) $data->[$i][$_->{"pos"}]->isa("DBIO::Row")
Truth table0%0/7
A ||= B and C or D or E and F
A= $_->{"is_rel"}B= $$rel_info{$_->{"name"}}C= ref $data->[$i][$_->{"pos"}] eq "ARRAY"D= ref $data->[$i][$_->{"pos"}] eq "HASH"E= defined builtin::blessed($data->[$i][$_->{"pos"}])F= $data->[$i][$_->{"pos"}]->isa("DBIO::Row")
ABCDEFresult
1XXXXX1
011XXX1
0101XX1
0100111
00XXXX0
01000X0
0100100
2275 $rel_info->{$_->{name}}
2276 and
2277 (
2278 ref $data->[$i][$_->{pos}] eq 'ARRAY'
2279 or
2280 ref $data->[$i][$_->{pos}] eq 'HASH'
2281 or
2282 ( defined blessed $data->[$i][$_->{pos}] and $data->[$i][$_->{pos}]->isa('DBIO::Row') )
2283 )
2284 and
2285 1
2286 )) {
2287  
2288 # moar sanity check... sigh
2289 0 ▶ for ( ref $data->[$i][$_->{pos}] eq 'ARRAY' ? @{$data->[$i][$_->{pos}]} : $data->[$i][$_->{pos}] ) {
Branch: 1 branch
BranchTrueFalseTotal
ref $data->[$i][$_->{'pos'}] eq 'ARRAY' ? : 0 0 0
2290 0 ▶ if ( defined blessed $_ and $_->isa('DBIO::Row' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined builtin::blessed($_) and $_->isa("DBIO::Row")) 0 0 0
Condition0%0/3
defined builtin::blessed($_) and $_->isa("DBIO::Row")
!ll&&!rl&&r
000
MC/DC0%0/2
defined builtin::blessed($_) and $_->isa("DBIO::Row")
defined builtin::blessed($_) $_->isa("DBIO::Row")
Truth table0%0/3
A and B
A= defined builtin::blessed($_)B= $_->isa("DBIO::Row")
ABresult
0X0
100
111
2291 0 carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2292 0 return my $throwaway = $self->populate(@_);
2293 }
2294 }
2295  
2296 0 push @$current_slice_seen_rel_infos, $rel_info->{$_->{name}};
2297 }
2298 }
2299 }
2300  
2301 3 ▶ if ($current_slice_seen_rel_infos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_slice_seen_rel_infos) 0 3 3
2302 0 push @$slices_with_rels, { map { $colnames->[$_] => $data->[$i][$_] } 0 .. $#$colnames };
2303  
2304 # this is needed further down to decide whether or not to fallback to create()
2305 $colinfo->{$colnames->[$_]}{seen_null} ||= ! defined $data->[$i][$_]
2306 0 ▶ for 0 .. $#$colnames;
Condition0%0/3
$$colinfo{$colnames->[$_]}{"seen_null"} ||= !defined($data->[$i][$_])
l!l&&r!l&&!r
000
MC/DC0%0/2
$$colinfo{$colnames->[$_]}{"seen_null"} ||= !defined($data->[$i][$_])
$$colinfo{$colnames->[$_]}{"seen_null"} !defined($data->[$i][$_])
Truth table0%0/3
A ||= not(B)
A= $$colinfo{$colnames->[$_]}{"seen_null"}B= !defined($data->[$i][$_])
ABresult
1X1
011
000
2307 }
2308 }
2309 elsif( ref $data->[$i] eq 'HASH' ) {
2310  
2311 22 for ( sort keys %{$data->[$i]} ) {
2312  
2313 45 ▶ $colinfo->{$_} ||= do {
Condition66%2/3
$colinfo->{$_} ||= do { $self->throw_exception("Column '${_}' must be present in supplied explicit column list") if $data_start; push @$colnames, $_; +{"pos", $colnames->$#*, "name", $_} }
l!l&&r!l&&!r
14310
MC/DC0%0/2
$colinfo->{$_} ||= do { $self->throw_exception("Column '${_}' must be present in supplied explicit column list") if $data_start; push @$colnames, $_; +{"pos", $colnames->$#*, "name", $_} }
$colinfo->{$_} do { $self->throw_exception("Column '${_}' must be present in supplied explicit column list") if $data_start; push @$colnames, $_; +{"pos", $colnames->$#*, "name", $_} }
Truth table66%2/3
A ||= B
A= $colinfo->{$_}B= do { $self->throw_exception("Column '${_}' must be present in supplied explicit column list") if $data_start; push @$colnames, $_; +{"pos", $colnames->$#*, "name", $_} }
ABresult
1X1
011
000
2314  
2315 31 ▶ $self->throw_exception("Column '$_' must be present in supplied explicit column list")
Branch: 1 branch
BranchTrueFalseTotal
if $data_start 0 31 31
2316 if $data_start; # it will be 0 on AoH, 1 on AoA
2317  
2318 31 push @$colnames, $_;
2319  
2320 # RV
2321 31 { pos => $#$colnames, name => $_ }
2322 };
2323  
2324 45 ▶ if ($colinfo->{$_}{is_rel} ||= (
Branch: 1 branch
BranchTrueFalseTotal
if ($colinfo->{$_}{"is_rel"} ||= $rel_info->{$_} && (ref $data->[$i]{$_} eq "ARRAY" || ref $data->[$i]{$_} eq "HASH" || defined builtin::blessed($data->[$i]{$_}) && $data->[$i]{$_}->isa("DBIO::Row")) && 1) 1 44 45
Condition70%12/17
$colinfo->{$_}{"is_rel"} ||= $rel_info->{$_} && (ref $data->[$i]{$_} eq "ARRAY" || ref $data->[$i]{$_} eq "HASH" || defined builtin::blessed($data->[$i]{$_}) && $data->[$i]{$_}->isa("DBIO::Row")) && 1
l!l&&r!l&&!r
0144
$rel_info->{$_} && (ref $data->[$i]{$_} eq 'ARRAY' || ref $data->[$i]{$_} eq 'HASH' || defined builtin::blessed($data->[$i]{$_}) && $data->[$i]{$_}->isa('DBIO::Row')) && 1
!ll
441
$rel_info->{$_} and ref $data->[$i]{$_} eq "ARRAY" || ref $data->[$i]{$_} eq "HASH" || defined builtin::blessed($data->[$i]{$_}) && $data->[$i]{$_}->isa("DBIO::Row")
!ll&&!rl&&r
3861
ref $data->[$i]{$_} eq "ARRAY" or ref $data->[$i]{$_} eq "HASH" or defined builtin::blessed($data->[$i]{$_}) and $data->[$i]{$_}->isa("DBIO::Row")
l!l&&r!l&&!r
106
ref $data->[$i]{$_} eq "ARRAY" or ref $data->[$i]{$_} eq "HASH"
l!l&&r!l&&!r
016
defined builtin::blessed($data->[$i]{$_}) and $data->[$i]{$_}->isa("DBIO::Row")
!ll&&!rl&&r
600
MC/DC0%0/6
$colinfo->{$_}{"is_rel"} ||= $rel_info->{$_} && (ref $data->[$i]{$_} eq "ARRAY" || ref $data->[$i]{$_} eq "HASH" || defined builtin::blessed($data->[$i]{$_}) && $data->[$i]{$_}->isa("DBIO::Row")) && 1
$colinfo->{$_}{"is_rel"} $rel_info->{$_} ref $data->[$i]{$_} eq "ARRAY" ref $data->[$i]{$_} eq "HASH" defined builtin::blessed($data->[$i]{$_}) $data->[$i]{$_}->isa("DBIO::Row")
Truth table0%0/7
A ||= B and C or D or E and F
A= $colinfo->{$_}{"is_rel"}B= $rel_info->{$_}C= ref $data->[$i]{$_} eq "ARRAY"D= ref $data->[$i]{$_} eq "HASH"E= defined builtin::blessed($data->[$i]{$_})F= $data->[$i]{$_}->isa("DBIO::Row")
ABCDEFresult
1XXXXX1
011XXX1
0101XX1
0100111
00XXXX0
01000X0
0100100
2325 $rel_info->{$_}
2326 and
2327 (
2328 ref $data->[$i]{$_} eq 'ARRAY'
2329 or
2330 ref $data->[$i]{$_} eq 'HASH'
2331 or
2332 ( defined blessed $data->[$i]{$_} and $data->[$i]{$_}->isa('DBIO::Row') )
2333 )
2334 and
2335 1
2336 )) {
2337  
2338 # moar sanity check... sigh
2339 0 ▶ for ( ref $data->[$i]{$_} eq 'ARRAY' ? @{$data->[$i]{$_}} : $data->[$i]{$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
ref $data->[$i]{$_} eq 'ARRAY' ? : 0 1 1
2340 1 ▶ if ( defined blessed $_ and $_->isa('DBIO::Row' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined builtin::blessed($_) and $_->isa("DBIO::Row")) 0 1 1
Condition33%1/3
defined builtin::blessed($_) and $_->isa("DBIO::Row")
!ll&&!rl&&r
100
MC/DC0%0/2
defined builtin::blessed($_) and $_->isa("DBIO::Row")
defined builtin::blessed($_) $_->isa("DBIO::Row")
Truth table33%1/3
A and B
A= defined builtin::blessed($_)B= $_->isa("DBIO::Row")
ABresult
0X0
100
111
2341 0 carp_unique("Fast-path populate() with supplied related objects is not possible - falling back to regular create()");
2342 0 return my $throwaway = $self->populate(@_);
2343 }
2344 }
2345  
2346 1 push @$current_slice_seen_rel_infos, $rel_info->{$_};
2347 }
2348 }
2349  
2350 22 ▶ if ($current_slice_seen_rel_infos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_slice_seen_rel_infos) 1 21 22
2351 1 push @$slices_with_rels, $data->[$i];
2352  
2353 # this is needed further down to decide whether or not to fallback to create()
2354 $colinfo->{$_}{seen_null} ||= ! defined $data->[$i]{$_}
2355 1 ▶ for keys %{$data->[$i]};
Condition33%1/3
$colinfo->{$_}{"seen_null"} ||= !defined($data->[$i]{$_})
l!l&&r!l&&!r
003
MC/DC0%0/2
$colinfo->{$_}{"seen_null"} ||= !defined($data->[$i]{$_})
$colinfo->{$_}{"seen_null"} !defined($data->[$i]{$_})
Truth table33%1/3
A ||= not(B)
A= $colinfo->{$_}{"seen_null"}B= !defined($data->[$i]{$_})
ABresult
1X1
011
000
2356 }
2357 }
2358 else {
2359 0 $self->throw_exception('Unexpected populate() data structure member type: ' . ref $data->[$i] );
2360 }
2361  
2362 25 ▶ if ( grep
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_->{"attrs"}{"is_depends_on"};} @{$current_slice_seen_rel_infos or [];}) 1 24 25
2363 1 { $_->{attrs}{is_depends_on} }
2364 25 ▶ @{ $current_slice_seen_rel_infos || [] }
Condition100%2/2
$current_slice_seen_rel_infos || []
l!l
124
MC/DC100%1/1
$current_slice_seen_rel_infos || []
$current_slice_seen_rel_infos
Truth table100%2/2
A
A= $current_slice_seen_rel_infos
Aresult
11
00
2365 ) {
2366 1 carp_unique("Fast-path populate() of belongs_to relationship data is not possible - falling back to regular create()");
2367 1 return my $throwaway = $self->populate(@_);
2368 }
2369 }
2370  
2371 16 ▶ if( $slices_with_rels ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slices_with_rels) 0 16 16
2372  
2373 # need to exclude the rel "columns"
2374 0 $colnames = [ grep { ! $colinfo->{$_}{is_rel} } @$colnames ];
2375  
2376 # extra sanity check - ensure the main source is in fact identifiable
2377 # the localizing of nullability is insane, but oh well... the use-case is legit
2378 0 my $ci = $rsrc->columns_info($colnames);
2379  
2380 0 $ci->{$_} = { %{$ci->{$_}}, is_nullable => 0 }
2381 0 for grep { ! $colinfo->{$_}{seen_null} } keys %$ci;
2382  
2383 0 ▶ unless( $rsrc->_identifying_column_set($ci) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rsrc->_identifying_column_set($ci)) 0 0 0
2384 0 carp_unique("Fast-path populate() of non-uniquely identifiable rows with related data is not possible - falling back to regular create()");
2385 0 return my $throwaway = $self->populate(@_);
2386 }
2387 }
2388  
2389 ### what the caller assigns (ADR 0071), checked as new_result checks it: no
2390 ### guarded column or relationship, no value against the resultset's condition
2391 16 ▶ for my $name (sort keys %{ $colinfo || {} }) {
Condition50%1/2
$colinfo || {}
l!l
160
MC/DC0%0/1
$colinfo || {}
$colinfo
Truth table50%1/2
A
A= $colinfo
Aresult
11
00
2392 $colinfo->{$name}{is_rel}
2393 35 ▶ ? $rsrc->_assert_relationship_not_guarded($name)
Branch: 1 branch
BranchTrueFalseTotal
$colinfo->{$name}{'is_rel'} ? : 0 35 35
2394 : $rsrc->_assert_columns_not_guarded($name)
2395 ;
2396 }
2397  
2398 14 ▶ if ( my %scope = %{ $self->_scope_values } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(%scope) = %{$self->_scope_values;}) 4 10 14
2399 4 for my $name (grep { exists $scope{$_} } @$colnames) {
2400 4 my $pos = $colinfo->{$name}{pos};
2401  
2402 $rsrc->_assert_scope_agrees(
2403 { $name => ref $data->[$_] eq 'ARRAY' ? $data->[$_][$pos] : $data->[$_]{$name} },
2404 { $name => $scope{$name} },
2405 4 ▶ ) for $data_start .. $#$data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data->[$_] eq 'ARRAY' ? : 1 6 7
2406 }
2407 }
2408  
2409 ### inherit the data locked in the conditions of the resultset
2410 11 my ($rs_data) = $self->_merge_with_rscond({});
2411 11 delete @{$rs_data}{@$colnames}; # passed-in stuff takes precedence
2412  
2413 # if anything left - decompose rs_data
2414 11 my $rs_data_vals;
2415 11 ▶ if (keys %$rs_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$rs_data) 0 11 11
2416 push @$rs_data_vals, $rs_data->{$_}
2417 0 for sort keys %$rs_data;
2418 }
2419  
2420 ### start work
2421 11 my $guard;
2422 11 ▶ $guard = $rsrc->schema->storage->txn_scope_guard
Branch: 1 branch
BranchTrueFalseTotal
if $slices_with_rels 0 11 11
2423 if $slices_with_rels;
2424  
2425 ### main source data
2426 # FIXME - need to switch entirely to a coderef-based thing,
2427 # so that large sets aren't copied several times... I think
2428 11 my $bulk_cols = [ @$colnames, sort keys %$rs_data ];
2429 my $bulk_rows = [ map {
2430 11 ref $data->[$_] eq 'ARRAY'
2431 ? (
2432 0 ▶ $slices_with_rels ? [ @{$data->[$_]}[0..$#$colnames], @{$rs_data_vals||[]} ] # the collist changed
Branch: 1 branch
BranchTrueFalseTotal
$rs_data_vals ? : 0 1 1
Condition0%0/2
$rs_data_vals || []
l!l
00
MC/DC0%0/1
$rs_data_vals || []
$rs_data_vals
Truth table0%0/2
A
A= $rs_data_vals
Aresult
11
00
2433 0 : $rs_data_vals ? [ @{$data->[$_]}, @$rs_data_vals ]
2434 : $data->[$_]
2435 )
2436 17 ▶ : [ @{$data->[$_]}{@$colnames}, @{$rs_data_vals||[]} ]
Branch: 2 branches
BranchTrueFalseTotal
ref $data->[$_] eq 'ARRAY' ? : 1 16 17
$slices_with_rels ? : 0 1 1
Condition50%1/2
$rs_data_vals || []
l!l
016
MC/DC0%0/1
$rs_data_vals || []
$rs_data_vals
Truth table50%1/2
A
A= $rs_data_vals
Aresult
11
00
2437 } $data_start .. $#$data ];
2438  
2439 # the bulk path goes to the storage as it is: every value is a storage value
2440 11 for my $row (@$bulk_rows) {
2441 17 assert_column_value($bulk_cols->[$_], $row->[$_]) for 0 .. $#$bulk_cols;
2442 }
2443  
2444 8 $rsrc->storage->_insert_bulk($rsrc, $bulk_cols, $bulk_rows);
2445  
2446 ### do the children relationships
2447 6 ▶ if ( $slices_with_rels ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slices_with_rels) 0 6 6
2448 0 ▶ my @rels = grep { $colinfo->{$_}{is_rel} } keys %$colinfo
Branch: 1 branch
BranchTrueFalseTotal
my(@rels) = grep({$colinfo->{$_}{"is_rel"};} keys %$colinfo) or die "wtf... please report a bug with DBIO_TRACE=1 output (stacktrace)" 0 0 0
2449 or die 'wtf... please report a bug with DBIO_TRACE=1 output (stacktrace)';
2450  
2451 0 for my $sl (@$slices_with_rels) {
2452  
2453 0 my ($main_proto, $main_proto_rs);
2454 0 for my $rel (@rels) {
2455 0 ▶ next unless defined $sl->{$rel};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sl->{$rel} 0 0 0
2456  
2457 $main_proto ||= {
2458 %$rs_data,
2459 0 ▶ (map { $_ => $sl->{$_} } @$colnames),
Condition0%0/2
$main_proto ||= {%$rs_data, map({$_, $sl->{$_};} @$colnames)}
l!l
00
MC/DC0%0/1
$main_proto ||= {%$rs_data, map({$_, $sl->{$_};} @$colnames)}
$main_proto
Truth table0%0/2
A
A= $main_proto
Aresult
11
00
2460 };
2461  
2462 0 ▶ unless (defined $colinfo->{$rel}{rs}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $colinfo->{$rel}{"rs"}) 0 0 0
2463  
2464 0 $colinfo->{$rel}{rs} = $rsrc->related_source($rel)->resultset;
2465  
2466 0 $colinfo->{$rel}{fk_map} = { reverse %{ $rsrc->_resolve_relationship_condition(
2467 rel_name => $rel,
2468 self_alias => "\xFE", # irrelevant
2469 foreign_alias => "\xFF", # irrelevant
2470 0 ▶ )->{identity_map} || {} } };
Condition0%0/2
$rsrc->_resolve_relationship_condition('rel_name', $rel, 'self_alias', "\376", 'foreign_alias', "\377")->{'identity_map'} || {}
l!l
00
MC/DC0%0/1
$rsrc->_resolve_relationship_condition('rel_name', $rel, 'self_alias', "\376", 'foreign_alias', "\377")->{'identity_map'} || {}
$rsrc->_resolve_relationship_condition('rel_name', $rel, 'self_alias', "\376", 'foreign_alias', "\377")->{'identity_map'}
Truth table0%0/2
A
A= $rsrc->_resolve_relationship_condition('rel_name', $rel, 'self_alias', "\376", 'foreign_alias', "\377")->{'identity_map'}
Aresult
11
00
2471  
2472 }
2473  
2474 $colinfo->{$rel}{rs}->search({ map # only so that we inherit them values properly, no actual search
2475 {
2476 $_ => { '=' =>
2477 ( $main_proto_rs ||= $rsrc->resultset->search($main_proto) )
2478 0 ▶ ->get_column( $colinfo->{$rel}{fk_map}{$_} )
Condition0%0/3
$main_proto_rs ||= $rsrc->resultset->search($main_proto)
l!l&&r!l&&!r
000
MC/DC0%0/2
$main_proto_rs ||= $rsrc->resultset->search($main_proto)
$main_proto_rs $rsrc->resultset->search($main_proto)
Truth table0%0/3
A ||= B
A= $main_proto_rsB= $rsrc->resultset->search($main_proto)
ABresult
1X1
011
000
2479 ->as_query
2480 }
2481 }
2482 0 ▶ keys %{$colinfo->{$rel}{fk_map}}
Branch: 1 branch
BranchTrueFalseTotal
ref $sl->{$rel} eq 'ARRAY' ? : 0 0 0
2483 0 })->populate( ref $sl->{$rel} eq 'ARRAY' ? $sl->{$rel} : [ $sl->{$rel} ] );
2484  
2485 0 1;
2486 }
2487 }
2488 }
2489  
2490 6 ▶ $guard->commit if $guard;
Branch: 1 branch
BranchTrueFalseTotal
if $guard 0 6 6
2491 }
2492  
2493  
2494 22 ▶sub pager {
Subroutine pager: called CC=6 SCAR=18.4
Pod documented
2495 22 my ($self) = @_;
2496  
2497 22 ▶ return $self->{pager} if $self->{pager};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pager"} 8 14 22
2498  
2499 14 my $attrs = $self->{attrs};
2500 14 ▶ if (!defined $attrs->{page}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $attrs->{'page'}) { } 0 14 14
elsif ($attrs->{'page'} <= 0) { } 0 14 14
2501 0 $self->throw_exception("Can't create pager for non-paged rs, you need to call page(\$num) first");
2502 }
2503 elsif ($attrs->{page} <= 0) {
2504 0 $self->throw_exception('Invalid page number (page-numbers are 1-based)');
2505 }
2506 14 ▶ $attrs->{rows} ||= 10;
Condition50%1/2
$attrs->{"rows"} ||= 10
l!l
140
MC/DC0%0/1
$attrs->{"rows"} ||= 10
$attrs->{"rows"}
Truth table50%1/2
A
A= $attrs->{"rows"}
Aresult
11
00
2507  
2508 # throw away the paging flags and re-run the count (possibly
2509 # with a subselect) to get the real total count
2510 14 my $count_attrs = { %$attrs };
2511 14 delete @{$count_attrs}{qw/rows offset page pager/};
2512  
2513 14 my $total_rs = (ref $self)->new($self->result_source, $count_attrs);
2514  
2515 # a bound resultset counts through its context (karr k331), as the async
2516 # recipe in DBIO::ResultSet::Pager does
2517 14 ▶ $total_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 1 13 14
2518  
2519 14 require DBIO::ResultSet::Pager;
2520 return $self->{pager} = DBIO::ResultSet::Pager->new(
2521 9 ▶ sub { $total_rs->count }, #lazy-get the total
Subroutine __ANON__: called CC=1 SCAR=0.0
2522 $attrs->{rows},
2523 $self->{attrs}{page},
2524 14 );
2525 }
2526  
2527  
2528 10 ▶sub page {
Subroutine page: called CC=2 SCAR=6.9
Pod documented
2529 10 my ($self, $page) = @_;
2530 10 my $rs = (ref $self)->new($self->result_source, { %{$self->{attrs}}, page => $page });
2531 # ADR 0045 / karr k195: a page derived from a context-bound resultset inherits
2532 # the pin so ->page(N)->all_async stays on the pinned connection.
2533 10 ▶ $rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 1 9 10
2534 10 return $rs;
2535 }
2536  
2537  
2538 3614 ▶sub new_result {
Subroutine new_result: called CC=11 SCAR=26.4
Pod documented
2539 3614 my ($self, $values) = @_;
2540  
2541 3614 ▶ $self->throw_exception( "new_result takes only one argument - a hashref of values" )
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 2 0 3614 3614
2542 if @_ > 2;
2543  
2544 3614 ▶ $self->throw_exception( "Result object instantiation requires a hashref as argument" )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "HASH" 0 3614 3614
2545 unless (ref $values eq 'HASH');
2546  
2547 # ADR 0071: the keys of $values are what the caller assigns (new_related
2548 # names its own, its values hold the parent's foreign key as well); what the
2549 # condition holds is inherited
2550 3614 my ($merged_cond, $cols_from_relations) = $self->_merge_with_rscond($values, 1);
2551 3605 my $scope_values = $self->_scope_values;
2552  
2553 my $new = $self->result_class->new({
2554 %$merged_cond,
2555 ( @$cols_from_relations
2556 ? (-cols_from_relations => $cols_from_relations)
2557 : ()
2558 ),
2559 -caller_keys => $self->{_caller_keys}
2560 3605 ▶ || [ keys %{ $self->_remove_alias($values, $self->{attrs}{alias}) } ],
Branch: 2 branches
BranchTrueFalseTotal
@$cols_from_relations ? : 0 3605 3605
%$scope_values ? : 1506 2099 3605
Condition100%2/2
$self->{'_caller_keys'} || [keys %{$self->_remove_alias($values, $self->{'attrs'}{'alias'});}]
l!l
14882117
MC/DC100%1/1
$self->{'_caller_keys'} || [keys %{$self->_remove_alias($values, $self->{'attrs'}{'alias'});}]
$self->{'_caller_keys'}
Truth table100%2/2
A
A= $self->{'_caller_keys'}
Aresult
11
00
2561 ( %$scope_values
2562 ? (-scope_values => $scope_values)
2563 : ()
2564 ),
2565 -result_source => $self->result_source, # DO NOT REMOVE THIS, REQUIRED
2566 });
2567  
2568 3579 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::reftype($new) eq "HASH" and not keys %$new and builtin::blessed($new)) 0 3579 3579
Condition33%2/6
builtin::reftype($new) eq "HASH" and not keys %$new and builtin::blessed($new)
!ll&&!rl&&r
357900
builtin::reftype($new) eq "HASH" and not keys %$new
!ll&&!rl&&r
035790
MC/DC0%0/3
builtin::reftype($new) eq "HASH" and not keys %$new and builtin::blessed($new)
builtin::reftype($new) eq "HASH" not keys %$new builtin::blessed($new)
Truth table25%1/4
A and not(B) and C
A= builtin::reftype($new) eq "HASH"B= not keys %$newC= builtin::blessed($new)
ABCresult
0XX0
10X0
1100
1111
2569 reftype($new) eq 'HASH'
2570 and
2571 ! keys %$new
2572 and
2573 blessed($new)
2574 ) {
2575 0 carp_unique (sprintf (
2576 "%s->new returned a blessed empty hashref - a strong indicator something is wrong with its inheritance chain",
2577 $self->result_class,
2578 ));
2579 }
2580  
2581 # A row built from a context-bound resultset (create_async,
2582 # find_or_new_async, update_or_new_async, ...) inherits the pinned async
2583 # context so its own insert_async/update_async stays on the pinned connection.
2584 $new->{_async_context} = $self->{_async_context}
2585 3579 ▶ if $self->{_async_context} and blessed($new);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} and builtin::blessed($new) 43 3536 3579
Condition66%2/3
$self->{"_async_context"} and builtin::blessed($new)
!ll&&!rl&&r
3536043
MC/DC50%1/2
$self->{"_async_context"} and builtin::blessed($new)
$self->{"_async_context"} builtin::blessed($new)
Truth table66%2/3
A and B
A= $self->{"_async_context"}B= builtin::blessed($new)
ABresult
0X0
100
111
2586  
2587 3579 $new;
2588 }
2589  
2590 # _merge_with_rscond
2591 #
2592 # Takes a simple hash of K/V data and returns its copy merged with the
2593 # condition already present on the resultset. Additionally returns an
2594 # arrayref of value/condition names, which were inferred from related
2595 # objects (this is needed for in-memory related objects)
2596 #
2597 # A true second argument says $data is what the caller assigns to the new row
2598 # (ADR 0071): a plain value that contradicts an equality of the condition
2599 # throws. A relationship value is resolved to columns by the row layer, which
2600 # checks those the same way.
2601 5671 ▶sub _merge_with_rscond {
Subroutine _merge_with_rscond: called CC=9 SCAR=23.0
2602 5671 my ($self, $data, $assignment) = @_;
2603  
2604 5671 my ($implied_data, @cols_from_relations);
2605  
2606 5671 my $alias = $self->{attrs}{alias};
2607  
2608 5671 ▶ if (! defined $self->{cond}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $self->{'cond'}) { } 4116 1555 5671
elsif ($self->{'cond'} eq \'1 = 0') { } 0 1555 1555
2609 # just massage $data below
2610 }
2611 elsif ($self->{cond} eq UNRESOLVABLE_CONDITION) {
2612 0 $implied_data = $self->{attrs}{related_objects}; # nothing might have been inserted yet
2613 0 ▶ @cols_from_relations = keys %{ $implied_data || {} };
Condition0%0/2
$implied_data || {}
l!l
00
MC/DC0%0/1
$implied_data || {}
$implied_data
Truth table0%0/2
A
A= $implied_data
Aresult
11
00
2614 }
2615 else {
2616 1555 $implied_data = $self->_scope_values;
2617  
2618 1555 ▶ if ($assignment) {
Branch: 1 branch
BranchTrueFalseTotal
if ($assignment) 1518 37 1555
2619 1518 my $rsrc = $self->result_source;
2620 1518 my $given = $self->_remove_alias($data, $alias);
2621  
2622 $rsrc->_assert_scope_agrees(
2623 { map {
2624 1518 ( ref $given->{$_} and ! is_literal_value($given->{$_}) and $rsrc->relationship_info($_) )
2625 ? ()
2626 4510 ▶ : ( $_ => $given->{$_} )
Branch: 1 branch
BranchTrueFalseTotal
ref $given->{$_} && !&is_literal_value($given->{$_}) && $rsrc->relationship_info($_) ? : 5 4505 4510
Condition66%4/6
ref $given->{$_} and not &is_literal_value($given->{$_}) and $rsrc->relationship_info($_)
!ll&&!rl&&r
450505
ref $given->{$_} and not &is_literal_value($given->{$_})
!ll&&!rl&&r
450505
MC/DC33%1/3
ref $given->{$_} and not &is_literal_value($given->{$_}) and $rsrc->relationship_info($_)
ref $given->{$_} not &is_literal_value($given->{$_}) $rsrc->relationship_info($_)
Truth table50%2/4
A and not(B) and C
A= ref $given->{$_}B= not &is_literal_value($given->{$_})C= $rsrc->relationship_info($_)
ABCresult
0XX0
10X0
1100
1111
2627 } keys %$given },
2628 $implied_data,
2629 );
2630 }
2631 }
2632  
2633 return (
2634 { map
2635 5660 ▶ { %{ $self->_remove_alias($_, $alias) } }
Condition100%3/3
$implied_data || ()
l!l&&r!l&&!r
154413992717
MC/DC100%2/2
$implied_data || ()
$implied_data ()
Truth table100%3/3
A || B
A= $implied_dataB= ()
ABresult
1X1
011
000
2636 # precedence must be given to passed values over values inherited from
2637 # the cond, so the order here is important.
2638 ( $implied_data||(), $data)
2639 },
2640 \@cols_from_relations
2641 );
2642 }
2643  
2644 # _scope_values
2645 #
2646 # The equalities the resultset's own condition holds, as { column => value }
2647 # with the alias removed and undef for IS NULL -- the values a row created
2648 # through this resultset inherits.
2649 5174 ▶sub _scope_values {
Subroutine _scope_values: called CC=5 SCAR=16.2
2650 5174 my ($self) = @_;
2651  
2652 return {}
2653 5174 ▶ if ! defined $self->{cond} or $self->{cond} eq UNRESOLVABLE_CONDITION;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $self->{"cond"} or $self->{"cond"} eq \"1 = 0" 2109 3065 5174
Condition66%2/3
not defined $self->{"cond"} or $self->{"cond"} eq \"1 = 0"
l!l&&r!l&&!r
210903065
MC/DC50%1/2
not defined $self->{"cond"} or $self->{"cond"} eq \"1 = 0"
not defined $self->{"cond"} $self->{"cond"} eq \"1 = 0"
Truth table66%2/3
not(A) or B
A= not defined $self->{"cond"}B= $self->{"cond"} eq \"1 = 0"
ABresult
1X1
011
000
2654  
2655 3065 my $eqs = $self->result_source->schema->storage->_extract_fixed_condition_columns($self->{cond}, 'consider_nulls');
2656  
2657 return $self->_remove_alias(
2658 { map {
2659 3065 ▶ ( ($eqs->{$_}||'') eq UNRESOLVABLE_CONDITION ) ? () : ( $_ => $eqs->{$_} )
Branch: 1 branch
BranchTrueFalseTotal
($eqs->{$_} || '') eq \'1 = 0' ? : 0 3065 3065
Condition100%2/2
$eqs->{$_} || ''
l!l
30605
MC/DC100%1/1
$eqs->{$_} || ''
$eqs->{$_}
Truth table100%2/2
A
A= $eqs->{$_}
Aresult
11
00
2660 } keys %$eqs },
2661 $self->{attrs}{alias},
2662 3065 );
2663 }
2664  
2665 # _has_resolved_attr
2666 #
2667 # determines if the resultset defines at least one
2668 # of the attributes supplied
2669 #
2670 # used to determine if a subquery is necessary
2671 #
2672 # supports some virtual attributes:
2673 # -join
2674 # This will scan for any joins being present on the resultset.
2675 # It is not a mere key-search but a deep inspection of {from}
2676 #
2677  
2678 1939 ▶sub _has_resolved_attr {
Subroutine _has_resolved_attr: called CC=12 SCAR=29.3
2679 1939 my ($self, @attr_names) = @_;
2680  
2681 1939 my $attrs = $self->_resolved_attrs;
2682  
2683 1939 my %extra_checks;
2684  
2685 1939 for my $n (@attr_names) {
2686 3951 ▶ if (grep { $n eq $_ } (qw/-join/) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$n eq $_;} "-join") 0 3951 3951
2687 0 $extra_checks{$n}++;
2688 0 next;
2689 }
2690  
2691 3951 my $attr = $attrs->{$n};
2692  
2693 3951 ▶ next if not defined $attr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $attr 3924 27 3951
2694  
2695 27 ▶ if (ref $attr eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $attr eq 'HASH') { } 0 27 27
elsif (ref $attr eq 'ARRAY') { } 13 14 27
2696 0 ▶ return 1 if keys %$attr;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$attr 0 0 0
2697 }
2698 elsif (ref $attr eq 'ARRAY') {
2699 13 ▶ return 1 if @$attr;
Branch: 1 branch
BranchTrueFalseTotal
if @$attr 13 0 13
2700 }
2701 else {
2702 14 ▶ return 1 if $attr;
Branch: 1 branch
BranchTrueFalseTotal
if $attr 9 5 14
2703 }
2704 }
2705  
2706 # a resolved join is expressed as a multi-level from
2707 return 1 if (
2708 $extra_checks{-join}
2709 and
2710 ref $attrs->{from} eq 'ARRAY'
2711 and
2712 0 ▶ @{$attrs->{from}} > 1
Branch: 1 branch
BranchTrueFalseTotal
if $extra_checks{"-join"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} > 1 0 1917 1917
Condition33%2/6
$extra_checks{"-join"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} > 1
!ll&&!rl&&r
191700
$extra_checks{"-join"} and ref $attrs->{"from"} eq "ARRAY"
!ll&&!rl&&r
191700
MC/DC0%0/3
$extra_checks{"-join"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} > 1
$extra_checks{"-join"} ref $attrs->{"from"} eq "ARRAY" @{$attrs->{"from"};} > 1
Truth table25%1/4
A and B and C
A= $extra_checks{"-join"}B= ref $attrs->{"from"} eq "ARRAY"C= @{$attrs->{"from"};} > 1
ABCresult
0XX0
10X0
1100
1111
2713 );
2714  
2715 1917 return 0;
2716 }
2717  
2718 # _remove_alias
2719 #
2720 # Remove the specified alias from the specified query hash. A copy is made so
2721 # the original query is not modified.
2722  
2723 14866 ▶sub _remove_alias {
Subroutine _remove_alias: called CC=5 SCAR=16.2
2724 14866 my ($self, $query, $alias) = @_;
2725  
2726 14866 ▶ my %orig = %{ $query || {} };
Condition50%1/2
$query || {}
l!l
148660
MC/DC0%0/1
$query || {}
$query
Truth table50%1/2
A
A= $query
Aresult
11
00
2727 14866 my %unaliased;
2728  
2729 14866 foreach my $key (keys %orig) {
2730 24000 ▶ if ($key !~ /\./) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($key =~ /\./) 20962 3038 24000
2731 20962 $unaliased{$key} = $orig{$key};
2732 20962 next;
2733 }
2734 3038 ▶ $unaliased{$1} = $orig{$key}
Branch: 1 branch
BranchTrueFalseTotal
if $key =~ /^(?:\Q$alias\E\.)?([^.]+)$/ 3038 0 3038
2735 if $key =~ m/^(?:\Q$alias\E\.)?([^.]+)$/;
2736 }
2737  
2738 14866 return \%unaliased;
2739 }
2740  
2741  
2742 917 ▶sub as_query {
Subroutine as_query: called CC=1 SCAR=0.0
Pod documented
2743 917 my $self = shift;
2744  
2745 917 my $attrs = { %{ $self->_resolved_attrs } };
2746  
2747 my $aq = $self->result_source->storage->_select_args_to_query (
2748 917 $attrs->{from}, $attrs->{select}, $attrs->{where}, $attrs
2749 );
2750  
2751 914 $aq;
2752 }
2753  
2754  
2755 21 ▶sub find_or_new {
Subroutine find_or_new: called CC=6 SCAR=18.2
Pod documented
2756 21 my $self = shift;
2757 21 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 12 9 21
Condition66%2/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
9012
MC/DC50%1/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table66%2/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2758 21 ▶ my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 21 0 21
2759 21 ▶ if (keys %$hash and my $row = $self->_find_for_write($hash, $attrs, 'find_or_new') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_new")) 5 11 16
Condition66%2/3
keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_new")
!ll&&!rl&&r
0165
MC/DC50%1/2
keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_new")
keys %$hash my $row = $self->_find_for_write($hash, $attrs, "find_or_new")
Truth table66%2/3
A and B
A= keys %$hashB= my $row = $self->_find_for_write($hash, $attrs, "find_or_new")
ABresult
0X0
100
111
2760 5 return $row;
2761 }
2762 11 return $self->new_result($hash);
2763 }
2764  
2765  
2766 10 ▶sub find_or_new_async {
Subroutine find_or_new_async: called CC=4 SCAR=14.3
Pod documented
2767 10 my $self = shift;
2768 10 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 0 10 10
Condition33%1/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
1000
MC/DC0%0/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table33%1/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2769 10 ▶ my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 10 0 10
2770  
2771 return $self->_rs_run_async('find_or_new',
2772 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2773 6 my ($backend, $fc) = @_;
2774 6 ▶ return $fc->done($self->new_result($hash)) unless keys %$hash;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$hash 0 6 6
2775  
2776 6 ▶ return $self->_find_for_write_async($hash, $attrs, 'find_or_new')->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2777 6 my ($row) = @_;
2778 6 ▶ return $row if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 2 4 6
2779 4 return $self->new_result($hash);
2780 6 });
2781 },
2782 3 ▶ sub { $self->find_or_new($hash, $attrs) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2783 10 );
2784 }
2785  
2786  
2787 775 ▶sub create {
Subroutine create: called CC=2 SCAR=7.2
Pod documented
2788 #my ($self, $col_data) = @_;
2789 775 ▶ assert_no_internal_indirect_calls and fail_on_internal_call;
Branch: 1 branch
BranchTrueFalseTotal
&assert_no_internal_indirect_calls() and fail_on_internal_call() 0 775 775
2790 775 return shift->new_result(shift)->insert;
2791 }
2792  
2793  
2794 24 ▶sub find_or_create {
Subroutine find_or_create: called CC=6 SCAR=18.2
Pod documented
2795 24 my $self = shift;
2796 24 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 13 11 24
Condition66%2/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
11013
MC/DC50%1/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table66%2/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2797 24 ▶ my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 24 0 24
2798 24 ▶ if (keys %$hash and my $row = $self->_find_for_write($hash, $attrs, 'find_or_create') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_create")) 6 12 18
Condition66%2/3
keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_create")
!ll&&!rl&&r
0186
MC/DC50%1/2
keys %$hash and my $row = $self->_find_for_write($hash, $attrs, "find_or_create")
keys %$hash my $row = $self->_find_for_write($hash, $attrs, "find_or_create")
Truth table66%2/3
A and B
A= keys %$hashB= my $row = $self->_find_for_write($hash, $attrs, "find_or_create")
ABresult
0X0
100
111
2799 6 return $row;
2800 }
2801 12 return $self->new_result($hash)->insert;
2802 }
2803  
2804  
2805 10 ▶sub find_or_create_async {
Subroutine find_or_create_async: called CC=4 SCAR=14.3
Pod documented
2806 10 my $self = shift;
2807 10 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 0 10 10
Condition33%1/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
1000
MC/DC0%0/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table33%1/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2808 10 ▶ my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 10 0 10
2809  
2810 return $self->_rs_run_async('find_or_create',
2811 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2812 6 my ($backend, $fc) = @_;
2813 6 ▶ return $self->create_async($hash) unless keys %$hash;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$hash 0 6 6
2814  
2815 6 ▶ return $self->_find_for_write_async($hash, $attrs, 'find_or_create')->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2816 6 my ($row) = @_;
2817 6 ▶ return $row if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 2 4 6
2818 4 return $self->create_async($hash);
2819 6 });
2820 },
2821 3 ▶ sub { $self->find_or_create($hash, $attrs) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2822 10 );
2823 }
2824  
2825  
2826 835 ▶sub update_or_create {
Subroutine update_or_create: called CC=5 SCAR=16.2
Pod documented
2827 835 my $self = shift;
2828 835 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 22 813 835
Condition66%2/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
813022
MC/DC50%1/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table66%2/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2829 835 ▶ my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 835 0 835
2830  
2831 # find() only accepts a condition it can reduce to concrete columns on this
2832 # table, so the lookup drops any relation-valued key that does not resolve to
2833 # a concrete foreign-key condition. The FULL condition -- relation keys
2834 # included -- still reaches the row layer via update()/insert below, which
2835 # owns nested-relation semantics.
2836 835 my @lookup_cols;
2837 835 my $row = $self->_find_for_write($self->_find_lookup_cond($cond), $attrs, 'update_or_create', \@lookup_cols);
2838 831 ▶ if (defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $row) { } 13 818 831
2839 13 $row->update($self->_update_data_for_found_row($cond, \@lookup_cols));
2840 }
2841 else {
2842 818 $row = $self->new_result($cond)->insert;
2843 }
2844  
2845 826 return $row;
2846 }
2847  
2848 # Build the find() lookup for update_or_create: the passed condition with every
2849 # relation-valued key that does NOT reduce to a concrete foreign-key condition
2850 # on this table removed. A resolvable belongs_to (FK-bearing hashref, or a
2851 # blessed related object) resolves join-free to { self_fk => <defined value> }
2852 # and stays, so find() folds it in as before. A has_many / has_one / might_have
2853 # searched by its own non-key columns is either crosstable, or resolves join-free
2854 # to { self_pk => undef }; leaving it in the lookup would make find() reject it
2855 # (before the guard, it silently clobbered the key with an undef FK). Such keys
2856 # are dropped from the LOOKUP only -- update_or_create still passes the full
2857 # condition to the row layer, which owns nested-relation semantics. See ADR 0034.
2858 842 ▶sub _find_lookup_cond {
Subroutine _find_lookup_cond: called CC=5 SCAR=16.1
2859 842 my ($self, $cond) = @_;
2860  
2861 842 my $rsrc = $self->result_source;
2862 842 my %lookup = %$cond;
2863  
2864 842 for my $key (keys %lookup) {
2865 893 ▶ next unless ref $lookup{$key} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $lookup{$key} eq "HASH" 888 5 893
2866 5 ▶ next unless $rsrc->relationship_info($key);
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->relationship_info($key) 0 5 5
2867  
2868 my ($rel_cond, $crosstable)
2869 5 = $self->_resolve_related_cond($rsrc, $key, $lookup{$key});
2870  
2871 5 ▶ delete $lookup{$key}
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_related_cond_is_concrete($rel_cond, $crosstable) 4 1 5
2872 unless $self->_related_cond_is_concrete($rel_cond, $crosstable);
2873 }
2874  
2875 842 return \%lookup;
2876 }
2877  
2878  
2879 10 ▶sub update_or_create_async {
Subroutine update_or_create_async: called CC=4 SCAR=14.2
Pod documented
2880 10 my $self = shift;
2881 10 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 0 10 10
Condition33%1/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
1000
MC/DC0%0/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table33%1/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
2882 10 ▶ my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 10 0 10
2883  
2884 return $self->_rs_run_async('update_or_create',
2885 6 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2886 6 my ($backend, $fc) = @_;
2887  
2888 6 my @lookup_cols;
2889 6 ▶ return $self->_find_for_write_async($self->_find_lookup_cond($cond), $attrs, 'update_or_create', \@lookup_cols)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2890 6 my ($row) = @_;
2891 6 ▶ return $row->update_async($self->_update_data_for_found_row($cond, \@lookup_cols)) if defined $row;
Branch: 1 branch
BranchTrueFalseTotal
if defined $row 4 2 6
2892 2 return $self->create_async($cond);
2893 6 });
2894 },
2895 3 ▶ sub { $self->update_or_create($cond, $attrs) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2896 10 );
2897 }
2898  
2899  
2900 379 my %_upsert_options = map { $_ => 1 } qw(
2901 key conflict_target on_conflict update update_where result fallback relations
2902 );
2903  
2904 379 my %_upsert_result_shapes = map { $_ => 1 } qw(
2905 row_or_undef row_or_die count void
2906 );
2907  
2908 # What a single entry of the `relations` structure may say. Deliberately just
2909 # the conflict target plus its own nesting: on_conflict, update and result are
2910 # whole-cascade or whole-statement decisions, not per-part ones.
2911 379 my %_upsert_relation_options = map { $_ => 1 } qw(
2912 key conflict_target relations
2913 );
2914  
2915  
2916 15 ▶sub upsert_async {
Subroutine upsert_async: called CC=3 SCAR=11.0
Pod documented
2917 15 my ($self, $data, $opts) = @_;
2918  
2919 15 my $rsrc = $self->result_source;
2920 15 ▶ my $sname = $rsrc->source_name || $rsrc->result_class || 'this result source';
Condition40%2/5
$rsrc->source_name || $rsrc->result_class || 'this result source'
l!l
150
$rsrc->source_name or $rsrc->result_class
l!l&&r!l&&!r
1500
MC/DC0%0/2
$rsrc->source_name || $rsrc->result_class || 'this result source'
$rsrc->source_name $rsrc->result_class
Truth table33%1/3
A or B
A= $rsrc->source_nameB= $rsrc->result_class
ABresult
1X1
011
000
2921  
2922 return $self->_rs_run_async('upsert',
2923 8 ▶ sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2924 8 my ($backend, $fc, $mode, @rest) = @_;
2925  
2926 # Cascade and fallback are each already more than one statement (a
2927 # transactional multi-part write, and a racy client-side read-then-write
2928 # respectively) -- not expressible as a single insert_async. Run
2929 # synchronously and resolve immediately, same precedent as
2930 # create_async's related-object multi-create (ADR 0031).
2931 8 ▶ if ($mode eq 'cascade') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "cascade") 1 7 8
2932 return $self->_async_ctx_or_sync_punt($fc, 'upsert',
2933 'a cascade upsert is a transactional multi-part write',
2934 1 ▶ sub { $self->_upsert_cascade($data, $opts, $rest[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2935 }
2936 7 ▶ if ($mode eq 'fallback') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "fallback") 3 4 7
2937 return $self->_async_ctx_or_sync_punt($fc, 'upsert',
2938 'the fallback upsert is a racy client-side read-then-write',
2939 3 ▶ sub { $self->_upsert_fallback($data, $opts, $rest[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2940 }
2941  
2942 4 my ($storage, $new, $rowdata, $storage_opts, $shape, $action) = @rest;
2943  
2944 # No async transport contract carries an affected-row count for INSERT
2945 # SQL (insert_async always resolves the returned-columns hashref) -- see
2946 # the POD above. Same sync-and-resolve degrade as cascade/fallback.
2947 4 ▶ if ($shape eq 'count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "count") 1 3 4
2948 return $self->_async_ctx_or_sync_punt($fc, 'upsert',
2949 'no async transport carries an affected-row count for an upsert',
2950 1 ▶ sub { $self->upsert($data, $opts) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2951 }
2952  
2953 3 ▶ return $backend->insert_async($rsrc, { %$rowdata }, $storage_opts)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2954 3 my ($returned) = @_;
2955 3 ▶ return $fc->done() if $shape eq 'void';
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "void" 1 2 3
2956 2 return $fc->done(
2957 $self->_upsert_finish($rsrc, $sname, $shape, $opts, $action, $new, $rowdata, $returned)
2958 );
2959 3 });
2960 },
2961 1 ▶ sub { $self->upsert($data, $opts) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2962 13 ▶ sub { $self->_upsert_prepare($data, $opts) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2963 15 );
2964 }
2965  
2966 # $prebuilt is internal: the cascade has already built the Row (it needed one
2967 # as the vehicle for set_from_related) and hands it over so that column
2968 # setters run exactly as often here as they do on a flat call.
2969 145 ▶sub upsert {
Subroutine upsert: called CC=8 SCAR=21.1
Pod documented
2970 145 my ($self, $data, $opts, $prebuilt) = @_;
2971  
2972 145 my $rsrc = $self->result_source;
2973 145 ▶ my $sname = $rsrc->source_name || $rsrc->result_class || 'this result source';
Condition40%2/5
$rsrc->source_name || $rsrc->result_class || 'this result source'
l!l
1450
$rsrc->source_name or $rsrc->result_class
l!l&&r!l&&!r
14500
MC/DC0%0/2
$rsrc->source_name || $rsrc->result_class || 'this result source'
$rsrc->source_name $rsrc->result_class
Truth table33%1/3
A or B
A= $rsrc->source_nameB= $rsrc->result_class
ABresult
1X1
011
000
2974  
2975 145 my ($mode, @rest) = $self->_upsert_prepare($data, $opts, $prebuilt);
2976  
2977 95 ▶ return $self->_upsert_cascade($data, $opts, $rest[0]) if $mode eq 'cascade';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "cascade" 32 63 95
2978 63 ▶ return $self->_upsert_fallback($data, $opts, $rest[0]) if $mode eq 'fallback';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "fallback" 6 57 63
2979  
2980 57 my ($storage, $new, $rowdata, $storage_opts, $shape, $action) = @rest;
2981  
2982 57 my $returned = $storage->insert($rsrc, { %$rowdata }, $storage_opts);
2983  
2984 55 ▶ return if $shape eq 'void';
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "void" 23 32 55
2985  
2986 # DBI hands back the string '0E0' -- zero but true -- for a statement that
2987 # affected no rows, which is exactly what a conflicting upsert can do.
2988 # if (my $n = $rs->upsert(..., { result => 'count' })) must not read
2989 # "nothing happened" as true, and upsert throws on failure, so the
2990 # zero-but-true signal carries no information here: hand back a number.
2991 32 ▶ return 0 + ( $storage_opts->{affected_rows} || 0 ) if $shape eq 'count';
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "count" 3 29 32
Condition50%1/2
$storage_opts->{'affected_rows'} || 0
l!l
30
MC/DC0%0/1
$storage_opts->{'affected_rows'} || 0
$storage_opts->{'affected_rows'}
Truth table50%1/2
A
A= $storage_opts->{'affected_rows'}
Aresult
11
00
2992  
2993 29 return $self->_upsert_finish($rsrc, $sname, $shape, $opts, $action, $new, $rowdata, $returned);
2994 }
2995  
2996 # Shared, non-DB-touching preparation for upsert() and upsert_async(): option
2997 # validation, conflict-target/update-set resolution, the capability gate.
2998 # Exists so the async twin cannot drift from the sync rules --
2999 # there is exactly one place that decides what a given call means. Returns a
3000 # mode plus whatever the caller needs for it; every validation failure and the
3001 # unsupported-without-fallback capability gate throw here, same as always, and
3002 # the caller lets that propagate:
3003 #
3004 # ('cascade', $shape)
3005 # ('fallback', $shape)
3006 # ('flat', $storage, $new, \%rowdata, \%storage_opts, $shape, $action)
3007 #
3008 # $prebuilt is internal: the cascade has already built the Row (it needed one
3009 # as the vehicle for set_from_related) and hands it over so that column
3010 # setters run exactly as often here as they do on a flat call.
3011 158 ▶sub _upsert_prepare {
Subroutine _upsert_prepare: called CC=75 SCAR=43.2
3012 158 my ($self, $data, $opts, $prebuilt) = @_;
3013  
3014 158 my $rsrc = $self->result_source;
3015 158 ▶ my $sname = $rsrc->source_name || $rsrc->result_class || 'this result source';
Condition40%2/5
$rsrc->source_name || $rsrc->result_class || 'this result source'
l!l
1580
$rsrc->source_name or $rsrc->result_class
l!l&&r!l&&!r
15800
MC/DC0%0/2
$rsrc->source_name || $rsrc->result_class || 'this result source'
$rsrc->source_name $rsrc->result_class
Truth table33%1/3
A or B
A= $rsrc->source_nameB= $rsrc->result_class
ABresult
1X1
011
000
3016  
3017 158 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" and keys %$data 4 154 158
Condition100%3/3
ref $data eq "HASH" and keys %$data
!ll&&!rl&&r
22154
MC/DC100%2/2
ref $data eq "HASH" and keys %$data
ref $data eq "HASH" keys %$data
Truth table100%3/3
A and B
A= ref $data eq "HASH"B= keys %$data
ABresult
0X0
100
111
3018 'upsert() takes a non-empty hashref of column data as its first argument'
3019 ) unless ref $data eq 'HASH' and keys %$data;
3020  
3021 154 ▶ $opts ||= {};
Condition100%2/2
$opts ||= {}
l!l
13915
MC/DC100%1/1
$opts ||= {}
$opts
Truth table100%2/2
A
A= $opts
Aresult
11
00
3022 154 ▶ $self->throw_exception('upsert() takes a hashref of options as its second argument')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opts eq "HASH" 1 153 154
3023 unless ref $opts eq 'HASH';
3024  
3025 # ---- option validation. Engine-independent and complete before any SQL is
3026 # ---- built, so an invalid call is invalid everywhere (ADR 0036).
3027  
3028 153 ▶ if (my @unknown = sort grep { ! $_upsert_options{$_} } keys %$opts) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@unknown) = sort(grep({not $_upsert_options{$_};} keys %$opts))) 2 151 153
3029 2 $self->throw_exception(
3030 "upsert(): unknown option(s) '" . CORE::join("', '", @unknown) . "' -- valid "
3031 . 'options are ' . CORE::join(', ', sort keys %_upsert_options)
3032 );
3033 }
3034  
3035 $self->throw_exception(
3036 "upsert(): relations must be a hashref of relationship => "
3037 . '{ key => $constraint | conflict_target => \@columns }'
3038 151 ▶ ) if exists $opts->{relations} and ref $opts->{relations} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"relations"} and ref $opts->{"relations"} ne "HASH" 1 150 151
Condition100%3/3
exists $opts->{"relations"} and ref $opts->{"relations"} ne "HASH"
!ll&&!rl&&r
123271
MC/DC100%2/2
exists $opts->{"relations"} and ref $opts->{"relations"} ne "HASH"
exists $opts->{"relations"} ref $opts->{"relations"} ne "HASH"
Truth table100%3/3
A and B
A= exists $opts->{"relations"}B= ref $opts->{"relations"} ne "HASH"
ABresult
0X0
100
111
3039  
3040 150 ▶ my $action = defined $opts->{on_conflict} ? $opts->{on_conflict} : 'update';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'on_conflict'} ? : 8 142 150
3041 150 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $action eq "update" or $action eq "nothing" 1 149 150
Condition100%3/3
$action eq "update" or $action eq "nothing"
l!l&&r!l&&!r
14271
MC/DC100%2/2
$action eq "update" or $action eq "nothing"
$action eq "update" $action eq "nothing"
Truth table100%3/3
A or B
A= $action eq "update"B= $action eq "nothing"
ABresult
1X1
011
000
3042 "upsert(): on_conflict must be 'update' or 'nothing', not '$action'"
3043 ) unless $action eq 'update' or $action eq 'nothing';
3044  
3045 149 ▶ my $shape = defined $opts->{result} ? $opts->{result} : 'row_or_undef';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'result'} ? : 63 86 149
3046 $self->throw_exception(
3047 "upsert(): result must be one of " . CORE::join(', ', sort keys %_upsert_result_shapes)
3048 . " -- '$shape' is not a return shape upsert can guarantee"
3049 149 ▶ ) unless $_upsert_result_shapes{$shape};
Branch: 1 branch
BranchTrueFalseTotal
unless $_upsert_result_shapes{$shape} 2 147 149
3050  
3051 # row_or_die means "never hand back nothing"; DO NOTHING exists in order to
3052 # possibly write nothing. The combination is refused before any SQL is built.
3053 147 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "row_or_die" and $action eq "nothing" 1 146 147
Condition100%3/3
$shape eq "row_or_die" and $action eq "nothing"
!ll&&!rl&&r
125211
MC/DC100%2/2
$shape eq "row_or_die" and $action eq "nothing"
$shape eq "row_or_die" $action eq "nothing"
Truth table100%3/3
A and B
A= $shape eq "row_or_die"B= $action eq "nothing"
ABresult
0X0
100
111
3054 "upsert(): result => 'row_or_die' cannot be combined with "
3055 . "on_conflict => 'nothing' -- DO NOTHING may legitimately write no row"
3056 ) if $shape eq 'row_or_die' and $action eq 'nothing';
3057  
3058 # ---- the conditional conflict branch: DO UPDATE ... WHERE
3059 #
3060 # Core does not look inside the condition, exactly as search() does not look
3061 # inside its \%cond: the shape is checked, the content is the driver's and
3062 # the engine's. What core does own is the combinations in which a condition
3063 # cannot mean anything.
3064 146 my $update_where;
3065 146 ▶ if (exists $opts->{update_where}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"update_where"}) 17 129 146
3066 17 $update_where = $opts->{update_where};
3067  
3068 17 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $update_where eq "HASH" or ref $update_where eq "ARRAY" or &is_literal_value($update_where) 2 15 17
Condition100%6/6
ref $update_where eq "HASH" or ref $update_where eq "ARRAY" or &is_literal_value($update_where)
l!l&&r!l&&!r
1322
ref $update_where eq "HASH" or ref $update_where eq "ARRAY"
l!l&&r!l&&!r
1124
MC/DC100%3/3
ref $update_where eq "HASH" or ref $update_where eq "ARRAY" or &is_literal_value($update_where)
ref $update_where eq "HASH" ref $update_where eq "ARRAY" &is_literal_value($update_where)
Truth table100%4/4
A or B or C
A= ref $update_where eq "HASH"B= ref $update_where eq "ARRAY"C= &is_literal_value($update_where)
ABCresult
1XX1
01X1
0011
0000
3069 'upsert(): update_where must be a SQL::Abstract condition (a hashref or '
3070 . "an arrayref) or a literal (\\'sql' / \\[ 'sql', \@bind ])"
3071 ) unless ref $update_where eq 'HASH'
3072 or ref $update_where eq 'ARRAY'
3073 or is_literal_value($update_where);
3074  
3075 # An empty condition is not "nothing excluded", it is a condition that was
3076 # meant to say something -- most likely built from a variable that came out
3077 # empty. Silently writing everything is the one outcome the option exists
3078 # to prevent.
3079 15 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if ref $update_where eq "HASH" and not keys %$update_where or ref $update_where eq "ARRAY" and not @$update_where 2 13 15
Condition100%9/9
ref $update_where eq "HASH" and not keys %$update_where or ref $update_where eq "ARRAY" and not @$update_where
l!l&&r!l&&!r
1113
ref $update_where eq "HASH" and not keys %$update_where
!ll&&!rl&&r
4101
ref $update_where eq "ARRAY" and not @$update_where
!ll&&!rl&&r
1211
MC/DC100%4/4
ref $update_where eq "HASH" and not keys %$update_where or ref $update_where eq "ARRAY" and not @$update_where
ref $update_where eq "HASH" not keys %$update_where ref $update_where eq "ARRAY" not @$update_where
Truth table71%5/7
A and not(B) or C and not(D)
A= ref $update_where eq "HASH"B= not keys %$update_whereC= ref $update_where eq "ARRAY"D= not @$update_where
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
3080 'upsert(): update_where is empty -- an empty condition would make the '
3081 . 'conflict branch write unconditionally, which is what leaving the '
3082 . 'option out already does'
3083 ) if ( ref $update_where eq 'HASH' and ! keys %$update_where )
3084 or ( ref $update_where eq 'ARRAY' and ! @$update_where );
3085  
3086 13 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $action eq "nothing" 1 12 13
3087 "upsert(): update_where has no meaning with on_conflict => 'nothing' -- "
3088 . 'there is no update branch to put a condition on'
3089 ) if $action eq 'nothing';
3090  
3091 # Same class of refusal as row_or_die + DO NOTHING above, and for the same
3092 # reason: a conditional update exists in order to possibly write nothing,
3093 # so the two promises contradict each other by construction rather than by
3094 # data. Refusing it here also keeps the runtime diagnosis honest -- the
3095 # row_or_die throw further down blames the table shape ("this follows from
3096 # the table shape, not from the data"), which is precisely the wrong
3097 # explanation for a condition that did not hold.
3098 12 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "row_or_die" 1 11 12
3099 "upsert(): result => 'row_or_die' cannot be combined with update_where "
3100 . '-- a conditional DO UPDATE writes no row when the condition does not '
3101 . 'hold, so a row cannot be guaranteed'
3102 ) if $shape eq 'row_or_die';
3103 }
3104  
3105 140 ▶ if (defined $opts->{fallback}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"fallback"}) 17 123 140
3106 $self->throw_exception(
3107 "upsert(): the only supported fallback is 'update_or_create', not "
3108 . "'$opts->{fallback}'"
3109 17 ▶ ) unless $opts->{fallback} eq 'update_or_create';
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"fallback"} eq "update_or_create" 1 16 17
3110  
3111 # update_or_create always writes, and always writes everything it is
3112 # given. Rather than let the fallback path mean something else than the
3113 # atomic path, refuse the two combinations where it would.
3114 16 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $action eq "nothing" 1 15 16
3115 "upsert(): fallback => 'update_or_create' cannot express "
3116 . "on_conflict => 'nothing' -- update_or_create always writes. Use "
3117 . 'find_or_create() at the call site for that shape'
3118 ) if $action eq 'nothing';
3119  
3120 $self->throw_exception(
3121 "upsert(): fallback => 'update_or_create' cannot express a restricted "
3122 . "'update' set -- update_or_create writes every supplied column"
3123 15 ▶ ) if exists $opts->{update};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"update"} 1 14 15
3124  
3125 # ... and it writes them unconditionally. Dropping the condition on the
3126 # fallback path would turn the guard the caller asked for into the
3127 # last-write-wins overwrite it exists to prevent, on whichever engine the
3128 # fallback happens to engage.
3129 $self->throw_exception(
3130 "upsert(): fallback => 'update_or_create' cannot express update_where "
3131 . '-- update_or_create writes unconditionally, so the fallback path would '
3132 . 'overwrite exactly the rows the condition protects'
3133 14 ▶ ) if exists $opts->{update_where};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"update_where"} 1 13 14
3134  
3135 # update_or_create finds by a *named* unique constraint; there is no way
3136 # to hand it a bare column list. Silently dropping the target would aim
3137 # the fallback at whatever constraint find()'s heuristics like best --
3138 # i.e. at a different row than the atomic path targets.
3139 $self->throw_exception(
3140 "upsert(): fallback => 'update_or_create' cannot express "
3141 . 'conflict_target -- update_or_create looks the row up by a named unique '
3142 . 'constraint, so the fallback would target a different constraint than '
3143 . 'the atomic statement. Name the constraint with key => $constraint if a '
3144 . 'fallback is wanted'
3145 13 ▶ ) if defined $opts->{conflict_target};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"conflict_target"} 3 10 13
3146 }
3147  
3148 $self->throw_exception(
3149 "upsert(): 'key' and 'conflict_target' are mutually exclusive -- name the "
3150 . 'unique constraint with key, or its columns with conflict_target'
3151 133 ▶ ) if defined $opts->{key} and defined $opts->{conflict_target};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"key"} and defined $opts->{"conflict_target"} 1 132 133
Condition100%3/3
defined $opts->{"key"} and defined $opts->{"conflict_target"}
!ll&&!rl&&r
122101
MC/DC100%2/2
defined $opts->{"key"} and defined $opts->{"conflict_target"}
defined $opts->{"key"} defined $opts->{"conflict_target"}
Truth table100%3/3
A and B
A= defined $opts->{"key"}B= defined $opts->{"conflict_target"}
ABresult
0X0
100
111
3152  
3153 # Nested relationship data is the cascading upsert: N atomic upserts in
3154 # dependency order inside one transaction. Everything above this point is
3155 # shared; from here the two are different operations.
3156 132 my $nested = ( $self->_upsert_split_nested($rsrc, $data) )[1];
3157  
3158 131 ▶ if (keys %$nested) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$nested) 36 95 131
3159 # A count across a cascade has no defined meaning, and void would deny the
3160 # cascade the identity it structurally needs to hand a parent's key to its
3161 # children. Refused here rather than half-way through the tree.
3162 36 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "count" or $shape eq "void" 2 34 36
Condition100%3/3
$shape eq "count" or $shape eq "void"
l!l&&r!l&&!r
1134
MC/DC100%2/2
$shape eq "count" or $shape eq "void"
$shape eq "count" $shape eq "void"
Truth table100%3/3
A or B
A= $shape eq "count"B= $shape eq "void"
ABresult
1X1
011
000
3163 "upsert(): result => '$shape' cannot be used with nested relationship "
3164 . 'data -- a cascade is more than one statement, so there is no single '
3165 . 'affected-row count, and void would withhold the identity the cascade '
3166 . 'needs to link the parts. Use row_or_undef or row_or_die'
3167 ) if $shape eq 'count' or $shape eq 'void';
3168  
3169 # update_or_create takes one named constraint for the top-level row and
3170 # nothing at all for the parts, so a fallback cascade would look every
3171 # part up by find()'s heuristics -- a different row than the atomic path
3172 # writes, which is exactly what refusing conflict_target here prevents.
3173 $self->throw_exception(
3174 "upsert(): fallback => 'update_or_create' cannot express a cascade -- "
3175 . 'it has no way to state a conflict target per part, so every nested '
3176 . "part would be looked up by find()'s heuristics. Branch on "
3177 . '$storage->_use_supports_upsert and call update_or_create() yourself if '
3178 . 'the racy client-side cascade is what you want'
3179 34 ▶ ) if defined $opts->{fallback};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"fallback"} 1 33 34
3180  
3181 33 return ('cascade', $shape);
3182 }
3183  
3184 # A per-relation target with no nested part to apply it to is a typo, not a
3185 # no-op -- the caller believes a cascade is happening and none is.
3186 95 ▶ if (my @orphan = sort keys %{ $opts->{relations} || {} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@orphan) = sort(keys %{$opts->{"relations"} or {};})) 1 94 95
Condition100%2/2
$opts->{'relations'} || {}
l!l
194
MC/DC100%1/1
$opts->{'relations'} || {}
$opts->{'relations'}
Truth table100%2/2
A
A= $opts->{'relations'}
Aresult
11
00
3187 1 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
@orphan > 1 ? : 0 1 1
3188 "upsert(): relations names '" . CORE::join("', '", @orphan) . "', but "
3189 . '%col_data has no nested data for '
3190 . (@orphan > 1 ? 'those relationships' : 'that relationship')
3191 . ' -- a per-relation conflict target with nothing to apply it to would '
3192 . 'silently do nothing'
3193 );
3194 }
3195  
3196 # Route the data through new_result: it validates the column names, folds in
3197 # the resultset's own condition exactly as create() does, and deflates
3198 # inflated columns. By the check above it cannot carry relationship data.
3199 94 ▶ my $new = $prebuilt || $self->new_result($data);
Condition100%3/3
$prebuilt || $self->new_result($data)
l!l&&r!l&&!r
31621
MC/DC0%0/2
$prebuilt || $self->new_result($data)
$prebuilt $self->new_result($data)
Truth table66%2/3
A || B
A= $prebuiltB= $self->new_result($data)
ABresult
1X1
011
000
3200 93 my %rowdata = $new->get_columns;
3201  
3202 # ---- conflict target
3203  
3204 93 my ($target, @target_cols);
3205 93 ▶ if (defined $opts->{key}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts->{'key'}) { } 10 83 93
elsif (defined(my $ct = $opts->{'conflict_target'})) { } 43 40 83
3206 # throws on an unknown constraint name -- before any SQL is built
3207 10 @target_cols = $rsrc->unique_constraint_columns($opts->{key});
3208  
3209 # Both halves travel down. The name is what an engine that can name a
3210 # constraint wants (PostgreSQL's ON CONSTRAINT); the resolved columns are
3211 # what the engines whose grammar knows a column list only can use at all
3212 # (SQLite). A SQLMaker is handed ($table, $data, $options) and no
3213 # ResultSource, so it cannot resolve the name itself -- passing the name
3214 # alone is what made key => $constraint unusable on those engines.
3215 9 $target = { constraint => $opts->{key}, columns => [ @target_cols ] };
3216 }
3217 elsif (defined( my $ct = $opts->{conflict_target} )) {
3218 43 ▶ if (ref $ct eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $ct eq 'ARRAY') { } 28 15 43
elsif (not length ref $ct and $ct eq 'any') { } 1 14 15
elsif (not length ref $ct) { } 13 1 14
3219 28 ▶ $self->throw_exception('upsert(): conflict_target is an empty list')
Branch: 1 branch
BranchTrueFalseTotal
unless @$ct 1 27 28
3220 unless @$ct;
3221 27 @target_cols = @$ct;
3222 27 $target = [ @$ct ];
3223 }
3224 ▶ elsif (! length ref $ct and $ct eq 'any') {
Condition100%3/3
not length ref $ct and $ct eq "any"
!ll&&!rl&&r
1131
MC/DC100%2/2
not length ref $ct and $ct eq "any"
not length ref $ct $ct eq "any"
Truth table100%3/3
not(A) and B
A= not length ref $ctB= $ct eq "any"
ABresult
0X0
100
111
3225 1 $target = 'any';
3226 }
3227 elsif (! length ref $ct) {
3228 13 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->has_column($ct) 1 12 13
3229 "upsert(): conflict_target '$ct' is not a column of $sname -- pass an "
3230 . "arrayref of columns, the string 'any', or name a unique constraint "
3231 . "with key => '$ct'"
3232 ) unless $rsrc->has_column($ct);
3233 12 @target_cols = ($ct);
3234 12 $target = [ $ct ];
3235 }
3236 else {
3237 1 $self->throw_exception(
3238 'upsert(): conflict_target must be an arrayref of columns, a single '
3239 . "column name, or the string 'any'"
3240 );
3241 }
3242  
3243 40 for my $col (@target_cols) {
3244 61 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->has_column($col) 1 60 61
3245 "upsert(): conflict_target column '$col' is not a column of $sname"
3246 ) unless $rsrc->has_column($col);
3247 }
3248 }
3249 else {
3250 40 my @pk = $rsrc->primary_columns;
3251 40 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @pk 1 39 40
3252 "upsert(): $sname has no primary key, so there is no conflict target to "
3253 . 'default to -- name one with key => $constraint or '
3254 . 'conflict_target => \@columns. upsert does not guess among the unique '
3255 . 'constraints'
3256 ) unless @pk;
3257  
3258 39 ▶ if (my @missing = grep { ! defined $rowdata{$_} } @pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@missing) = grep({not defined $rowdata{$_};} @pk)) 1 38 39
3259 1 $self->throw_exception(
3260 "upsert(): no conflict target given and the data does not supply the "
3261 . "primary key of $sname (missing: " . CORE::join(', ', @missing) . ') -- the '
3262 . 'statement could never collide and would silently degenerate into a '
3263 . 'plain INSERT. Name the target with key => $constraint or '
3264 . 'conflict_target => \@columns'
3265 );
3266 }
3267  
3268 38 @target_cols = @pk;
3269 38 $target = [ @pk ];
3270 }
3271  
3272 # ---- the update set
3273  
3274 86 my $set;
3275 86 ▶ if ($action eq 'nothing') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq 'nothing') { } 3 83 86
3276 $self->throw_exception(
3277 "upsert(): the 'update' option has no meaning with "
3278 . "on_conflict => 'nothing'"
3279 3 ▶ ) if exists $opts->{update};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"update"} 1 2 3
3280 }
3281 else {
3282 83 my %skip = map { $_ => 1 } (@target_cols, $rsrc->primary_columns);
3283  
3284 83 ▶ if (ref $opts->{update} eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $opts->{'update'} eq 'ARRAY') { } 11 72 83
elsif (ref $opts->{'update'} eq 'HASH') { } 2 70 72
elsif (exists $opts->{'update'}) { } 1 69 70
3285 11 for my $col (@{ $opts->{update} }) {
3286 11 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->has_column($col) 1 10 11
3287 "upsert(): update column '$col' is not a column of $sname"
3288 ) unless $rsrc->has_column($col);
3289  
3290 $self->throw_exception(
3291 "upsert(): update column '$col' is not among the values being "
3292 . 'inserted, so there is no attempted value to set it to -- supply it '
3293 . 'in the data, or use the update => { col => $expr } form'
3294 10 ▶ ) unless exists $rowdata{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $rowdata{$col} 1 9 10
3295 }
3296 9 $set = { map { $_ => { -attempted => $_ } } @{ $opts->{update} } };
3297 }
3298 elsif (ref $opts->{update} eq 'HASH') {
3299 2 for my $col (sort keys %{ $opts->{update} }) {
3300 3 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $rsrc->has_column($col) 1 2 3
3301 "upsert(): update column '$col' is not a column of $sname"
3302 ) unless $rsrc->has_column($col);
3303 }
3304 1 $set = { %{ $opts->{update} } };
3305 }
3306 elsif (exists $opts->{update}) {
3307 1 $self->throw_exception(
3308 'upsert(): update must be an arrayref of columns or a hashref of '
3309 . 'column => expression pairs'
3310 );
3311 }
3312 else {
3313 $set = {
3314 77 map { $_ => { -attempted => $_ } }
3315 69 grep { ! $skip{$_} }
3316 sort keys %rowdata
3317 };
3318 }
3319  
3320 79 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$set 2 77 79
3321 'upsert(): the conflict branch would set no column at all -- every '
3322 . "supplied column is part of the conflict target or the primary key of "
3323 . "$sname. Use on_conflict => 'nothing' if that is what you mean"
3324 ) unless keys %$set;
3325 }
3326  
3327 79 my $on_conflict = {
3328 target => $target,
3329 action => $action,
3330 set => $set
3331 };
3332  
3333 # Only when there is one: a driver that never sees the key renders exactly
3334 # the statement it rendered before this option existed.
3335 79 ▶ $on_conflict->{where} = $update_where if defined $update_where;
Branch: 1 branch
BranchTrueFalseTotal
if defined $update_where 8 71 79
3336  
3337 # ---- capability gate. No silent degradation: an engine without an atomic
3338 # ---- upsert throws unless the caller opted into the race for this call.
3339  
3340 79 my $storage = $rsrc->storage;
3341 79 ▶ my $supported = $storage->can('_use_supports_upsert')
Branch: 1 branch
BranchTrueFalseTotal
$storage->can('_use_supports_upsert') ? : 79 0 79
3342 ? $storage->_use_supports_upsert
3343 : 0;
3344  
3345 79 ▶ unless ($supported) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($supported) 17 62 79
3346 return ('fallback', $shape)
3347 17 ▶ if defined $opts->{fallback};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"fallback"} 9 8 17
3348  
3349 8 $self->_upsert_unsupported($storage);
3350 }
3351  
3352 # A second gate, for the one part of the structure a driver can ignore
3353 # without producing a single symptom. Every other dialect difference is
3354 # self-announcing: a driver that drops the conflict target emits invalid SQL
3355 # on PostgreSQL, one that ignores action => 'nothing' has no set to write.
3356 # A dropped WHERE renders a perfectly valid unconditional UPDATE -- the
3357 # last-write-wins overwrite the condition was written to prevent, silently.
3358 # So the driver has to say it renders conditions before core sends one.
3359 62 ▶ if (defined $update_where) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $update_where) 6 56 62
3360 6 ▶ my $conditional = $storage->can('_use_supports_upsert_where')
Branch: 1 branch
BranchTrueFalseTotal
$storage->can('_use_supports_upsert_where') ? : 6 0 6
3361 ? $storage->_use_supports_upsert_where
3362 : 0;
3363  
3364 6 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $conditional 1 5 6
3365 ref($storage) . ' does not declare the supports_upsert_where '
3366 . 'capability: this engine has no conditional conflict branch, or its '
3367 . 'driver does not render one. MySQL is the engine that cannot -- '
3368 . 'ON DUPLICATE KEY UPDATE has no WHERE, and a per-column IF() does not '
3369 . 'suppress the write. Drop update_where, or branch on '
3370 . '$storage->_use_supports_upsert_where'
3371 ) unless $conditional;
3372 }
3373  
3374 61 my %storage_opts = ( on_conflict => $on_conflict );
3375 61 ▶ $storage_opts{no_retrieve} = 1 if $shape eq 'void' or $shape eq 'count';
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "void" or $shape eq "count" 30 31 61
Condition100%3/3
$shape eq "void" or $shape eq "count"
l!l&&r!l&&!r
26431
MC/DC100%2/2
$shape eq "void" or $shape eq "count"
$shape eq "void" $shape eq "count"
Truth table100%3/3
A or B
A= $shape eq "void"B= $shape eq "count"
ABresult
1X1
011
000
3376  
3377 61 return ('flat', $storage, $new, \%rowdata, \%storage_opts, $shape, $action);
3378 }
3379  
3380 # Shared tail for the row_or_undef/row_or_die shapes of the flat upsert path
3381 # (both upsert() and upsert_async(), once each has its own $returned
3382 # hashref) -- void/count are decided by the caller before this is reached
3383 # (upsert_async's count degrades to sync entirely, see its POD). $returned is
3384 # the returned-columns hashref the write produced, same shape sync
3385 # $storage->insert and async insert_async both resolve.
3386 31 ▶sub _upsert_finish {
Subroutine _upsert_finish: called CC=6 SCAR=17.9
3387 31 my ($self, $rsrc, $sname, $shape, $opts, $action, $new, $rowdata, $returned) = @_;
3388  
3389 # row_or_undef / row_or_die: the written row can be named only when the
3390 # engine handed back every primary key column for it.
3391 31 my @pk = $rsrc->primary_columns;
3392 31 ▶ if (@pk and ! grep { ! defined $returned->{$_} } @pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pk and not grep({not defined $returned->{$_};} @pk)) 26 5 31
Condition100%3/3
@pk and not grep({not defined $returned->{$_};} @pk)
!ll&&!rl&&r
4126
MC/DC100%2/2
@pk and not grep({not defined $returned->{$_};} @pk)
@pk not grep({not defined $returned->{$_};} @pk)
Truth table100%3/3
A and not(B)
A= @pkB= not grep({not defined $returned->{$_};} @pk)
ABresult
0X0
100
111
3393 26 return $new->_store_inserted_columns($rowdata, $returned);
3394 }
3395  
3396 $self->throw_exception(
3397 5 ▶ "upsert(): result => 'row_or_die' asked for the written row, but the "
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "row_or_die" 2 3 5
3398 . "engine did not name it (no primary key came back for $sname). This "
3399 . 'follows from the table shape, not from the data'
3400 ) if $shape eq 'row_or_die';
3401  
3402 # The default is the one value nobody types, so its name cannot teach the
3403 # caller who needs teaching -- the runtime has to. Silenceable by passing
3404 # result => 'row_or_undef' explicitly.
3405 #
3406 # Not on the DO NOTHING branch though: a conflicting DO NOTHING writes no
3407 # row, so RETURNING yields none and no primary key can come back. That is
3408 # the documented, legitimate outcome of what the caller asked for, not an
3409 # engine failing to name what it wrote -- warning there would be false.
3410 carp_once(
3411 "upsert() on $sname could not name the row it wrote -- no primary key "
3412 . 'came back for it, so undef is returned. Pass result => "row_or_undef" '
3413 . 'explicitly to silence this, or result => "count" / "void" if the row is '
3414 . 'not needed'
3415 3 ▶ ) unless exists $opts->{result} or $action eq 'nothing';
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"result"} or $action eq "nothing" 1 2 3
Condition100%3/3
exists $opts->{"result"} or $action eq "nothing"
l!l&&r!l&&!r
111
MC/DC100%2/2
exists $opts->{"result"} or $action eq "nothing"
exists $opts->{"result"} $action eq "nothing"
Truth table100%3/3
A or B
A= exists $opts->{"result"}B= $action eq "nothing"
ABresult
1X1
011
000
3416  
3417 3 return undef;
3418 }
3419  
3420 # No capability, no upsert -- never a silent client-side two-step. Shared by
3421 # the flat path and the cascade, which asserts it before opening its
3422 # transaction rather than after (ADR 0036 section 3).
3423 9 ▶sub _upsert_unsupported {
Subroutine _upsert_unsupported: called CC=1 SCAR=0.0
3424 9 my ($self, $storage) = @_;
3425  
3426 9 $self->throw_exception(
3427 ref($storage) . ' does not declare the supports_upsert capability: this '
3428 . 'engine has no atomic upsert. Branch on '
3429 . '$storage->_use_supports_upsert and call update_or_create() (racy, '
3430 . "client-side) yourself, or pass fallback => 'update_or_create' to accept "
3431 . 'the race for this call'
3432 );
3433 }
3434  
3435 # The explicit, per-call fallback for engines without an atomic upsert. The
3436 # return mapping is pinned so the same call never changes return *type* with
3437 # the engine (ADR 0036 section 3).
3438 7 ▶sub _upsert_fallback {
Subroutine _upsert_fallback: called CC=4 SCAR=13.9
3439 7 my ($self, $data, $opts, $shape) = @_;
3440  
3441 # The fallback has to look the row up by the constraint the atomic statement
3442 # would have conflicted on -- anything else writes a different row than the
3443 # engine would have. Option validation refused fallback together with
3444 # conflict_target, so only two targets can reach here, and both are
3445 # expressible as update_or_create's key: the named constraint, or the
3446 # primary-key default (which upsert only takes when the data supplies every
3447 # PK column, so the lookup is always satisfiable). Without the explicit key
3448 # update_or_create would fall into find()'s heuristics mode, which ORs every
3449 # satisfiable unique constraint together.
3450 my $row = $self->update_or_create(
3451 $data,
3452 7 ▶ { key => defined $opts->{key} ? $opts->{key} : 'primary' }
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'key'} ? : 0 7 7
3453 );
3454  
3455 7 ▶ return if $shape eq 'void';
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "void" 1 6 7
3456 6 ▶ return 1 if $shape eq 'count'; # synthetic, not an affected-rows figure
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "count" 1 5 6
3457 5 return $row;
3458 }
3459  
3460 # ---- the cascading upsert (ADR 0036 section 1) --------------------------
3461 #
3462 # What is promised, and it is deliberately not "an atomic upsert": N atomic
3463 # upserts, in dependency order, inside one transaction -- all-or-nothing, and
3464 # every part individually free of the read-then-write race. No engine has a
3465 # multi-table upsert, so a cascade is inherently more than one statement.
3466  
3467 # Split \%data into this source's own columns and its nested relationship
3468 # parts. Same criterion DBIO::Row::new applies when it sorts multicreate data:
3469 # a non-literal ref under a key that names a relationship is a part; anything
3470 # else -- an inflated object, a literal \'NOW()', a plain value -- is a column.
3471 209 ▶sub _upsert_split_nested {
Subroutine _upsert_split_nested: called CC=11 SCAR=24.8
3472 209 my ($self, $rsrc, $data) = @_;
3473  
3474 209 my (%cols, %nested);
3475  
3476 209 for my $key (keys %$data) {
3477 508 my $val = $data->{$key};
3478  
3479 508 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (length ref $val and not &is_literal_value($val) and ref $val eq "HASH" || ref $val eq "ARRAY" || builtin::blessed($val)) 79 429 508
Condition83%10/12
length ref $val and not &is_literal_value($val) and ref $val eq "HASH" || ref $val eq "ARRAY" || builtin::blessed($val)
!ll&&!rl&&r
429079
length ref $val and not &is_literal_value($val)
!ll&&!rl&&r
428179
ref $val eq "HASH" or ref $val eq "ARRAY" or builtin::blessed($val)
l!l&&r!l&&!r
7720
ref $val eq "HASH" or ref $val eq "ARRAY"
l!l&&r!l&&!r
48292
MC/DC40%2/5
length ref $val and not &is_literal_value($val) and ref $val eq "HASH" || ref $val eq "ARRAY" || builtin::blessed($val)
length ref $val not &is_literal_value($val) ref $val eq "HASH" ref $val eq "ARRAY" builtin::blessed($val)
Truth table83%5/6
A and not(B) and C or D or E
A= length ref $valB= not &is_literal_value($val)C= ref $val eq "HASH"D= ref $val eq "ARRAY"E= builtin::blessed($val)
ABCDEresult
0XXXX0
10XXX0
110000
111XX1
1101X1
110011
3480 length ref $val
3481 and
3482 ! is_literal_value($val)
3483 and
3484 ( ref $val eq 'HASH' or ref $val eq 'ARRAY' or blessed $val )
3485 ) {
3486 79 ▶ if ($rsrc->has_relationship($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsrc->has_relationship($key)) 78 1 79
3487 78 $nested{$key} = $val;
3488 78 next;
3489 }
3490  
3491 # A many_to_many is an accessor over a bridge table, not a relationship,
3492 # so it would fall through to "no such column" and read like a typo.
3493 # Out of scope, and it says why: writing bridge rows reopens the very
3494 # deletion question has_many is deliberately kept out of.
3495 1 my $rclass = $rsrc->result_class;
3496 $self->throw_exception(
3497 "upsert(): '$key' is a many_to_many accessor, which the cascading "
3498 . 'upsert does not handle -- it would have to write link rows, and what '
3499 . 'to do with the link rows you did not list has no safe answer. Nest '
3500 . 'the bridge relationship itself instead, or use set_' . $key . '()'
3501 ) if $rclass
3502 and $rclass->can('_m2m_metadata')
3503 1 ▶ and $rclass->_m2m_metadata->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $rclass and $rclass->can("_m2m_metadata") and $rclass->_m2m_metadata->{$key} 1 0 1
Condition33%2/6
$rclass and $rclass->can("_m2m_metadata") and $rclass->_m2m_metadata->{$key}
!ll&&!rl&&r
001
$rclass and $rclass->can("_m2m_metadata")
!ll&&!rl&&r
001
MC/DC0%0/3
$rclass and $rclass->can("_m2m_metadata") and $rclass->_m2m_metadata->{$key}
$rclass $rclass->can("_m2m_metadata") $rclass->_m2m_metadata->{$key}
Truth table25%1/4
A and B and C
A= $rclassB= $rclass->can("_m2m_metadata")C= $rclass->_m2m_metadata->{$key}
ABCresult
0XX0
10X0
1100
1111
3504 }
3505  
3506 429 $cols{$key} = $val;
3507 }
3508  
3509 208 return (\%cols, \%nested);
3510 }
3511  
3512 # Build the whole cascade plan before the first statement runs.
3513 #
3514 # Everything checked here follows from static schema metadata and the shape of
3515 # the options -- never from data the server holds -- so a cascade that cannot
3516 # work fails on the first call in development rather than the day the "other"
3517 # unique constraint finally collides in production (ADR 0036 section 4).
3518 #
3519 # $want is the result shape this node has to deliver: 'row_or_die' whenever
3520 # something downstream needs the written row's identity, which is what makes
3521 # the identity preconditions apply.
3522 61 ▶sub _upsert_plan {
Subroutine _upsert_plan: called CC=59 SCAR=42.1
3523 61 my ($self, $rs, $data, $opts, $want, $filled, $path) = @_;
3524  
3525 61 my $rsrc = $rs->result_source;
3526 61 ▶ my $sname = $rsrc->source_name || $rsrc->result_class || 'this result source';
Condition40%2/5
$rsrc->source_name || $rsrc->result_class || 'this result source'
l!l
610
$rsrc->source_name or $rsrc->result_class
l!l&&r!l&&!r
6100
MC/DC0%0/2
$rsrc->source_name || $rsrc->result_class || 'this result source'
$rsrc->source_name $rsrc->result_class
Truth table33%1/3
A or B
A= $rsrc->source_nameB= $rsrc->result_class
ABresult
1X1
011
000
3527 61 ▶ my $at = length $path ? " for the nested '$path'" : '';
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 29 32 61
3528 61 ▶ my $hint = length $path
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 29 32 61
3529 ? "relations => { '$path' => { key => \$constraint } }"
3530 : 'key => $constraint or conflict_target => \@columns';
3531  
3532 61 my ($cols, $nested) = $self->_upsert_split_nested($rsrc, $data);
3533  
3534 # ---- the per-relation targets
3535  
3536 61 ▶ my $relopts = $opts->{relations} || {};
Condition100%2/2
$opts->{'relations'} || {}
l!l
2338
MC/DC100%1/1
$opts->{'relations'} || {}
$opts->{'relations'}
Truth table100%2/2
A
A= $opts->{'relations'}
Aresult
11
00
3537 61 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $relopts eq "HASH" 0 61 61
3538 "upsert(): relations$at must be a hashref of relationship => "
3539 . '{ key => $constraint | conflict_target => \@columns }'
3540 ) unless ref $relopts eq 'HASH';
3541  
3542 61 for my $rel (sort keys %$relopts) {
3543 $self->throw_exception(
3544 "upsert(): relations$at names '$rel', but there is no nested data for "
3545 . 'it -- a per-relation conflict target with nothing to apply it to would '
3546 . 'silently do nothing'
3547 27 ▶ ) unless exists $nested->{$rel};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $nested->{$rel} 1 26 27
3548  
3549 $self->throw_exception(
3550 "upsert(): relations$at => { '$rel' => ... } must be a hashref"
3551 26 ▶ ) unless ref $relopts->{$rel} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $relopts->{$rel} eq "HASH" 1 25 26
3552  
3553 25 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (my(@unknown) = sort(grep({not $_upsert_relation_options{$_};} keys %{$$relopts{$rel};}))) 2 23 25
3554 my @unknown =
3555 29 sort grep { ! $_upsert_relation_options{$_} } keys %{ $relopts->{$rel} }
3556 ) {
3557 2 $self->throw_exception(
3558 "upsert(): unknown option(s) '" . CORE::join("', '", @unknown) . "' for the "
3559 . "nested '$rel'$at -- a per-relation entry takes "
3560 . CORE::join(', ', sort keys %_upsert_relation_options)
3561 . '. on_conflict, update, update_where and result are decisions about '
3562 . 'the whole call, not about one part'
3563 );
3564 }
3565  
3566 $self->throw_exception(
3567 "upsert(): 'key' and 'conflict_target' are mutually exclusive, also for "
3568 . "the nested '$rel'$at"
3569 ) if defined $relopts->{$rel}{key}
3570 23 ▶ and defined $relopts->{$rel}{conflict_target};
Branch: 1 branch
BranchTrueFalseTotal
if defined $relopts->{$rel}{"key"} and defined $relopts->{$rel}{"conflict_target"} 1 22 23
Condition100%3/3
defined $relopts->{$rel}{"key"} and defined $relopts->{$rel}{"conflict_target"}
!ll&&!rl&&r
12101
MC/DC100%2/2
defined $relopts->{$rel}{"key"} and defined $relopts->{$rel}{"conflict_target"}
defined $relopts->{$rel}{"key"} defined $relopts->{$rel}{"conflict_target"}
Truth table100%3/3
A and B
A= defined $relopts->{$rel}{"key"}B= defined $relopts->{$rel}{"conflict_target"}
ABresult
0X0
100
111
3571 }
3572  
3573 # ---- dependency order: whose primary key becomes whose foreign key.
3574 #
3575 # This is the split DBIO::Row::insert performs for multicreate, applied to
3576 # the data instead of to constructed Row objects: _pk_depends_on answers
3577 # "must the part be written before us" (belongs_to -- its key becomes our
3578 # foreign key) or "does the part need us" (has_many / might_have -- our key
3579 # becomes theirs).
3580  
3581 56 my (@before, @after, @from_before);
3582  
3583 56 for my $rel (sort keys %$nested) {
3584 32 my $val = $nested->{$rel};
3585 32 my $info = $rsrc->relationship_info($rel);
3586 32 ▶ my $acc = $info->{attrs}{accessor} || '';
Condition50%1/2
$info->{'attrs'}{'accessor'} || ''
l!l
320
MC/DC0%0/1
$info->{'attrs'}{'accessor'} || ''
$info->{'attrs'}{'accessor'}
Truth table50%1/2
A
A= $info->{'attrs'}{'accessor'}
Aresult
11
00
3587 32 my $rel_rsrc = $rsrc->related_source($rel);
3588 32 ▶ my $sub_path = length $path ? "$path.$rel" : $rel;
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 1 31 32
3589 32 ▶ my $sub_opts = $relopts->{$rel} || {};
Condition100%2/2
$relopts->{$rel} || {}
l!l
2111
MC/DC100%1/1
$relopts->{$rel} || {}
$relopts->{$rel}
Truth table100%2/2
A
A= $relopts->{$rel}
Aresult
11
00
3590  
3591 32 ▶ my @list = ref $val eq 'ARRAY' ? @$val : ($val);
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 14 18 32
3592  
3593 32 for my $part (@list) {
3594 # A Row object is already a decision about identity: "link this one" and
3595 # "write these values" are different asks, and guessing between them is
3596 # the DWIM this API exists to avoid. The cascade upserts data.
3597 33 ▶ next if ref $part eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $part eq "HASH" 32 1 33
3598  
3599 1 ▶ $self->throw_exception(
Branch: 2 branches
BranchTrueFalseTotal
builtin::blessed($part) ? : 1 0 1
ref $part ? : 0 0 0
3600 "upsert(): the nested '$sub_path' is "
3601 . ( blessed $part ? 'a ' . ref($part) . ' object'
3602 : ref $part ? 'a ' . ref($part) . ' reference'
3603 : 'a plain scalar' )
3604 . ' -- the cascade upserts column data, so pass the columns '
3605 . '({ $row->get_columns }) or set the foreign key yourself. An existing '
3606 . 'Result object does not say whether you want it written or only linked'
3607 );
3608 }
3609  
3610 31 ▶ if (ref $val eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'ARRAY') { } 14 17 31
3611 14 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $acc eq "multi" 1 13 14
3612 "upsert(): the nested '$sub_path' is a list, but '$rel' is not a "
3613 . 'has_many -- pass a single hashref for a single related row'
3614 ) unless $acc eq 'multi';
3615 }
3616 else {
3617 17 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $acc eq "multi" 1 16 17
3618 "upsert(): the nested '$sub_path' is a single hashref, but '$rel' is "
3619 . 'a has_many -- pass an arrayref of hashrefs'
3620 ) if $acc eq 'multi';
3621 }
3622  
3623 29 my $cond = $info->{cond};
3624  
3625 # multi is always "after us" -- exactly as multicreate treats it. For a
3626 # single/filter accessor the direction is a schema question, and
3627 # _pk_depends_on is the one place in the codebase that answers it.
3628 29 ▶ my ($flat_part) = $acc eq 'multi'
Branch: 1 branch
BranchTrueFalseTotal
$acc eq 'multi' ? : 13 16 29
3629 ? ({})
3630 : $self->_upsert_split_nested($rel_rsrc, $val);
3631  
3632 29 ▶ if ($acc ne 'multi' and $rsrc->_pk_depends_on($rel, $flat_part)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($acc ne "multi" and $rsrc->_pk_depends_on($rel, $flat_part)) 15 14 29
Condition100%3/3
$acc ne "multi" and $rsrc->_pk_depends_on($rel, $flat_part)
!ll&&!rl&&r
13115
MC/DC100%2/2
$acc ne "multi" and $rsrc->_pk_depends_on($rel, $flat_part)
$acc ne "multi" $rsrc->_pk_depends_on($rel, $flat_part)
Truth table100%3/3
A and B
A= $acc ne "multi"B= $rsrc->_pk_depends_on($rel, $flat_part)
ABresult
0X0
100
111
3633 # its key becomes our foreign key: written before us, and it must be
3634 # able to name what it wrote
3635 15 push @before, {
3636 rel => $rel,
3637 node => $self->_upsert_plan(
3638 $rel_rsrc->resultset, $val, $sub_opts, 'row_or_die', [], $sub_path,
3639 ),
3640 };
3641  
3642 9 ▶ push @from_before, map { m/^self\.(.+)\z/ ? $1 : () } values %$cond
Branch: 2 branches
BranchTrueFalseTotal
if ref $cond eq "HASH" 9 0 9
/^self\.(.+)\z/ ? : 9 0 9
3643 if ref $cond eq 'HASH';
3644  
3645 9 next;
3646 }
3647  
3648 # our key becomes theirs: written after us. The foreign key is set the way
3649 # multicreate sets it, through the reverse relationship -- without one
3650 # nothing would link the child to us and the cascade would quietly write
3651 # an orphan.
3652 14 my @revs = sort keys %{ $rsrc->reverse_relationship_info($rel) };
3653 14 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @revs 1 13 14
3654 "upsert(): '$rel'$at has no reverse relationship back to $sname, so "
3655 . 'there is no way to derive the foreign key of the nested rows from the '
3656 . 'row written for it -- they would be written unlinked. Declare the '
3657 1 ▶ . "opposing relationship on @{[ $rel_rsrc->source_name || $rel_rsrc->result_class ]}"
Condition33%1/3
$rel_rsrc->source_name || $rel_rsrc->result_class
l!l&&r!l&&!r
100
MC/DC0%0/2
$rel_rsrc->source_name || $rel_rsrc->result_class
$rel_rsrc->source_name $rel_rsrc->result_class
Truth table33%1/3
A || B
A= $rel_rsrc->source_nameB= $rel_rsrc->result_class
ABresult
1X1
011
000
3658 ) unless @revs;
3659  
3660 my @child_filled = ref $cond eq 'HASH'
3661 13 ▶ ? map { m/^foreign\.(.+)\z/ ? $1 : () } keys %$cond
Branch: 2 branches
BranchTrueFalseTotal
ref $cond eq 'HASH' ? : 13 0 13
/^foreign\.(.+)\z/ ? : 13 0 13
3662 : ();
3663  
3664 push @after, {
3665 rel => $rel,
3666 revs => \@revs,
3667 nodes => [
3668 map {
3669 13 $self->_upsert_plan(
3670 $rel_rsrc->resultset, $_, $sub_opts, 'void', \@child_filled,
3671 $sub_path,
3672 )
3673 } @list
3674 ],
3675 };
3676 }
3677  
3678 # A part may legitimately carry no column of its own -- a might_have whose
3679 # only column is the foreign key it is handed. Carrying none and being
3680 # handed none is nothing at all.
3681 $self->throw_exception(
3682 44 ▶ 'upsert(): ' . (length $path ? "the nested '$path'" : $sname)
Branch: 2 branches
BranchTrueFalseTotal
unless keys %$cols or @$filled or @from_before 0 44 44
length $path ? : 0 0 0
Condition50%3/6
keys %$cols or @$filled or @from_before
l!l&&r!l&&!r
4400
keys %$cols or @$filled
l!l&&r!l&&!r
4310
MC/DC0%0/3
keys %$cols or @$filled or @from_before
keys %$cols @$filled @from_before
Truth table50%2/4
A or B or C
A= keys %$colsB= @$filledC= @from_before
ABCresult
1XX1
01X1
0011
0000
3683 . ' supplies no column of its own and is handed none by the rows around it '
3684 . '-- there is no row there to upsert'
3685 ) unless keys %$cols or @$filled or @from_before;
3686  
3687 # Children need our key, so we have to be able to name the row we wrote --
3688 # whatever the caller asked to get back.
3689 44 ▶ $want = 'row_or_die' if @after;
Branch: 1 branch
BranchTrueFalseTotal
if @after 11 33 44
3690 44 my $identity = $want eq 'row_or_die';
3691  
3692 # ---- the preconditions, all decided from static metadata
3693  
3694 44 my @pk = $rsrc->primary_columns;
3695  
3696 44 ▶ if ($identity) {
Branch: 1 branch
BranchTrueFalseTotal
if ($identity) 26 18 44
3697 26 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @pk 1 25 26
Condition50%1/2
$at || ' at the top level'
l!l
10
MC/DC0%0/1
$at || ' at the top level'
$at
Truth table50%1/2
A
A= $at
Aresult
11
00
3698 "upsert(): the cascade needs the key of the row written for $sname"
3699 . ($at || ' at the top level')
3700 . ', but the source has no primary key, so no row it writes can be named'
3701 ) unless @pk;
3702  
3703 25 my $ct = $opts->{conflict_target};
3704 25 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if defined $ct and not length ref $ct and $ct eq "any" 1 24 25
Condition100%6/6
defined $ct and not length ref $ct and $ct eq "any"
!ll&&!rl&&r
2311
defined $ct and not length ref $ct
!ll&&!rl&&r
1942
MC/DC100%3/3
defined $ct and not length ref $ct and $ct eq "any"
defined $ct not length ref $ct $ct eq "any"
Truth table100%4/4
A and not(B) and C
A= defined $ctB= not length ref $ctC= $ct eq "any"
ABCresult
0XX0
10X0
1100
1111
3705 "upsert(): conflict_target => 'any'$at cannot take part in a cascade -- "
3706 . 'it asks the engine to resolve on whichever unique constraint collides, '
3707 . 'which is exactly the shape in which the written row cannot be named. '
3708 . 'Name the constraint the parts are linked on'
3709 ) if defined $ct and ! length ref $ct and $ct eq 'any';
3710  
3711 $self->throw_exception(
3712 "upsert(): on_conflict => 'nothing' cannot take part in a cascade with "
3713 . 'nested rows that depend on this one -- DO NOTHING may write no row, '
3714 . 'and then there is no key to hand to them'
3715 24 ▶ ) if ($opts->{on_conflict} || 'update') eq 'nothing';
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"on_conflict"} || "update") eq "nothing" 1 23 24
Condition100%2/2
$opts->{'on_conflict'} || 'update'
l!l
123
MC/DC100%1/1
$opts->{'on_conflict'} || 'update'
$opts->{'on_conflict'}
Truth table100%2/2
A
A= $opts->{'on_conflict'}
Aresult
11
00
3716  
3717 # Same shape, same reason: whether the condition holds is a fact about the
3718 # stored data, so a row the children need may or may not exist -- and the
3719 # cascade would find that out half-way through, in production, on the day
3720 # the condition first fails.
3721 $self->throw_exception(
3722 'upsert(): update_where cannot take part in a cascade with nested rows '
3723 . 'that depend on this one -- a conditional DO UPDATE may write no row, '
3724 . 'and then there is no key to hand to them'
3725 23 ▶ ) if exists $opts->{update_where};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"update_where"} 1 22 23
3726 }
3727  
3728 # The three-way primary-key default rule, per part. A foreign key this node
3729 # is handed -- by its parent, or by a part written before it -- counts as
3730 # supplied even though it is not in the data yet.
3731 40 ▶ if (! defined $opts->{key} and ! defined $opts->{conflict_target}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts->{"key"} or defined $opts->{"conflict_target"}) 12 28 40
Condition100%3/3
defined $opts->{"key"} or defined $opts->{"conflict_target"}
l!l&&r!l&&!r
82012
MC/DC100%2/2
defined $opts->{"key"} or defined $opts->{"conflict_target"}
defined $opts->{"key"} defined $opts->{"conflict_target"}
Truth table100%3/3
A or B
A= defined $opts->{"key"}B= defined $opts->{"conflict_target"}
ABresult
1X1
011
000
3732 25 my %have = map { $_ => 1 } (
3733 12 ( grep { defined $cols->{$_} } keys %$cols ), @$filled, @from_before,
3734 );
3735  
3736 12 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @pk 0 12 12
3737 "upsert(): $sname$at has no primary key, so there is no conflict target "
3738 . "to default to -- name one with $hint. upsert does not guess among the "
3739 . 'unique constraints'
3740 ) unless @pk;
3741  
3742 12 ▶ if (my @missing = grep { ! $have{$_} } @pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@missing) = grep({not $have{$_};} @pk)) 6 6 12
3743 6 $self->throw_exception(
3744 "upsert(): no conflict target given for $sname$at and the data does "
3745 . 'not supply its primary key (missing: ' . CORE::join(', ', @missing) . ') -- '
3746 . 'the statement could never collide and would silently degenerate into '
3747 . "a plain INSERT. Name the target with $hint"
3748 );
3749 }
3750 }
3751  
3752 34 my %flat_opts = ( result => $want );
3753 34 for my $k (qw/ key conflict_target on_conflict update update_where /) {
3754 170 ▶ $flat_opts{$k} = $opts->{$k} if exists $opts->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{$k} 29 141 170
3755 }
3756  
3757 # The columns the conflict branch must not treat as "something to update".
3758 # Resolved here so the run can tell an empty update set from a real one --
3759 # a bare key resolves through the same unique_constraints as everywhere
3760 # else, and an unknown constraint name is caught before any statement.
3761 my @target_cols =
3762 defined $opts->{key} ? $rsrc->unique_constraint_columns($opts->{key})
3763 : ! defined $opts->{conflict_target} ? @pk
3764 19 ▶ : ref $opts->{conflict_target} eq 'ARRAY' ? @{ $opts->{conflict_target} }
Branch: 1 branch
BranchTrueFalseTotal
!length(ref $opts->{'conflict_target'}) && $opts->{'conflict_target'} ne 'any' ? : 1 0 1
Condition33%1/3
not length ref $opts->{"conflict_target"} and $opts->{"conflict_target"} ne "any"
!ll&&!rl&&r
001
MC/DC0%0/2
not length ref $opts->{"conflict_target"} and $opts->{"conflict_target"} ne "any"
not length ref $opts->{"conflict_target"} $opts->{"conflict_target"} ne "any"
Truth table33%1/3
not(A) and B
A= not length ref $opts->{"conflict_target"}B= $opts->{"conflict_target"} ne "any"
ABresult
0X0
100
111
3765 : ( ! length ref $opts->{conflict_target}
3766 and $opts->{conflict_target} ne 'any' ) ? ( $opts->{conflict_target} )
3767 34 ▶ : ();
Branch: 3 branches
BranchTrueFalseTotal
defined $opts->{'key'} ? : 8 26 34
!defined($opts->{'conflict_target'}) ? : 6 20 26
ref $opts->{'conflict_target'} eq 'ARRAY' ? : 19 1 20
3768  
3769 return {
3770 34 rs => $rs,
3771 cols => $cols,
3772 opts => \%flat_opts,
3773 target_cols => \@target_cols,
3774 before => \@before,
3775 after => \@after,
3776 };
3777 }
3778  
3779 # Plan first, then one transaction around the whole tree.
3780 33 ▶sub _upsert_cascade {
Subroutine _upsert_cascade: called CC=3 SCAR=11.0
3781 33 my ($self, $data, $opts, $shape) = @_;
3782  
3783 33 my $storage = $self->result_source->storage;
3784  
3785 # Ahead of the transaction, so an unsupporting engine does not get a BEGIN
3786 # and a ROLLBACK to show for a call that could never have worked.
3787 33 ▶ $self->_upsert_unsupported($storage)
Branch: 1 branch
BranchTrueFalseTotal
unless $storage->can("_use_supports_upsert") and $storage->_use_supports_upsert 1 32 33
Condition66%2/3
$storage->can("_use_supports_upsert") and $storage->_use_supports_upsert
!ll&&!rl&&r
0132
MC/DC50%1/2
$storage->can("_use_supports_upsert") and $storage->_use_supports_upsert
$storage->can("_use_supports_upsert") $storage->_use_supports_upsert
Truth table66%2/3
A and B
A= $storage->can("_use_supports_upsert")B= $storage->_use_supports_upsert
ABresult
0X0
100
111
3788 unless $storage->can('_use_supports_upsert')
3789 and $storage->_use_supports_upsert;
3790  
3791 32 my $plan = $self->_upsert_plan($self, $data, $opts, $shape, [], '');
3792  
3793 # All-or-nothing. Already inside a transaction? Then this JOINS it -- a
3794 # failing cascade takes the caller's outer work down with it. Deliberately
3795 # no savepoint magic: a caller who wants the cascade isolated from
3796 # surrounding work opens their own savepoint.
3797 13 my $guard = $storage->txn_scope_guard;
3798 13 my $row = $self->_upsert_run($plan);
3799 11 $guard->commit;
3800  
3801 11 return $row;
3802 }
3803  
3804 # A row identified entirely by its own conflict target -- the lookup row that
3805 # a belongs_to part almost always is, { name => 'Y' } keyed on name -- leaves
3806 # the conflict branch with nothing to set. Flat, that is a caller mistake and
3807 # upsert says so, pointing at on_conflict => 'nothing'. In a cascade it is not
3808 # a choice the caller can make: DO NOTHING writes no row, and a part something
3809 # hangs off has to be nameable. So the branch re-asserts the target instead --
3810 # col = <the value that was attempted> -- which is a no-op on the value and
3811 # keeps the row returned. Exactly the idiom ADR 0036 section 4 blesses for
3812 # MySQL's identity set, for the same reason.
3813 31 ▶sub _upsert_node_opts {
Subroutine _upsert_node_opts: called CC=7 SCAR=20.3
3814 31 my ($self, $node, $row) = @_;
3815  
3816 31 my %opts = %{ $node->{opts} };
3817  
3818 return \%opts
3819 if exists $opts{update}
3820 or ( $opts{on_conflict} || 'update' ) eq 'nothing'
3821 31 ▶ or ! @{ $node->{target_cols} };
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"update"} or ($opts{"on_conflict"} || "update") eq "nothing" or not @{$node->{"target_cols"};} 0 31 31
Condition37%3/8
exists $opts{"update"} or ($opts{"on_conflict"} || "update") eq "nothing" or not @{$node->{"target_cols"};}
l!l&&r!l&&!r
0031
exists $opts{"update"} or ($opts{"on_conflict"} || "update") eq "nothing"
l!l&&r!l&&!r
0031
$opts{'on_conflict'} || 'update'
l!l
031
MC/DC0%0/3
exists $opts{"update"} or ($opts{"on_conflict"} || "update") eq "nothing" or not @{$node->{"target_cols"};}
exists $opts{"update"} $opts{'on_conflict'} not @{$node->{"target_cols"};}
Truth table25%1/4
A or B or not(C)
A= exists $opts{"update"}B= $opts{'on_conflict'}C= not @{$node->{"target_cols"};}
ABCresult
1XX1
01X1
0011
0000
3822  
3823 31 my %rowdata = $row->get_columns;
3824 79 my %skip = map { $_ => 1 }
3825 31 @{ $node->{target_cols} }, $node->{rs}->result_source->primary_columns;
3826  
3827 31 ▶ return \%opts if grep { ! $skip{$_} } keys %rowdata;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $skip{$_};} keys %rowdata 24 7 31
3828  
3829 7 my @noop = grep { exists $rowdata{$_} } @{ $node->{target_cols} };
3830 7 ▶ $opts{update} = \@noop if @noop;
Branch: 1 branch
BranchTrueFalseTotal
if @noop 7 0 7
3831  
3832 7 return \%opts;
3833 }
3834  
3835 # Walk the plan: parts whose key we need first, us, then the parts that need
3836 # ours. $prebuilt is the Row the caller of this node already had to build in
3837 # order to set the foreign key on it.
3838 31 ▶sub _upsert_run {
Subroutine _upsert_run: called CC=6 SCAR=17.9
3839 31 my ($self, $node, $prebuilt) = @_;
3840  
3841 31 my $rs = $node->{rs};
3842 31 ▶ my $row = $prebuilt || $rs->new_result($node->{cols});
Condition66%2/3
$prebuilt || $rs->new_result($node->{'cols'})
l!l&&r!l&&!r
10210
MC/DC0%0/2
$prebuilt || $rs->new_result($node->{'cols'})
$prebuilt $rs->new_result($node->{'cols'})
Truth table66%2/3
A || B
A= $prebuiltB= $rs->new_result($node->{'cols'})
ABresult
1X1
011
000
3843  
3844 $row->set_from_related(
3845 $_->{rel}, $self->_upsert_run($_->{node})
3846 31 ) for @{ $node->{before} };
3847  
3848 31 $row = $rs->upsert(
3849 { $row->get_columns }, $self->_upsert_node_opts($node, $row), $row,
3850 );
3851  
3852 29 for my $after (@{ $node->{after} }) {
3853 9 for my $child (@{ $after->{nodes} }) {
3854 10 my $crow = $child->{rs}->new_result($child->{cols});
3855 10 $crow->set_from_related($_, $row) for @{ $after->{revs} };
3856 10 $self->_upsert_run($child, $crow);
3857 }
3858 }
3859  
3860 27 return $row;
3861 }
3862  
3863  
3864 18 ▶sub update_or_new {
Subroutine update_or_new: called CC=5 SCAR=16.2
Pod documented
3865 18 my $self = shift;
3866 18 ▶ my $attrs = ( @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {} );
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 11 7 18
Condition66%2/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
7011
MC/DC50%1/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table66%2/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
3867 18 ▶ my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 18 0 18
3868  
3869 18 my @lookup_cols;
3870 18 my $row = $self->_find_for_write( $cond, $attrs, 'update_or_new', \@lookup_cols );
3871 14 ▶ if ( defined $row ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $row) 8 6 14
3872 8 $row->update($self->_update_data_for_found_row($cond, \@lookup_cols));
3873 6 return $row;
3874 }
3875  
3876 6 return $self->new_result($cond);
3877 }
3878  
3879  
3880 10 ▶sub update_or_new_async {
Subroutine update_or_new_async: called CC=4 SCAR=14.2
Pod documented
3881 10 my $self = shift;
3882 10 ▶ my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 && ref $_[$#_] eq 'HASH' ? : 0 10 10
Condition33%1/3
@_ > 1 and ref $_[$#_] eq "HASH"
!ll&&!rl&&r
1000
MC/DC0%0/2
@_ > 1 and ref $_[$#_] eq "HASH"
@_ > 1 ref $_[$#_] eq "HASH"
Truth table33%1/3
A and B
A= @_ > 1B= ref $_[$#_] eq "HASH"
ABresult
0X0
100
111
3883 10 ▶ my $cond = ref $_[0] eq 'HASH' ? shift : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 10 0 10
3884  
3885 return $self->_rs_run_async('update_or_new',
3886 6 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3887 6 my ($backend, $fc) = @_;
3888  
3889 6 my @lookup_cols;
3890 6 ▶ return $self->_find_for_write_async($cond, $attrs, 'update_or_new', \@lookup_cols)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3891 6 my ($row) = @_;
3892 6 ▶ return $row->update_async($self->_update_data_for_found_row($cond, \@lookup_cols)) if defined $row;
Branch: 1 branch
BranchTrueFalseTotal
if defined $row 4 2 6
3893 2 return $self->new_result($cond);
3894 6 });
3895 },
3896 3 ▶ sub { $self->update_or_new($cond, $attrs) },
Subroutine __ANON__: called CC=1 SCAR=0.0
3897 10 );
3898 }
3899  
3900  
3901 18443 ▶sub get_cache {
Subroutine get_cache: called CC=1 SCAR=0.0
Pod documented
3902 18443 shift->{all_cache};
3903 }
3904  
3905  
3906 49 ▶sub set_cache {
Subroutine set_cache: called CC=3 SCAR=12.0
Pod documented
3907 49 my ( $self, $data ) = @_;
3908 49 ▶ $self->throw_exception("set_cache requires an arrayref")
Branch: 1 branch
BranchTrueFalseTotal
if defined $data and ref $data ne "ARRAY" 0 49 49
Condition33%1/3
defined $data and ref $data ne "ARRAY"
!ll&&!rl&&r
0490
MC/DC0%0/2
defined $data and ref $data ne "ARRAY"
defined $data ref $data ne "ARRAY"
Truth table33%1/3
A and B
A= defined $dataB= ref $data ne "ARRAY"
ABresult
0X0
100
111
3909 if defined($data) && (ref $data ne 'ARRAY');
3910  
3911 # If set_cache is called after a related resultset has been created,
3912 # we expect subsequent calls to related_resultset to include cached
3913 # results (if they are present on the objects in $data).
3914 #
3915 # This won't be true if we've cached the related_resultsets already,
3916 # so clear them.
3917 49 $self->{related_resultsets} = {};
3918 49 $self->{all_cache} = $data;
3919 }
3920  
3921  
3922 0 ▶sub clear_cache {
Subroutine clear_cache: not called CC=1 SCAR=6.9
Pod documented
3923 0 shift->set_cache(undef);
3924 }
3925  
3926  
3927 2 ▶sub is_paged {
Subroutine is_paged: called CC=1 SCAR=0.0
Pod documented
3928 2 my ($self) = @_;
3929 2 return !!$self->{attrs}{page};
3930 }
3931  
3932  
3933 14 ▶sub is_ordered {
Subroutine is_ordered: called CC=1 SCAR=0.0
Pod documented
3934 14 my ($self) = @_;
3935 14 return scalar $self->result_source->storage->_extract_order_criteria($self->{attrs}{order_by});
3936 }
3937  
3938  
3939 18 ▶sub related_resultset {
Subroutine related_resultset: called CC=8 SCAR=22.9
Pod documented
3940 18 my ($self, $rel) = @_;
3941  
3942 my $rrs = defined $self->{related_resultsets}{$rel}
3943 ? $self->{related_resultsets}{$rel}
3944 18 ▶ : ( $self->{related_resultsets}{$rel} = do {
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'related_resultsets'}{$rel} ? : 0 18 18
3945 18 my $rsrc = $self->result_source;
3946 18 my $rel_info = $rsrc->relationship_info($rel);
3947  
3948 18 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless $rel_info 0 18 18
3949 "search_related: result source '" . $rsrc->source_name .
3950 "' has no such relationship $rel")
3951 unless $rel_info;
3952  
3953 18 my $attrs = $self->_chain_relationship($rel);
3954  
3955 18 my $join_count = $attrs->{seen_join}{$rel};
3956  
3957 18 my $alias = $self->result_source->storage
3958 ->relname_to_table_alias($rel, $join_count);
3959  
3960 # since this is search_related, and we already slid the select window inwards
3961 # (the select/as attrs were deleted in the beginning), we need to flip all
3962 # left joins to inner, so we get the expected results
3963 # read the comment on top of the actual function to see what this does
3964 18 $attrs->{from} = $rsrc->schema->storage->_inner_join_to_node ($attrs->{from}, $alias);
3965  
3966  
3967 #XXX - temp fix for result_class bug. There likely is a more elegant fix -groditi
3968 18 delete @{$attrs}{qw(result_class alias)};
3969  
3970 18 my $rel_source = $rsrc->related_source($rel);
3971  
3972 18 my $new = do {
3973  
3974 # The reason we do this now instead of passing the alias to the
3975 # search_rs below is that if you wrap/overload resultset on the
3976 # source you need to know what alias it's -going- to have for things
3977 # to work sanely (e.g. RestrictWithObject wants to be able to add
3978 # extra query restrictions, and these may need to be $alias.)
3979  
3980 18 my $rel_attrs = $rel_source->resultset_attributes;
3981 18 local $rel_attrs->{alias} = $alias;
3982  
3983 $rel_source->resultset
3984 ->search_rs(
3985 undef, {
3986 %$attrs,
3987 where => $attrs->{where},
3988 18 });
3989 };
3990  
3991 18 ▶ if (my $cache = $self->get_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cache = $self->get_cache) 0 18 18
3992 my @related_cache = map
3993 0 ▶ { $_->related_resultset($rel)->get_cache || () }
Condition0%0/3
$_->related_resultset($rel)->get_cache || ()
l!l&&r!l&&!r
000
MC/DC0%0/2
$_->related_resultset($rel)->get_cache || ()
$_->related_resultset($rel)->get_cache ()
Truth table0%0/3
A || B
A= $_->related_resultset($rel)->get_cacheB= ()
ABresult
1X1
011
000
3994 @$cache
3995 ;
3996  
3997 0 ▶ $new->set_cache([ map @$_, @related_cache ]) if @related_cache == @$cache;
Branch: 1 branch
BranchTrueFalseTotal
if @related_cache == @$cache 0 0 0
3998 }
3999  
4000 18 $new;
4001 } );
4002  
4003 # ADR 0045 / karr k195: a related resultset derived from a context-bound
4004 # resultset inherits the pin, so with_context($ctx)->search_related(...)
4005 # routes onto the pinned connection instead of a sibling pool connection.
4006 $rrs->{_async_context} = $self->{_async_context}
4007 18 ▶ if $self->{_async_context} and blessed $rrs;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} and builtin::blessed($rrs) 2 16 18
Condition66%2/3
$self->{"_async_context"} and builtin::blessed($rrs)
!ll&&!rl&&r
1602
MC/DC50%1/2
$self->{"_async_context"} and builtin::blessed($rrs)
$self->{"_async_context"} builtin::blessed($rrs)
Truth table66%2/3
A and B
A= $self->{"_async_context"}B= builtin::blessed($rrs)
ABresult
0X0
100
111
4008  
4009 18 return $rrs;
4010 }
4011  
4012  
4013 497 ▶sub current_source_alias {
Subroutine current_source_alias: called CC=3 SCAR=12.7
Pod documented
4014 497 ▶ return (shift->{attrs} || {})->{alias} || 'me';
Condition50%2/4
+(+(shift())->{'attrs'} || {})->{'alias'} || 'me'
l!l
4970
+(shift())->{'attrs'} || {}
l!l
4970
MC/DC0%0/1
+(+(shift())->{'attrs'} || {})->{'alias'} || 'me'
+(shift())->{'attrs'}
Truth table50%1/2
A
A= +(shift())->{'attrs'}
Aresult
11
00
4015 }
4016  
4017  
4018 34 ▶sub as_subselect_rs {
Subroutine as_subselect_rs: called CC=2 SCAR=6.9
Pod documented
4019 34 my $self = shift;
4020  
4021 34 my $attrs = $self->_resolved_attrs;
4022  
4023 34 my $fresh_rs = (ref $self)->new (
4024 $self->result_source,
4025 {},
4026 );
4027  
4028 # these pieces will be locked in the subquery
4029 34 delete $fresh_rs->{cond};
4030 34 delete @{$fresh_rs->{attrs}}{qw/where bind/};
4031  
4032 # ADR 0045 / karr k195: a subselect wrapper of a context-bound resultset keeps
4033 # the pin (the ->search_rs below propagates it onto the returned clone).
4034 34 ▶ $fresh_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 5 29 34
4035  
4036 return $fresh_rs->search_rs( {}, {
4037 from => [{
4038 $attrs->{alias} => $self->as_query,
4039 -alias => $attrs->{alias},
4040 -rsrc => $self->result_source,
4041 }],
4042 alias => $attrs->{alias},
4043 34 });
4044 }
4045  
4046 # This code is called by search_related, and makes sure there
4047 # is clear separation between the joins before, during, and
4048 # after the relationship. This information is needed later
4049 # in order to properly resolve prefetch aliases (any alias
4050 # with a relation_chain_depth less than the depth of the
4051 # current prefetch is not considered)
4052 #
4053 # The increments happen twice per join. An even number means a
4054 # relationship specified via a search_related, whereas an odd
4055 # number indicates a join/prefetch added via attributes
4056 #
4057 # Also this code will wrap the current resultset (the one we
4058 # chain to) in a subselect IFF it contains limiting attributes
4059 18 ▶sub _chain_relationship {
Subroutine _chain_relationship: called CC=11 SCAR=24.0
4060 18 my ($self, $rel) = @_;
4061 18 my $source = $self->result_source;
4062 18 ▶ my $attrs = { %{$self->{attrs}||{}} };
Condition50%1/2
$self->{'attrs'} || {}
l!l
180
MC/DC0%0/1
$self->{'attrs'} || {}
$self->{'attrs'}
Truth table50%1/2
A
A= $self->{'attrs'}
Aresult
11
00
4063  
4064 # we need to take the prefetch the attrs into account before we
4065 # ->_resolve_join as otherwise they get lost - captainL
4066 18 my $join = $self->_merge_joinpref_attr( $attrs->{join}, $attrs->{prefetch} );
4067  
4068 18 delete @{$attrs}{qw/join prefetch collapse group_by distinct _grouped_by_distinct select as columns +select +as +columns/};
4069  
4070 18 ▶ my $seen = { %{ (delete $attrs->{seen_join}) || {} } };
Condition100%2/2
delete $attrs->{'seen_join'} || {}
l!l
414
MC/DC100%1/1
delete $attrs->{'seen_join'} || {}
delete $attrs->{'seen_join'}
Truth table100%2/2
A
A= delete $attrs->{'seen_join'}
Aresult
11
00
4071  
4072 18 my $from;
4073 18 my @force_subq_attrs = qw/offset rows group_by having/;
4074  
4075 18 ▶ if (
Branch: 2 branches
BranchTrueFalseTotal
if ($attrs->{'from'} and ref $attrs->{'from'} ne 'ARRAY' or $self->_has_resolved_attr(@force_subq_attrs)) { } 1 17 18
elsif ($attrs->{'from'}) { } 4 13 17
Condition66%4/6
$attrs->{"from"} and ref $attrs->{"from"} ne "ARRAY" or $self->_has_resolved_attr(@force_subq_attrs)
l!l&&r!l&&!r
0117
$attrs->{"from"} and ref $attrs->{"from"} ne "ARRAY"
!ll&&!rl&&r
1440
MC/DC33%1/3
$attrs->{"from"} and ref $attrs->{"from"} ne "ARRAY" or $self->_has_resolved_attr(@force_subq_attrs)
$attrs->{"from"} ref $attrs->{"from"} ne "ARRAY" $self->_has_resolved_attr(@force_subq_attrs)
Truth table60%3/5
A and B or C
A= $attrs->{"from"}B= ref $attrs->{"from"} ne "ARRAY"C= $self->_has_resolved_attr(@force_subq_attrs)
ABCresult
11X1
0X11
1011
0X00
1000
4076 ($attrs->{from} && ref $attrs->{from} ne 'ARRAY')
4077 ||
4078 $self->_has_resolved_attr (@force_subq_attrs)
4079 ) {
4080 # Nuke the prefetch (if any) before the new $rs attrs
4081 # are resolved (prefetch is useless - we are wrapping
4082 # a subquery anyway).
4083 1 my $rs_copy = $self->search;
4084 $rs_copy->{attrs}{join} = $self->_merge_joinpref_attr (
4085 $rs_copy->{attrs}{join},
4086 delete $rs_copy->{attrs}{prefetch},
4087 1 );
4088  
4089 $from = [{
4090 -rsrc => $source,
4091 -alias => $attrs->{alias},
4092 1 $attrs->{alias} => $rs_copy->as_query,
4093 }];
4094 1 delete @{$attrs}{@force_subq_attrs, qw/where bind/};
4095 1 $seen->{-relation_chain_depth} = 0;
4096 }
4097 elsif ($attrs->{from}) { #shallow copy suffices
4098 4 $from = [ @{$attrs->{from}} ];
4099 }
4100 else {
4101 $from = [{
4102 -rsrc => $source,
4103 -alias => $attrs->{alias},
4104 13 $attrs->{alias} => $source->from,
4105 }];
4106 }
4107  
4108 my $jpath = ($seen->{-relation_chain_depth})
4109 ? $from->[-1][0]{-join_path}
4110 18 ▶ : [];
Branch: 1 branch
BranchTrueFalseTotal
$seen->{'-relation_chain_depth'} ? : 4 14 18
4111  
4112 my @requested_joins = $source->_resolve_join(
4113 $join,
4114 $attrs->{alias},
4115 18 $seen,
4116 $jpath,
4117 );
4118  
4119 18 push @$from, @requested_joins;
4120  
4121 18 $seen->{-relation_chain_depth}++;
4122  
4123 # if $self already had a join/prefetch specified on it, the requested
4124 # $rel might very well be already included. What we do in this case
4125 # is effectively a no-op (except that we bump up the chain_depth on
4126 # the join in question so we could tell it *is* the search_related)
4127 18 my $already_joined;
4128  
4129 # we consider the last one thus reverse
4130 18 for my $j (reverse @requested_joins) {
4131 8 my ($last_j) = keys %{$j->[0]{-join_path}[-1]};
4132 8 ▶ if ($rel eq $last_j) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rel eq $last_j) 2 6 8
4133 2 $j->[0]{-relation_chain_depth}++;
4134 2 $already_joined++;
4135 2 last;
4136 }
4137 }
4138  
4139 18 ▶ unless ($already_joined) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($already_joined) 16 2 18
4140 push @$from, $source->_resolve_join(
4141 $rel,
4142 $attrs->{alias},
4143 16 $seen,
4144 $jpath,
4145 );
4146 }
4147  
4148 18 $seen->{-relation_chain_depth}++;
4149  
4150 18 return {%$attrs, from => $from, seen_join => $seen};
4151 }
4152  
4153 9328 ▶sub _resolved_attrs {
Subroutine _resolved_attrs: called CC=87 SCAR=46.5
4154 9328 my $self = shift;
4155 9328 ▶ return $self->{_attrs} if $self->{_attrs};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_attrs"} 4553 4775 9328
4156  
4157 4775 ▶ my $attrs = { %{ $self->{attrs} || {} } };
Condition50%1/2
$self->{'attrs'} || {}
l!l
47750
MC/DC0%0/1
$self->{'attrs'} || {}
$self->{'attrs'}
Truth table50%1/2
A
A= $self->{'attrs'}
Aresult
11
00
4158 4775 my $source = $attrs->{result_source} = $self->result_source;
4159 4775 my $alias = $attrs->{alias};
4160  
4161 $self->throw_exception("Specifying distinct => 1 in conjunction with collapse => 1 is unsupported")
4162 4775 ▶ if $attrs->{collapse} and $attrs->{distinct};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"collapse"} and $attrs->{"distinct"} 0 4775 4775
Condition33%1/3
$attrs->{"collapse"} and $attrs->{"distinct"}
!ll&&!rl&&r
477500
MC/DC0%0/2
$attrs->{"collapse"} and $attrs->{"distinct"}
$attrs->{"collapse"} $attrs->{"distinct"}
Truth table33%1/3
A and B
A= $attrs->{"collapse"}B= $attrs->{"distinct"}
ABresult
0X0
100
111
4163  
4164 # The engine behind the remove_columns attribute and its shortcut method:
4165 # turn "everything except these" into an explicit column list.
4166 # Deliberately lazy and resolved here rather than eagerly in the shortcut, so
4167 # that an explicit columns/select from anywhere in the chain always wins over
4168 # a remove_columns. Guard as upstream: it falls through untouched whenever
4169 # remove_columns is not in play.
4170 4775 ▶ if (!$attrs->{columns} && !$attrs->{select} && $attrs->{remove_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $attrs->{"columns"} || $attrs->{"select"} and $attrs->{"remove_columns"}) 8 4767 4775
Condition100%6/6
not $attrs->{"columns"} || $attrs->{"select"} and $attrs->{"remove_columns"}
!ll&&!rl&&r
104337248
$attrs->{'columns'} || $attrs->{'select'}
l!l&&r!l&&!r
7792643732
MC/DC100%3/3
not $attrs->{"columns"} || $attrs->{"select"} and $attrs->{"remove_columns"}
$attrs->{'columns'} $attrs->{'select'} $attrs->{"remove_columns"}
Truth table100%4/4
not(A || B) and C
A= $attrs->{'columns'}B= $attrs->{'select'}C= $attrs->{"remove_columns"}
ABCresult
1XX0
01X0
0000
0011
4171 8 my %rc = map { $_ => 1 } @{$attrs->{remove_columns}};
4172 8 $attrs->{columns} = [ grep { !$rc{$_} } $source->columns ];
4173 }
4174  
4175 # default selection list
4176 $attrs->{columns} = [ $source->columns ]
4177 4775 ▶ unless grep { exists $attrs->{$_} } qw/columns cols select as/;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {exists $attrs->{$_};} "columns", "cols", "select", "as" 3724 1051 4775
4178  
4179 # merge selectors together
4180 4775 for (qw/columns select as/) {
4181 $attrs->{$_} = $self->_merge_attr($attrs->{$_}, delete $attrs->{"+$_"})
4182 14325 ▶ if $attrs->{$_} or $attrs->{"+$_"};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{$_} or $$attrs{"+$_"} 5100 9225 14325
Condition100%3/3
$attrs->{$_} or $$attrs{"+$_"}
l!l&&r!l&&!r
5051499225
MC/DC100%2/2
$attrs->{$_} or $$attrs{"+$_"}
$attrs->{$_} $$attrs{"+$_"}
Truth table100%3/3
A or B
A= $attrs->{$_}B= $$attrs{"+$_"}
ABresult
1X1
011
000
4183 }
4184  
4185 # disassemble columns
4186 4775 my (@sel, @as);
4187 4775 ▶ if (my $cols = delete $attrs->{columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cols = delete $attrs->{"columns"}) 4514 261 4775
4188 4514 ▶ for my $c (ref $cols eq 'ARRAY' ? @$cols : $cols) {
Branch: 1 branch
BranchTrueFalseTotal
ref $cols eq 'ARRAY' ? : 4514 0 4514
4189 14829 ▶ if (ref $c eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $c eq 'HASH') { } 345 14484 14829
4190 345 for my $as (sort keys %$c) {
4191 348 push @sel, $c->{$as};
4192 348 push @as, $as;
4193 }
4194 }
4195 else {
4196 14484 push @sel, $c;
4197 14484 push @as, $c;
4198 }
4199 }
4200 }
4201  
4202 # when trying to weed off duplicates later do not go past this point -
4203 # everything added from here on is unbalanced "anyone's guess" stuff
4204 4775 my $dedup_stop_idx = $#as;
4205  
4206 293 ▶ push @as, @{ ref $attrs->{as} eq 'ARRAY' ? $attrs->{as} : [ $attrs->{as} ] }
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{'as'} eq 'ARRAY' ? : 293 0 293
4207 4775 ▶ if $attrs->{as};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"as"} 293 4482 4775
4208 293 ▶ push @sel, @{ ref $attrs->{select} eq 'ARRAY' ? $attrs->{select} : [ $attrs->{select} ] }
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{'select'} eq 'ARRAY' ? : 293 0 293
4209 4775 ▶ if $attrs->{select};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"select"} 293 4482 4775
4210  
4211 # assume all unqualified selectors to apply to the current alias (legacy stuff)
4212 4775 ▶ $_ = (ref $_ or $_ =~ /\./) ? $_ : "$alias.$_" for @sel;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ || $_ =~ /\./ ? : 927 14262 15189
Condition100%3/3
ref $_ or $_ =~ /\./
l!l&&r!l&&!r
54638114262
MC/DC100%2/2
ref $_ or $_ =~ /\./
ref $_ $_ =~ /\./
Truth table100%3/3
A or B
A= ref $_B= $_ =~ /\./
ABresult
1X1
011
000
4213  
4214 # disqualify all $alias.col as-bits (inflate-map mandated)
4215 4775 ▶ $_ = ($_ =~ /^\Q$alias.\E(.+)$/) ? $1 : $_ for @as;
Branch: 1 branch
BranchTrueFalseTotal
$_ =~ /^\Q$alias.\E(.+)$/ ? : 324 14850 15174
4216  
4217 # de-duplicate the result (remove *identical* select/as pairs)
4218 # and also die on duplicate {as} pointing to different {select}s
4219 # not using a c-style for as the condition is prone to shrinkage
4220 4775 my $seen;
4221 4775 my $i = 0;
4222 4775 ▶ while ($i <= $dedup_stop_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $dedup_stop_idx) 14832 4775 19607
4223 14832 ▶ if ($seen->{"$sel[$i] \x00\x00 $as[$i]"}++) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$seen{"$sel[$i] \000\000 $as[$i]"}++) { } 8 14824 14832
elsif ($$seen{$as[$i]}++) { } 0 14824 14824
4224 8 splice @sel, $i, 1;
4225 8 splice @as, $i, 1;
4226 8 $dedup_stop_idx--;
4227 }
4228 elsif ($seen->{$as[$i]}++) {
4229 0 $self->throw_exception(
4230 "inflate_result() alias '$as[$i]' specified twice with different SQL-side {select}-ors"
4231 );
4232 }
4233 else {
4234 14824 $i++;
4235 }
4236 }
4237  
4238 4775 $attrs->{select} = \@sel;
4239 4775 $attrs->{as} = \@as;
4240  
4241 $attrs->{from} ||= [{
4242 -rsrc => $source,
4243 -alias => $self->{attrs}{alias},
4244 4775 ▶ $self->{attrs}{alias} => $source->from,
Condition100%2/2
$attrs->{"from"} ||= [{"-rsrc", $source, "-alias", $self->{"attrs"}{"alias"}, $self->{"attrs"}{"alias"}, $source->from}]
l!l
7594016
MC/DC100%1/1
$attrs->{"from"} ||= [{"-rsrc", $source, "-alias", $self->{"attrs"}{"alias"}, $self->{"attrs"}{"alias"}, $source->from}]
$attrs->{"from"}
Truth table100%2/2
A
A= $attrs->{"from"}
Aresult
11
00
4245 }];
4246  
4247 # Auto-discover joins from WHERE/HAVING condition keys that reference
4248 # relationships (e.g. 'artist.name' implies join => 'artist').
4249 # Skip if from is already custom (joins were resolved by a prior
4250 # _resolved_attrs call, e.g. count internals building a new RS from
4251 # already-resolved attrs), or if FROM is a subquery (as_subselect_rs).
4252 4775 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not $attrs->{"_auto_joins_done"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} == 1 and ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"} or $alias} ne "REF") 4017 758 4775
Condition100%9/9
not $attrs->{"_auto_joins_done"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} == 1 and ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"} or $alias} ne "REF"
!ll&&!rl&&r
6451134017
not $attrs->{"_auto_joins_done"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} == 1
!ll&&!rl&&r
613324130
not $attrs->{"_auto_joins_done"} and ref $attrs->{"from"} eq "ARRAY"
!ll&&!rl&&r
61214162
MC/DC100%4/4
not $attrs->{"_auto_joins_done"} and ref $attrs->{"from"} eq "ARRAY" and @{$attrs->{"from"};} == 1 and ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"} or $alias} ne "REF"
not $attrs->{"_auto_joins_done"} ref $attrs->{"from"} eq "ARRAY" @{$attrs->{"from"};} == 1 ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"} or $alias} ne "REF"
Truth table100%5/5
not(A) and B and C and D
A= not $attrs->{"_auto_joins_done"}B= ref $attrs->{"from"} eq "ARRAY"C= @{$attrs->{"from"};} == 1D= ref $attrs->{"from"}[0]{$attrs->{"from"}[0]{"-alias"} or $alias} ne "REF"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4253 ! $attrs->{_auto_joins_done}
4254 and
4255 ref $attrs->{from} eq 'ARRAY'
4256 and
4257 4162 ▶ @{ $attrs->{from} } == 1 # only the base table, no joins resolved yet
Condition66%2/3
$attrs->{'from'}[0]{'-alias'} || $alias
l!l&&r!l&&!r
412280
MC/DC0%0/2
$attrs->{'from'}[0]{'-alias'} || $alias
$attrs->{'from'}[0]{'-alias'} $alias
Truth table66%2/3
A || B
A= $attrs->{'from'}[0]{'-alias'}B= $alias
ABresult
1X1
011
000
4258 and
4259 ref( $attrs->{from}[0]{ $attrs->{from}[0]{'-alias'} || $alias } ) ne 'REF' # not a subquery
4260 ) {
4261 4017 ▶ if ( my $auto_joins = $self->_extract_condition_rels(
Branch: 1 branch
BranchTrueFalseTotal
if (my $auto_joins = $self->_extract_condition_rels([$attrs->{"where"}, $attrs->{"having"}], $source, $alias)) 37 3980 4017
4262 [ $attrs->{where}, $attrs->{having} ], $source, $alias
4263 )) {
4264 # Only add auto-discovered joins that are not already in join/prefetch
4265 # to preserve the user's explicit join ordering
4266 37 ▶ if (defined $attrs->{join} || defined $attrs->{prefetch}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attrs->{'join'} or defined $attrs->{'prefetch'}) { } 31 6 37
Condition100%3/3
defined $attrs->{"join"} or defined $attrs->{"prefetch"}
l!l&&r!l&&!r
2656
MC/DC100%2/2
defined $attrs->{"join"} or defined $attrs->{"prefetch"}
defined $attrs->{"join"} defined $attrs->{"prefetch"}
Truth table100%3/3
A or B
A= defined $attrs->{"join"}B= defined $attrs->{"prefetch"}
ABresult
1X1
011
000
4267 31 my %existing = map { $_ => 1 } $self->_flatten_join_attr($attrs->{join});
4268 31 %existing = (%existing, map { $_ => 1 } $self->_flatten_join_attr($attrs->{prefetch}));
4269 31 my @novel;
4270 31 for my $j ($self->_flatten_join_attr($auto_joins)) {
4271 33 ▶ push @novel, $j unless $existing{$j};
Branch: 1 branch
BranchTrueFalseTotal
unless $existing{$j} 0 33 33
4272 }
4273 31 ▶ if (@novel) {
Branch: 1 branch
BranchTrueFalseTotal
if (@novel) 0 31 31
4274 0 ▶ my $novel_joins = @novel == 1 ? $novel[0] : \@novel;
Branch: 1 branch
BranchTrueFalseTotal
@novel == 1 ? : 0 0 0
4275 $attrs->{join} = defined $attrs->{join}
4276 0 ▶ ? $self->_merge_joinpref_attr( $attrs->{join}, $novel_joins )
Branch: 1 branch
BranchTrueFalseTotal
defined $attrs->{'join'} ? : 0 0 0
4277 : $novel_joins;
4278 }
4279 }
4280 else {
4281 6 $attrs->{join} = $auto_joins;
4282 }
4283 }
4284 4017 $attrs->{_auto_joins_done} = 1;
4285 }
4286  
4287 4775 ▶ if ( $attrs->{join} || $attrs->{prefetch} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"join"} or $attrs->{"prefetch"}) 108 4667 4775
Condition100%3/3
$attrs->{"join"} or $attrs->{"prefetch"}
l!l&&r!l&&!r
66424667
MC/DC100%2/2
$attrs->{"join"} or $attrs->{"prefetch"}
$attrs->{"join"} $attrs->{"prefetch"}
Truth table100%3/3
A or B
A= $attrs->{"join"}B= $attrs->{"prefetch"}
ABresult
1X1
011
000
4288  
4289 $self->throw_exception ('join/prefetch can not be used with a custom {from}')
4290 108 ▶ if ref $attrs->{from} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $attrs->{"from"} ne "ARRAY" 0 108 108
4291  
4292 108 ▶ my $join = (delete $attrs->{join}) || {};
Condition100%2/2
delete $attrs->{'join'} || {}
l!l
6642
MC/DC100%1/1
delete $attrs->{'join'} || {}
delete $attrs->{'join'}
Truth table100%2/2
A
A= delete $attrs->{'join'}
Aresult
11
00
4293  
4294 108 ▶ if ( defined $attrs->{prefetch} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attrs->{"prefetch"}) 51 57 108
4295 51 $join = $self->_merge_joinpref_attr( $join, $attrs->{prefetch} );
4296 }
4297  
4298 $attrs->{from} = # have to copy here to avoid corrupting the original
4299 [
4300 108 @{ $attrs->{from} },
4301 $source->_resolve_join(
4302 $join,
4303 $alias,
4304 108 ▶ { %{ $attrs->{seen_join} || {} } },
Branch: 1 branch
BranchTrueFalseTotal
$attrs->{'seen_join'} && keys %{$$attrs{'seen_join'};} ? : 10 98 108
Condition100%5/5
$attrs->{'seen_join'} || {}
l!l
1296
$attrs->{"seen_join"} and keys %{$$attrs{"seen_join"};}
!ll&&!rl&&r
96210
MC/DC100%1/1
$attrs->{'seen_join'} || {}
$attrs->{'seen_join'}
MC/DC100%2/2
$attrs->{"seen_join"} and keys %{$$attrs{"seen_join"};}
$attrs->{"seen_join"} keys %{$$attrs{"seen_join"};}
Truth table100%2/2
A
A= $attrs->{'seen_join'}
Aresult
11
00
Truth table100%3/3
A and B
A= $attrs->{"seen_join"}B= keys %{$$attrs{"seen_join"};}
ABresult
0X0
100
111
4305 12 ( $attrs->{seen_join} && keys %{$attrs->{seen_join}})
4306 ? $attrs->{from}[-1][0]{-join_path}
4307 108 : []
4308 ,
4309 )
4310 ];
4311 }
4312  
4313 4775 for my $attr (qw(order_by group_by)) {
4314  
4315 9550 ▶ if ( defined $attrs->{$attr} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attrs->{$attr}) 402 9148 9550
4316 $attrs->{$attr} = (
4317 ref( $attrs->{$attr} ) eq 'ARRAY'
4318 95 ▶ ? [ @{ $attrs->{$attr} } ]
Condition33%1/3
$attrs->{$attr} || ()
l!l&&r!l&&!r
30700
MC/DC0%0/2
$attrs->{$attr} || ()
$attrs->{$attr} ()
Truth table33%1/3
A || B
A= $attrs->{$attr}B= ()
ABresult
1X1
011
000
4319 402 ▶ : [ $attrs->{$attr} || () ]
Branch: 1 branch
BranchTrueFalseTotal
ref $attrs->{$attr} eq 'ARRAY' ? : 95 307 402
4320 );
4321  
4322 402 ▶ delete $attrs->{$attr} unless @{$attrs->{$attr}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$attrs->{$attr};} 3 399 402
4323 }
4324 }
4325  
4326 # generate selections based on the prefetch helper
4327 4775 my ($prefetch, @prefetch_select, @prefetch_as);
4328 $prefetch = $self->_merge_joinpref_attr( {}, delete $attrs->{prefetch} )
4329 4775 ▶ if defined $attrs->{prefetch};
Branch: 1 branch
BranchTrueFalseTotal
if defined $attrs->{"prefetch"} 51 4724 4775
4330  
4331 4775 ▶ if ($prefetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefetch) 50 4725 4775
4332  
4333 $self->throw_exception("Unable to prefetch, resultset contains an unnamed selector $attrs->{_dark_selector}{string}")
4334 50 ▶ if $attrs->{_dark_selector};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"_dark_selector"} 1 49 50
4335  
4336 $self->throw_exception("Specifying prefetch in conjunction with an explicit collapse => 0 is unsupported")
4337 49 ▶ if defined $attrs->{collapse} and ! $attrs->{collapse};
Branch: 1 branch
BranchTrueFalseTotal
if defined $attrs->{"collapse"} and not $attrs->{"collapse"} 0 49 49
Condition33%1/3
defined $attrs->{"collapse"} and not $attrs->{"collapse"}
!ll&&!rl&&r
4900
MC/DC0%0/2
defined $attrs->{"collapse"} and not $attrs->{"collapse"}
defined $attrs->{"collapse"} not $attrs->{"collapse"}
Truth table33%1/3
A and not(B)
A= defined $attrs->{"collapse"}B= not $attrs->{"collapse"}
ABresult
0X0
100
111
4338  
4339 49 $attrs->{collapse} = 1;
4340  
4341 # this is a separate structure (we don't look in {from} directly)
4342 # as the resolver needs to shift things off the lists to work
4343 # properly (identical-prefetches on different branches)
4344 49 my $join_map = {};
4345 49 ▶ if (ref $attrs->{from} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $attrs->{"from"} eq "ARRAY") 49 0 49
4346  
4347 49 ▶ my $start_depth = $attrs->{seen_join}{-relation_chain_depth} || 0;
Condition100%2/2
$attrs->{'seen_join'}{'-relation_chain_depth'} || 0
l!l
643
MC/DC100%1/1
$attrs->{'seen_join'}{'-relation_chain_depth'} || 0
$attrs->{'seen_join'}{'-relation_chain_depth'}
Truth table100%2/2
A
A= $attrs->{'seen_join'}{'-relation_chain_depth'}
Aresult
11
00
4348  
4349 49 for my $j ( @{$attrs->{from}}[1 .. $#{$attrs->{from}} ] ) {
4350 79 ▶ next unless $j->[0]{-alias};
Branch: 1 branch
BranchTrueFalseTotal
unless $j->[0]{"-alias"} 0 79 79
4351 79 ▶ next unless $j->[0]{-join_path};
Branch: 1 branch
BranchTrueFalseTotal
unless $j->[0]{"-join_path"} 0 79 79
4352 79 ▶ next if ($j->[0]{-relation_chain_depth} || 0) < $start_depth;
Branch: 1 branch
BranchTrueFalseTotal
if ($j->[0]{"-relation_chain_depth"} || 0) < $start_depth 1 78 79
Condition50%1/2
$j->[0]{'-relation_chain_depth'} || 0
l!l
790
MC/DC0%0/1
$j->[0]{'-relation_chain_depth'} || 0
$j->[0]{'-relation_chain_depth'}
Truth table50%1/2
A
A= $j->[0]{'-relation_chain_depth'}
Aresult
11
00
4353  
4354 78 my @jpath = map { keys %$_ } @{$j->[0]{-join_path}};
4355  
4356 78 my $p = $join_map;
4357 78 ▶ $p = $p->{$_} ||= {} for @jpath[ ($start_depth/2) .. $#jpath]; #only even depths are actual jpath boundaries
Condition100%2/2
$p->{$_} ||= {}
l!l
1271
MC/DC100%1/1
$p->{$_} ||= {}
$p->{$_}
Truth table100%2/2
A
A= $p->{$_}
Aresult
11
00
4358 78 push @{$p->{-join_aliases} }, $j->[0]{-alias};
4359 }
4360 }
4361  
4362 49 my @prefetch = $source->_resolve_prefetch( $prefetch, $alias, $join_map );
4363  
4364 # save these for after distinct resolution
4365 49 @prefetch_select = map { $_->[0] } @prefetch;
4366 49 @prefetch_as = map { $_->[1] } @prefetch;
4367 }
4368  
4369 # run through the resulting joinstructure (starting from our current slot)
4370 # and unset collapse if proven unnecessary
4371 #
4372 # also while we are at it find out if the current root source has
4373 # been premultiplied by previous related_source chaining
4374 #
4375 # this allows to predict whether a root object with all other relation
4376 # data set to NULL is in fact unique
4377 4774 ▶ if ($attrs->{collapse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{"collapse"}) 49 4725 4774
4378  
4379 49 ▶ if (ref $attrs->{from} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $attrs->{'from'} eq 'ARRAY') { } 49 0 49
4380  
4381 49 ▶ if (@{$attrs->{from}} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$attrs->{'from'};} == 1) { } 0 49 49
4382 # no joins - no collapse
4383 0 $attrs->{collapse} = 0;
4384 }
4385 else {
4386 # find where our table-spec starts
4387 49 my @fromlist = @{$attrs->{from}};
4388 49 ▶ while (@fromlist) {
Branch: 1 branch
BranchTrueFalseTotal
if (@fromlist) 56 0 56
4389 56 my $t = shift @fromlist;
4390  
4391 56 my $is_multi;
4392 # me vs join from-spec distinction - a ref means non-root
4393 56 ▶ if (ref $t eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $t eq "ARRAY") 7 49 56
4394 7 $t = $t->[0];
4395 7 ▶ $is_multi ||= ! $t->{-is_single};
Condition66%2/3
$is_multi ||= !$t->{"-is_single"}
l!l&&r!l&&!r
043
MC/DC50%1/2
$is_multi ||= !$t->{"-is_single"}
$is_multi !$t->{"-is_single"}
Truth table66%2/3
A ||= not(B)
A= $is_multiB= !$t->{"-is_single"}
ABresult
1X1
011
000
4396 }
4397 56 ▶ last if ($t->{-alias} && $t->{-alias} eq $alias);
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"-alias"} and $t->{"-alias"} eq $alias 49 7 56
Condition66%2/3
$t->{"-alias"} and $t->{"-alias"} eq $alias
!ll&&!rl&&r
0749
MC/DC50%1/2
$t->{"-alias"} and $t->{"-alias"} eq $alias
$t->{"-alias"} $t->{"-alias"} eq $alias
Truth table66%2/3
A and B
A= $t->{"-alias"}B= $t->{"-alias"} eq $alias
ABresult
0X0
100
111
4398 7 ▶ $attrs->{_main_source_premultiplied} ||= $is_multi;
Condition33%1/3
$attrs->{"_main_source_premultiplied"} ||= $is_multi
l!l&&r!l&&!r
007
MC/DC0%0/2
$attrs->{"_main_source_premultiplied"} ||= $is_multi
$attrs->{"_main_source_premultiplied"} $is_multi
Truth table33%1/3
A ||= B
A= $attrs->{"_main_source_premultiplied"}B= $is_multi
ABresult
1X1
011
000
4399 }
4400  
4401 # no non-singles remaining, nor any premultiplication - nothing to collapse
4402 49 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
unless ($attrs->{"_main_source_premultiplied"} or grep {not $_->[0]{"-is_single"};} @fromlist) 13 36 49
Condition66%2/3
$attrs->{"_main_source_premultiplied"} or grep {not $_->[0]{"-is_single"};} @fromlist
l!l&&r!l&&!r
03613
MC/DC50%1/2
$attrs->{"_main_source_premultiplied"} or grep {not $_->[0]{"-is_single"};} @fromlist
$attrs->{"_main_source_premultiplied"} grep {not $_->[0]{"-is_single"};} @fromlist
Truth table66%2/3
A or B
A= $attrs->{"_main_source_premultiplied"}B= grep {not $_->[0]{"-is_single"};} @fromlist
ABresult
1X1
011
000
4403 ! $attrs->{_main_source_premultiplied}
4404 and
4405 72 ! grep { ! $_->[0]{-is_single} } @fromlist
4406 ) {
4407 13 $attrs->{collapse} = 0;
4408 }
4409 }
4410 }
4411  
4412 else {
4413 # if we can not analyze the from - err on the side of safety
4414 0 $attrs->{_main_source_premultiplied} = 1;
4415 }
4416 }
4417  
4418 # generate the distinct induced group_by before injecting the prefetched select/as parts
4419 4774 ▶ if (delete $attrs->{distinct}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $attrs->{"distinct"}) 33 4741 4774
4420 33 ▶ if ($attrs->{group_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attrs->{'group_by'}) { } 0 33 33
4421 0 carp_unique ("Useless use of distinct on a grouped resultset ('distinct' is ignored when a 'group_by' is present)");
4422 }
4423 else {
4424 33 $attrs->{_grouped_by_distinct} = 1;
4425 # distinct affects only the main selection part, not what prefetch may add below
4426 33 ($attrs->{group_by}, my $new_order) = $source->storage->_group_over_selection($attrs);
4427  
4428 # FIXME possibly ignore a rewritten order_by (may turn out to be an issue)
4429 # The thinking is: if we are collapsing the subquerying prefetch engine will
4430 # rip stuff apart for us anyway, and we do not want to have a potentially
4431 # function-converted external order_by
4432 # ( there is an explicit if ( collapse && _grouped_by_distinct ) check in QueryRewrite )
4433 33 ▶ $attrs->{order_by} = $new_order unless $attrs->{collapse};
Branch: 1 branch
BranchTrueFalseTotal
unless $attrs->{"collapse"} 28 5 33
4434 }
4435 }
4436  
4437 # inject prefetch-bound selection (if any)
4438 4774 push @{$attrs->{select}}, @prefetch_select;
4439 4774 push @{$attrs->{as}}, @prefetch_as;
4440  
4441 $attrs->{_simple_passthrough_construction} = !(
4442 $attrs->{collapse}
4443 or
4444 4774 ▶ grep { $_ =~ /\./ } @{$attrs->{as}}
Condition100%3/3
$attrs->{'collapse'} || grep({$_ =~ /\./;} @{$$attrs{'as'};})
l!l&&r!l&&!r
36134725
MC/DC100%2/2
$attrs->{'collapse'} || grep({$_ =~ /\./;} @{$$attrs{'as'};})
$attrs->{'collapse'} grep({$_ =~ /\./;} @{$$attrs{'as'};})
Truth table100%3/3
A || B
A= $attrs->{'collapse'}B= grep({$_ =~ /\./;} @{$$attrs{'as'};})
ABresult
1X1
011
000
4445 );
4446  
4447 # if both page and offset are specified, produce a combined offset
4448 # even though it doesn't make much sense, this is what pre 081xx has
4449 # been doing
4450 4774 ▶ if (my $page = delete $attrs->{page}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $page = delete $attrs->{"page"}) 14 4760 4774
4451 $attrs->{offset} =
4452 ($attrs->{rows} * ($page - 1))
4453 +
4454 14 ▶ ($attrs->{offset} || 0)
Condition50%1/2
$attrs->{'offset'} || 0
l!l
014
MC/DC0%0/1
$attrs->{'offset'} || 0
$attrs->{'offset'}
Truth table50%1/2
A
A= $attrs->{'offset'}
Aresult
11
00
4455 ;
4456 }
4457  
4458 4774 return $self->{_attrs} = $attrs;
4459 }
4460  
4461 260 ▶sub _rollout_attr {
Subroutine _rollout_attr: called CC=3 SCAR=11.0
4462 260 my ($self, $attr) = @_;
4463  
4464 260 ▶ if (ref $attr eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $attr eq 'HASH') { } 110 150 260
elsif (ref $attr eq 'ARRAY') { } 64 86 150
4465 110 return $self->_rollout_hash($attr);
4466 } elsif (ref $attr eq 'ARRAY') {
4467 64 return $self->_rollout_array($attr);
4468 } else {
4469 86 return [$attr];
4470 }
4471 }
4472  
4473 74 ▶sub _rollout_array {
Subroutine _rollout_array: called CC=4 SCAR=13.9
4474 74 my ($self, $attr) = @_;
4475  
4476 74 my @rolled_array;
4477 74 foreach my $element (@{$attr}) {
4478 128 ▶ if (ref $element eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $element eq 'HASH') { } 36 92 128
elsif (ref $element eq 'ARRAY') { } 10 82 92
4479 36 push( @rolled_array, @{ $self->_rollout_hash( $element ) } );
4480 } elsif (ref $element eq 'ARRAY') {
4481 # XXX - should probably recurse here
4482 10 push( @rolled_array, @{$self->_rollout_array($element)} );
4483 } else {
4484 82 push( @rolled_array, $element );
4485 }
4486 }
4487 74 return \@rolled_array;
4488 }
4489  
4490 146 ▶sub _rollout_hash {
Subroutine _rollout_hash: called CC=2 SCAR=6.9
4491 146 my ($self, $attr) = @_;
4492  
4493 146 my @rolled_array;
4494 146 foreach my $key (keys %{$attr}) {
4495 41 push( @rolled_array, { $key => $attr->{$key} } );
4496 }
4497 146 return \@rolled_array;
4498 }
4499  
4500 101 ▶sub _calculate_score {
Subroutine _calculate_score: called CC=13 SCAR=25.9
4501 101 my ($self, $a, $b) = @_;
4502  
4503 101 ▶ if (defined $a xor defined $b) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $a xor defined $b) { } 0 101 101
elsif (not defined $a) { } 2 99 101
Condition50%2/4
defined $a xor defined $b
l&&rl&&!r!l&&r!l&&!r
99002
MC/DC0%0/2
defined $a xor defined $b
defined $a defined $b
Truth table50%2/4
A xor B
A= defined $aB= defined $b
ABresult
110
101
011
000
4504 0 return 0;
4505 }
4506 elsif (not defined $a) {
4507 2 return 1;
4508 }
4509  
4510 99 ▶ if (ref $b eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $b eq 'HASH') { } 38 61 99
4511 38 my ($b_key) = keys %{$b};
4512 38 ▶ $b_key = '' if ! defined $b_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $b_key 1 37 38
4513 38 ▶ if (ref $a eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $a eq 'HASH') { } 12 26 38
4514 12 my ($a_key) = keys %{$a};
4515 12 ▶ $a_key = '' if ! defined $a_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a_key 1 11 12
4516 12 ▶ if ($a_key eq $b_key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a_key eq $b_key) { } 12 0 12
4517 12 return (1 + $self->_calculate_score( $a->{$a_key}, $b->{$b_key} ));
4518 } else {
4519 0 return 0;
4520 }
4521 } else {
4522 26 ▶ return ($a eq $b_key) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$a eq $b_key ? : 16 10 26
4523 }
4524 } else {
4525 61 ▶ if (ref $a eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $a eq 'HASH') { } 8 53 61
4526 8 my ($a_key) = keys %{$a};
4527 8 ▶ return ($b eq $a_key) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$b eq $a_key ? : 7 1 8
4528 } else {
4529 53 ▶ return ($b eq $a) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$b eq $a ? : 13 40 53
4530 }
4531 }
4532 }
4533  
4534 # Walk condition structures and extract relationship names referenced
4535 # via dotted column notation (e.g. 'artist.name' -> 'artist').
4536 # Supports nested relationships ('artist.producer.name') and builds
4537 # the appropriate join structure ({ artist => 'producer' }).
4538 # Returns undef if no auto-joins are needed.
4539 4017 ▶sub _extract_condition_rels {
Subroutine _extract_condition_rels: called CC=7 SCAR=20.8
4540 4017 my ($self, $conds, $source, $alias) = @_;
4541  
4542 4017 my %rels;
4543 4017 $self->_walk_condition_keys($_, $source, $alias, \%rels) for grep { defined } @$conds;
4544  
4545 4017 ▶ return undef unless %rels;
Branch: 1 branch
BranchTrueFalseTotal
unless %rels 3980 37 4017
4546  
4547 # Convert flat relationship hash into join structure
4548 # e.g. { artist => undef, 'cd.artist' => undef }
4549 # becomes [ 'artist', { cd => 'artist' } ]
4550 37 my @joins;
4551 37 for my $path (sort keys %rels) {
4552 40 my @parts = split /\./, $path;
4553 40 ▶ if (@parts == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts == 1) { } 40 0 40
4554 40 push @joins, $parts[0];
4555 } else {
4556 # Build nested: [a, b, c] -> { a => { b => 'c' } }
4557 0 my $leaf = pop @parts;
4558 0 my $node = $leaf;
4559 0 for my $part (reverse @parts) {
4560 0 $node = { $part => $node };
4561 }
4562 0 push @joins, $node;
4563 }
4564 }
4565  
4566 37 ▶ return @joins == 1 ? $joins[0] : \@joins;
Branch: 1 branch
BranchTrueFalseTotal
@joins == 1 ? : 34 3 37
4567 }
4568  
4569 2594 ▶sub _walk_condition_keys {
Subroutine _walk_condition_keys: called CC=11 SCAR=24.0
4570 2594 my ($self, $cond, $source, $alias, $rels) = @_;
4571  
4572 2594 ▶ return unless defined $cond;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cond 0 2594 2594
4573  
4574 2594 ▶ if (ref $cond eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $cond eq 'HASH') { } 2498 96 2594
elsif (ref $cond eq 'ARRAY') { } 76 20 96
4575 2498 for my $key (keys %$cond) {
4576 2651 ▶ if ($key =~ /^-(?:and|or|not|not_bool|bool)$/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($key =~ /^-(?:and|or|not|not_bool|bool)$/i) { } 47 2604 2651
elsif ($key =~ /^-/) { } 1 2603 2604
4577 47 $self->_walk_condition_keys($cond->{$key}, $source, $alias, $rels);
4578 }
4579 elsif ($key =~ /^-/) {
4580 # Other SQL::Abstract operators, skip
4581 1 next;
4582 }
4583 else {
4584 2603 $self->_check_column_rel($key, $source, $alias, $rels, $cond->{$key});
4585 # Also walk into the value for nested conditions
4586 2603 ▶ if (ref $cond->{$key} eq 'HASH' || ref $cond->{$key} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cond->{$key} eq "HASH" or ref $cond->{$key} eq "ARRAY") 234 2369 2603
Condition100%3/3
ref $cond->{$key} eq "HASH" or ref $cond->{$key} eq "ARRAY"
l!l&&r!l&&!r
140942369
MC/DC100%2/2
ref $cond->{$key} eq "HASH" or ref $cond->{$key} eq "ARRAY"
ref $cond->{$key} eq "HASH" ref $cond->{$key} eq "ARRAY"
Truth table100%3/3
A or B
A= ref $cond->{$key} eq "HASH"B= ref $cond->{$key} eq "ARRAY"
ABresult
1X1
011
000
4587 # Value-side hashrefs are operator conditions ({ '>' => 3 }), not column refs
4588 # No need to recurse into them
4589 }
4590 }
4591 }
4592 }
4593 elsif (ref $cond eq 'ARRAY') {
4594 # Array conditions: could be [ -and => cond1, cond2 ] or [ cond1, cond2 ]
4595 76 my @items = @$cond;
4596 76 for my $item (@items) {
4597 173 ▶ if (ref $item) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item) 118 55 173
4598 118 $self->_walk_condition_keys($item, $source, $alias, $rels);
4599 }
4600 # Skip scalar items like -and, -or
4601 }
4602 }
4603 # Literal SQL (SCALAR/REF) is intentionally NOT scanned for auto-discover.
4604 # Literal SQL may contain correlated sub-query references, function calls,
4605 # or other constructs where table.column patterns should not trigger joins.
4606 # Users writing literal SQL are responsible for declaring their own joins.
4607 }
4608  
4609 113 ▶sub _flatten_join_attr {
Subroutine _flatten_join_attr: called CC=5 SCAR=18.1
4610 113 my ($self, $attr) = @_;
4611 113 ▶ return () unless defined $attr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $attr 26 87 113
4612 87 ▶ if (!ref $attr) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $attr) { } 75 12 87
elsif (ref $attr eq 'ARRAY') { } 12 0 12
elsif (ref $attr eq 'HASH') { } 0 0 0
4613 75 return ($attr);
4614 }
4615 elsif (ref $attr eq 'ARRAY') {
4616 12 return map { $self->_flatten_join_attr($_) } @$attr;
4617 }
4618 elsif (ref $attr eq 'HASH') {
4619 0 return map { $_, $self->_flatten_join_attr($attr->{$_}) } keys %$attr;
4620 }
4621 0 return ();
4622 }
4623  
4624 2603 ▶sub _check_column_rel {
Subroutine _check_column_rel: called CC=7 SCAR=19.5
4625 2603 my ($self, $key, $source, $alias, $rels, $value) = @_;
4626  
4627 # Only process dotted column names
4628 2603 ▶ return unless $key =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /\./ 765 1838 2603
4629  
4630 1838 my @parts = split /\./, $key;
4631  
4632 # Skip if first part is the current table alias (e.g. 'me.column')
4633 1838 ▶ return if $parts[0] eq $alias;
Branch: 1 branch
BranchTrueFalseTotal
if $parts[0] eq $alias 1792 46 1838
4634  
4635 # Skip auto-join when the value is a pure correlation reference
4636 # (-ident / literal SQL), not a filter value. A condition like
4637 # 'books.owner' => { -ident => 'owner.id' }
4638 # is an identifier-to-identifier comparison: it expresses a join/
4639 # correlation *condition*, not "filter the related table by a value".
4640 # Auto-joining it here would materialise a LOCAL "books" range table
4641 # inside a subquery and, by SQL lexical scoping, shadow an outer
4642 # correlated "books" alias -- silently de-correlating the subquery.
4643 # Matching upstream, such keys never auto-join; the user
4644 # declares the join explicitly via { join => ... } when an inner
4645 # traversal is actually intended. Auto-join stays active for genuine
4646 # filters ('artist.name' => 'McCrae'), see t/search/auto_join.t.
4647 46 ▶ return if $self->_cond_value_is_correlation($value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_cond_value_is_correlation($value) 1 45 46
4648  
4649 # Walk relationship chain to verify each part is a valid relationship
4650 45 my $cur_source = $source;
4651 45 my @rel_path;
4652 45 for my $i (0 .. $#parts - 1) { # all parts except the last (which is the column)
4653 45 my $rel_name = $parts[$i];
4654 45 ▶ if ($cur_source->has_relationship($rel_name)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_source->has_relationship($rel_name)) { } 40 5 45
4655 40 push @rel_path, $rel_name;
4656 40 $cur_source = $cur_source->related_source($rel_name);
4657 } else {
4658 # Not a valid relationship chain, skip
4659 5 return;
4660 }
4661 }
4662  
4663 # Record the full relationship path
4664 40 ▶ $rels->{CORE::join('.', @rel_path)} = 1 if @rel_path;
Branch: 1 branch
BranchTrueFalseTotal
if @rel_path 40 0 40
4665 }
4666  
4667 # True when a condition RHS is a pure correlation/identifier reference
4668 # rather than a filter value -- i.e. it carries an -ident anywhere, or is
4669 # literal SQL (SCALAR/REF). Such a value means the dotted LHS is part of a
4670 # join/correlation condition, so the LHS must NOT trigger an auto-join (it
4671 # would shadow an outer correlated alias inside a subquery).
4672 59 ▶sub _cond_value_is_correlation {
Subroutine _cond_value_is_correlation: called CC=12 SCAR=30.0
4673 59 my ($self, $value) = @_;
4674  
4675 59 ▶ return 0 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 4 55 59
4676  
4677 55 my $r = ref $value;
4678  
4679 # Literal SQL: \'...' or \[ '...', @bind ]. Already never walked into for
4680 # join-discovery; an LHS compared against literal SQL is the user's own
4681 # correlation/expression, not a filter we should auto-join.
4682 55 ▶ return 1 if $r eq 'SCALAR' or $r eq 'REF';
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "SCALAR" or $r eq "REF" 0 55 55
Condition33%1/3
$r eq "SCALAR" or $r eq "REF"
l!l&&r!l&&!r
0055
MC/DC0%0/2
$r eq "SCALAR" or $r eq "REF"
$r eq "SCALAR" $r eq "REF"
Truth table33%1/3
A or B
A= $r eq "SCALAR"B= $r eq "REF"
ABresult
1X1
011
000
4683  
4684 55 ▶ if ($r eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "HASH") 14 41 55
4685 14 for my $k (keys %$value) {
4686 14 ▶ return 1 if $k eq '-ident';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "-ident" 1 13 14
4687 # Operator wrappers: { '!=' => { -ident => ... } }, { '=' => \'...' }
4688 13 ▶ return 1 if $self->_cond_value_is_correlation($value->{$k});
Branch: 1 branch
BranchTrueFalseTotal
if $self->_cond_value_is_correlation($value->{$k}) 0 13 13
4689 }
4690 13 return 0;
4691 }
4692  
4693 41 ▶ if ($r eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "ARRAY") 0 41 41
4694 # e.g. { '!=' => ['-and', { -ident => 'me.cdid' }, 23414] }: a single
4695 # -ident anywhere marks the whole comparison as a correlation condition.
4696 0 for my $el (@$value) {
4697 0 ▶ return 1 if ref $el and $self->_cond_value_is_correlation($el);
Branch: 1 branch
BranchTrueFalseTotal
if ref $el and $self->_cond_value_is_correlation($el) 0 0 0
Condition0%0/3
ref $el and $self->_cond_value_is_correlation($el)
!ll&&!rl&&r
000
MC/DC0%0/2
ref $el and $self->_cond_value_is_correlation($el)
ref $el $self->_cond_value_is_correlation($el)
Truth table0%0/3
A and B
A= ref $elB= $self->_cond_value_is_correlation($el)
ABresult
0X0
100
111
4698 }
4699 0 return 0;
4700 }
4701  
4702 41 return 0;
4703 }
4704  
4705 501 ▶sub _merge_joinpref_attr {
Subroutine _merge_joinpref_attr: called CC=13 SCAR=25.7
4706 501 my ($self, $orig, $import) = @_;
4707  
4708 501 ▶ return $import unless defined($orig);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $orig 367 134 501
4709 134 ▶ return $orig unless defined($import);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $import 4 130 134
4710  
4711 130 $orig = $self->_rollout_attr($orig);
4712 130 $import = $self->_rollout_attr($import);
4713  
4714 130 my $seen_keys;
4715 130 foreach my $import_element ( @{$import} ) {
4716 # find best candidate from $orig to merge $b_element into
4717 151 my $best_candidate = { position => undef, score => 0 }; my $position = 0;
4718 151 foreach my $orig_element ( @{$orig} ) {
4719 89 my $score = $self->_calculate_score( $orig_element, $import_element );
4720 89 ▶ if ($score > $best_candidate->{score}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($score > $best_candidate->{"score"}) 36 53 89
4721 36 $best_candidate->{position} = $position;
4722 36 $best_candidate->{score} = $score;
4723 }
4724 89 $position++;
4725 }
4726 151 ▶ my ($import_key) = ( ref $import_element eq 'HASH' ) ? keys %{$import_element} : ($import_element);
Branch: 1 branch
BranchTrueFalseTotal
ref $import_element eq 'HASH' ? : 28 123 151
4727 151 ▶ $import_key = '' if not defined $import_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $import_key 0 151 151
4728  
4729 151 ▶ if ($best_candidate->{score} == 0 || exists $seen_keys->{$import_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($best_candidate->{'score'} == 0 or exists $seen_keys->{$import_key}) { } 125 26 151
Condition100%3/3
$best_candidate->{"score"} == 0 or exists $seen_keys->{$import_key}
l!l&&r!l&&!r
118726
MC/DC100%2/2
$best_candidate->{"score"} == 0 or exists $seen_keys->{$import_key}
$best_candidate->{"score"} == 0 exists $seen_keys->{$import_key}
Truth table100%3/3
A or B
A= $best_candidate->{"score"} == 0B= exists $seen_keys->{$import_key}
ABresult
1X1
011
000
4730 125 push( @{$orig}, $import_element );
4731 } else {
4732 26 my $orig_best = $orig->[$best_candidate->{position}];
4733 # merge orig_best and b_element together and replace original with merged
4734 26 ▶ if (ref $orig_best ne 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $orig_best ne 'HASH') { } 17 9 26
elsif (ref $import_element eq 'HASH') { } 4 5 9
4735 17 $orig->[$best_candidate->{position}] = $import_element;
4736 } elsif (ref $import_element eq 'HASH') {
4737 4 my ($key) = keys %{$orig_best};
4738 4 $orig->[$best_candidate->{position}] = { $key => $self->_merge_joinpref_attr($orig_best->{$key}, $import_element->{$key}) };
4739 }
4740 }
4741 151 $seen_keys->{$import_key} = 1; # don't merge the same key twice
4742 }
4743  
4744 130 ▶ return @$orig ? $orig : ();
Branch: 1 branch
BranchTrueFalseTotal
@$orig ? : 128 2 130
4745 }
4746  
4747 {
4748 379 my $hm;
4749  
4750 7041 ▶ sub _merge_attr {
Subroutine _merge_attr: called CC=2 SCAR=11.9
4751 7041 ▶ $hm ||= do {
Condition66%2/3
$hm ||= do { my $hm = "Hash::Merge"->new; $hm->specify_behavior({"SCALAR", {"SCALAR", sub { my($defl, $defr) = map({defined $_;} @_[0, 1]); if ($defl xor $defr) { return [$defl ? $_[0] : $_[1]]; } elsif (not $defl) { return []; } else { return [$_[0], $_[1]]; } ; } , "ARRAY", sub { return $_[1] unless defined $_[0]; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless defined $_[0] or keys %{$_[1];}; return [$_[1]] unless defined $_[0]; return [$_[0]] unless keys %{$_[1];}; return [$_[0], $_[1]]; } }, "ARRAY", {"SCALAR", sub { return $_[0] unless defined $_[1]; '???'; return [@{$_[0];}, $_[1]]; } , "ARRAY", sub { my(@ret) = @{$_[0];} or return $_[1]; return [@ret, @{$_[1];}]; my(%idx) = map({$_, 1;} @ret); push @ret, grep({not defined $idx{$_};} @{$_[1];}); \@ret; } , "HASH", sub { return [$_[1]] unless @{$_[0];}; return $_[0] unless keys %{$_[1];}; '???'; return [@{$_[0];}, $_[1]]; } }, "HASH", {"SCALAR", sub { return [] unless keys %{$_[0];} or defined $_[1]; return [$_[0]] unless defined $_[1]; return [$_[1]] unless keys %{$_[0];}; return [$_[0], $_[1]]; } , "ARRAY", sub { return [] unless keys %{$_[0];} or @{$_[1];}; return [$_[0]] unless @{$_[1];}; return $_[1] unless keys %{$_[0];}; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless keys %{$_[0];} or keys %{$_[1];}; return [$_[0]] unless keys %{$_[1];}; return [$_[1]] unless keys %{$_[0];}; return [$_[0]] if $_[0] eq $_[1]; return [$_[0], $_[1]]; } }}, "DBIO_RS_ATTR_MERGER"); $hm }
l!l&&r!l&&!r
69241170
MC/DC0%0/2
$hm ||= do { my $hm = "Hash::Merge"->new; $hm->specify_behavior({"SCALAR", {"SCALAR", sub { my($defl, $defr) = map({defined $_;} @_[0, 1]); if ($defl xor $defr) { return [$defl ? $_[0] : $_[1]]; } elsif (not $defl) { return []; } else { return [$_[0], $_[1]]; } ; } , "ARRAY", sub { return $_[1] unless defined $_[0]; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless defined $_[0] or keys %{$_[1];}; return [$_[1]] unless defined $_[0]; return [$_[0]] unless keys %{$_[1];}; return [$_[0], $_[1]]; } }, "ARRAY", {"SCALAR", sub { return $_[0] unless defined $_[1]; '???'; return [@{$_[0];}, $_[1]]; } , "ARRAY", sub { my(@ret) = @{$_[0];} or return $_[1]; return [@ret, @{$_[1];}]; my(%idx) = map({$_, 1;} @ret); push @ret, grep({not defined $idx{$_};} @{$_[1];}); \@ret; } , "HASH", sub { return [$_[1]] unless @{$_[0];}; return $_[0] unless keys %{$_[1];}; '???'; return [@{$_[0];}, $_[1]]; } }, "HASH", {"SCALAR", sub { return [] unless keys %{$_[0];} or defined $_[1]; return [$_[0]] unless defined $_[1]; return [$_[1]] unless keys %{$_[0];}; return [$_[0], $_[1]]; } , "ARRAY", sub { return [] unless keys %{$_[0];} or @{$_[1];}; return [$_[0]] unless @{$_[1];}; return $_[1] unless keys %{$_[0];}; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless keys %{$_[0];} or keys %{$_[1];}; return [$_[0]] unless keys %{$_[1];}; return [$_[1]] unless keys %{$_[0];}; return [$_[0]] if $_[0] eq $_[1]; return [$_[0], $_[1]]; } }}, "DBIO_RS_ATTR_MERGER"); $hm }
$hm do { my $hm = "Hash::Merge"->new; $hm->specify_behavior({"SCALAR", {"SCALAR", sub { my($defl, $defr) = map({defined $_;} @_[0, 1]); if ($defl xor $defr) { return [$defl ? $_[0] : $_[1]]; } elsif (not $defl) { return []; } else { return [$_[0], $_[1]]; } ; } , "ARRAY", sub { return $_[1] unless defined $_[0]; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless defined $_[0] or keys %{$_[1];}; return [$_[1]] unless defined $_[0]; return [$_[0]] unless keys %{$_[1];}; return [$_[0], $_[1]]; } }, "ARRAY", {"SCALAR", sub { return $_[0] unless defined $_[1]; '???'; return [@{$_[0];}, $_[1]]; } , "ARRAY", sub { my(@ret) = @{$_[0];} or return $_[1]; return [@ret, @{$_[1];}]; my(%idx) = map({$_, 1;} @ret); push @ret, grep({not defined $idx{$_};} @{$_[1];}); \@ret; } , "HASH", sub { return [$_[1]] unless @{$_[0];}; return $_[0] unless keys %{$_[1];}; '???'; return [@{$_[0];}, $_[1]]; } }, "HASH", {"SCALAR", sub { return [] unless keys %{$_[0];} or defined $_[1]; return [$_[0]] unless defined $_[1]; return [$_[1]] unless keys %{$_[0];}; return [$_[0], $_[1]]; } , "ARRAY", sub { return [] unless keys %{$_[0];} or @{$_[1];}; return [$_[0]] unless @{$_[1];}; return $_[1] unless keys %{$_[0];}; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless keys %{$_[0];} or keys %{$_[1];}; return [$_[0]] unless keys %{$_[1];}; return [$_[1]] unless keys %{$_[0];}; return [$_[0]] if $_[0] eq $_[1]; return [$_[0], $_[1]]; } }}, "DBIO_RS_ATTR_MERGER"); $hm }
Truth table66%2/3
A ||= B
A= $hmB= do { my $hm = "Hash::Merge"->new; $hm->specify_behavior({"SCALAR", {"SCALAR", sub { my($defl, $defr) = map({defined $_;} @_[0, 1]); if ($defl xor $defr) { return [$defl ? $_[0] : $_[1]]; } elsif (not $defl) { return []; } else { return [$_[0], $_[1]]; } ; } , "ARRAY", sub { return $_[1] unless defined $_[0]; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless defined $_[0] or keys %{$_[1];}; return [$_[1]] unless defined $_[0]; return [$_[0]] unless keys %{$_[1];}; return [$_[0], $_[1]]; } }, "ARRAY", {"SCALAR", sub { return $_[0] unless defined $_[1]; '???'; return [@{$_[0];}, $_[1]]; } , "ARRAY", sub { my(@ret) = @{$_[0];} or return $_[1]; return [@ret, @{$_[1];}]; my(%idx) = map({$_, 1;} @ret); push @ret, grep({not defined $idx{$_};} @{$_[1];}); \@ret; } , "HASH", sub { return [$_[1]] unless @{$_[0];}; return $_[0] unless keys %{$_[1];}; '???'; return [@{$_[0];}, $_[1]]; } }, "HASH", {"SCALAR", sub { return [] unless keys %{$_[0];} or defined $_[1]; return [$_[0]] unless defined $_[1]; return [$_[1]] unless keys %{$_[0];}; return [$_[0], $_[1]]; } , "ARRAY", sub { return [] unless keys %{$_[0];} or @{$_[1];}; return [$_[0]] unless @{$_[1];}; return $_[1] unless keys %{$_[0];}; '???'; return [$_[0], @{$_[1];}]; } , "HASH", sub { return [] unless keys %{$_[0];} or keys %{$_[1];}; return [$_[0]] unless keys %{$_[1];}; return [$_[1]] unless keys %{$_[0];}; return [$_[0]] if $_[0] eq $_[1]; return [$_[0], $_[1]]; } }}, "DBIO_RS_ATTR_MERGER"); $hm }
ABresult
1X1
011
000
4752 117 my $hm = Hash::Merge->new;
4753  
4754 $hm->specify_behavior({
4755 SCALAR => {
4756 63 ▶ SCALAR => sub {
Subroutine __ANON__: called CC=5 SCAR=17.5
4757 63 my ($defl, $defr) = map { defined $_ } (@_[0,1]);
4758  
4759 63 ▶ if ($defl xor $defr) {
Branch: 2 branches
BranchTrueFalseTotal
if ($defl xor $defr) { } 62 1 63
elsif (not $defl) { } 1 0 1
Condition50%2/4
$defl xor $defr
l&&rl&&!r!l&&r!l&&!r
00621
MC/DC50%1/2
$defl xor $defr
$defl $defr
Truth table50%2/4
A xor B
A= $deflB= $defr
ABresult
110
101
011
000
4760 62 ▶ return [ $defl ? $_[0] : $_[1] ];
Branch: 1 branch
BranchTrueFalseTotal
$defl ? : 0 62 62
4761 }
4762 elsif (! $defl) {
4763 1 return [];
4764 }
4765 elsif (__HM_DEDUP and $_[0] eq $_[1]) {
4766 return [ $_[0] ];
4767 }
4768 else {
4769 0 return [$_[0], $_[1]];
4770 }
4771 },
4772 1491 ▶ ARRAY => sub {
Subroutine __ANON__: called CC=2 SCAR=11.6
4773 1491 ▶ return $_[1] if !defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 1491 0 1491
4774 0 return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4775 0 return [$_[0], @{$_[1]}]
4776 },
4777 344 ▶ HASH => sub {
Subroutine __ANON__: called CC=5 SCAR=20.2
4778 344 ▶ return [] if !defined $_[0] and !keys %{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] or keys %{$_[1];} 1 343 344
Condition66%2/3
defined $_[0] or keys %{$_[1];}
l!l&&r!l&&!r
03431
MC/DC50%1/2
defined $_[0] or keys %{$_[1];}
defined $_[0] keys %{$_[1];}
Truth table66%2/3
A or B
A= defined $_[0]B= keys %{$_[1];}
ABresult
1X1
011
000
4779 343 ▶ return [ $_[1] ] if !defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 343 0 343
4780 0 ▶ return [ $_[0] ] if !keys %{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[1];} 0 0 0
4781 0 return [$_[0], $_[1]]
4782 },
4783 },
4784 ARRAY => {
4785 5074 ▶ SCALAR => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
4786 5074 ▶ return $_[0] if !defined $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] 5073 1 5074
4787 1 return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4788 1 return [@{$_[0]}, $_[1]]
4789 },
4790 69 ▶ ARRAY => sub {
Subroutine __ANON__: called CC=2 SCAR=9.2
4791 69 ▶ my @ret = @{$_[0]} or return $_[1];
Branch: 1 branch
BranchTrueFalseTotal
my(@ret) = @{$_[0];} or return $_[1] 63 6 69
4792 63 return [ @ret, @{$_[1]} ] unless __HM_DEDUP;
4793 0 my %idx = map { $_ => 1 } @ret;
4794 0 push @ret, grep { ! defined $idx{$_} } (@{$_[1]});
4795 0 \@ret;
4796 },
4797 0 ▶ HASH => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
4798 0 ▶ return [ $_[1] ] if ! @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$_[0];} 0 0 0
4799 0 ▶ return $_[0] if !keys %{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[1];} 0 0 0
4800 0 return $_[0] if __HM_DEDUP and grep { $_ eq $_[1] } @{$_[0]};
4801 0 return [ @{$_[0]}, $_[1] ];
4802 },
4803 },
4804 HASH => {
4805 0 ▶ SCALAR => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4806 0 ▶ return [] if !keys %{$_[0]} and !defined $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} or defined $_[1] 0 0 0
Condition0%0/3
keys %{$_[0];} or defined $_[1]
l!l&&r!l&&!r
000
MC/DC0%0/2
keys %{$_[0];} or defined $_[1]
keys %{$_[0];} defined $_[1]
Truth table0%0/3
A or B
A= keys %{$_[0];}B= defined $_[1]
ABresult
1X1
011
000
4807 0 ▶ return [ $_[0] ] if !defined $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] 0 0 0
4808 0 ▶ return [ $_[1] ] if !keys %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} 0 0 0
4809 0 return [$_[0], $_[1]]
4810 },
4811 0 ▶ ARRAY => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4812 0 ▶ return [] if !keys %{$_[0]} and !@{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} or @{$_[1];} 0 0 0
Condition0%0/3
keys %{$_[0];} or @{$_[1];}
l!l&&r!l&&!r
000
MC/DC0%0/2
keys %{$_[0];} or @{$_[1];}
keys %{$_[0];} @{$_[1];}
Truth table0%0/3
A or B
A= keys %{$_[0];}B= @{$_[1];}
ABresult
1X1
011
000
4813 0 ▶ return [ $_[0] ] if !@{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$_[1];} 0 0 0
4814 0 ▶ return $_[1] if !keys %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} 0 0 0
4815 0 return $_[1] if __HM_DEDUP and grep { $_ eq $_[0] } @{$_[1]};
4816 0 return [ $_[0], @{$_[1]} ];
4817 },
4818 0 ▶ HASH => sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
4819 0 ▶ return [] if !keys %{$_[0]} and !keys %{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} or keys %{$_[1];} 0 0 0
Condition0%0/3
keys %{$_[0];} or keys %{$_[1];}
l!l&&r!l&&!r
000
MC/DC0%0/2
keys %{$_[0];} or keys %{$_[1];}
keys %{$_[0];} keys %{$_[1];}
Truth table0%0/3
A or B
A= keys %{$_[0];}B= keys %{$_[1];}
ABresult
1X1
011
000
4820 0 ▶ return [ $_[0] ] if !keys %{$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[1];} 0 0 0
4821 0 ▶ return [ $_[1] ] if !keys %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0];} 0 0 0
4822 0 ▶ return [ $_[0] ] if $_[0] eq $_[1];
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] eq $_[1] 0 0 0
4823 0 return [ $_[0], $_[1] ];
4824 },
4825 }
4826 117 } => 'DBIO_RS_ATTR_MERGER');
4827 117 $hm;
4828 };
4829  
4830 7041 return $hm->merge ($_[1], $_[2]);
4831 }
4832 }
4833  
4834 379 ▶sub STORABLE_freeze {
Subroutine STORABLE_freeze: called CC=3 SCAR=11.0
Pod undocumented
4835 21 my ($self, $cloning) = @_;
4836 21 my $to_serialize = { %$self };
4837  
4838 # A cursor in progress can't be serialized (and would make little sense anyway)
4839 # the parser can be regenerated (and can't be serialized)
4840 # an async context is a live object (a storage or a transaction
4841 # connection), meaningless after thaw: a frozen resultset is unbound
4842 21 delete @{$to_serialize}{qw/cursor _row_parser _result_inflator _async_context/};
4843  
4844 # nor is it sensical to store a not-yet-fired-count pager
4845 21 ▶ if ($to_serialize->{pager} and ref $to_serialize->{pager}{total_entries} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($to_serialize->{"pager"} and ref $to_serialize->{"pager"}{"total_entries"} eq "CODE") 5 16 21
Condition66%2/3
$to_serialize->{"pager"} and ref $to_serialize->{"pager"}{"total_entries"} eq "CODE"
!ll&&!rl&&r
1605
MC/DC50%1/2
$to_serialize->{"pager"} and ref $to_serialize->{"pager"}{"total_entries"} eq "CODE"
$to_serialize->{"pager"} ref $to_serialize->{"pager"}{"total_entries"} eq "CODE"
Truth table66%2/3
A and B
A= $to_serialize->{"pager"}B= ref $to_serialize->{"pager"}{"total_entries"} eq "CODE"
ABresult
0X0
100
111
4846 5 delete $to_serialize->{pager};
4847 }
4848  
4849 21 Storable::nfreeze($to_serialize);
4850 }
4851  
4852  
4853 20 ▶sub STORABLE_thaw {
Subroutine STORABLE_thaw: called CC=1 SCAR=0.0
Pod documented
4854 20 my ($self, $cloning, $serialized) = @_;
4855  
4856 20 %$self = %{ Storable::thaw($serialized) };
4857  
4858 20 $self;
4859 }
4860  
4861  
4862  
4863 338 ▶sub throw_exception {
Subroutine throw_exception: called CC=3 SCAR=11.0
Pod documented
4864 338 my $self=shift;
4865  
4866 338 ▶ if (ref $self and my $rsrc = $self->result_source) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self and my $rsrc = $self->result_source) { } 337 1 338
Condition66%2/3
ref $self and my $rsrc = $self->result_source
!ll&&!rl&&r
10337
MC/DC50%1/2
ref $self and my $rsrc = $self->result_source
ref $self my $rsrc = $self->result_source
Truth table66%2/3
A and B
A= ref $selfB= my $rsrc = $self->result_source
ABresult
0X0
100
111
4867 337 $rsrc->throw_exception(@_)
4868 }
4869 else {
4870 1 DBIO::Exception->throw(@_);
4871 }
4872 }
4873  
4874 # ============================================================
4875 # Integrated helper methods (from DBIx::Class::Helpers by FREW)
4876 # These are available natively without load_components.
4877 # ============================================================
4878  
4879  
4880 4 ▶sub me { CORE::join('.', $_[0]->current_source_alias, $_[1] || q{}) }
Subroutine me: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[1] || ''
l!l
22
MC/DC100%1/1
$_[1] || ''
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
4881  
4882  
4883 36 ▶sub order_by {
Subroutine order_by: called CC=3 SCAR=11.0
Pod documented
4884 36 my ($self, @order) = @_;
4885  
4886 # Belt and braces, no longer load bearing: since every top level ref is
4887 # handed to SQL::Abstract untouched anyway, this produces the same SQL as
4888 # the parser below - it only keeps the attribute value bit-for-bit identical
4889 # (the ref itself, not a list holding it) for the documented single ref call.
4890 36 ▶ return $self->search_rs(undef, { order_by => $order[0] })
Branch: 1 branch
BranchTrueFalseTotal
if @order == 1 and ref $order[0] 7 29 36
Condition100%3/3
@order == 1 and ref $order[0]
!ll&&!rl&&r
2367
MC/DC100%2/2
@order == 1 and ref $order[0]
@order == 1 ref $order[0]
Truth table100%3/3
A and B
A= @order == 1B= ref $order[0]
ABresult
0X0
100
111
4891 if @order == 1 && ref $order[0];
4892  
4893 29 return $self->search_rs(undef, {
4894 order_by => [ $self->_order_by_clauses(\@order) ],
4895 });
4896 }
4897  
4898 # Turns a flat order_by() argument list into an ordered list of ORDER BY
4899 # clauses, preserving the argument order. See the order_by POD for the forms.
4900 29 ▶sub _order_by_clauses {
Subroutine _order_by_clauses: called CC=8 SCAR=20.8
4901 29 my ($self, $args) = @_;
4902  
4903 29 my @queue = @$args;
4904 29 my @clauses;
4905  
4906 29 ▶ while (@queue) {
Branch: 1 branch
BranchTrueFalseTotal
if (@queue) 43 26 69
4907 43 my $item = shift @queue;
4908  
4909 43 ▶ if (ref $item eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $item eq 'ARRAY') { } 3 40 43
elsif (ref $item) { } 6 34 40
elsif (defined $item and $item =~ /^-(asc|desc)$/i) { } 15 19 34
4910 # A ref is native SQL::Abstract - we stay out of it. The list is only
4911 # flattened so that following arguments append after it; the elements
4912 # themselves are taken over verbatim and never parsed.
4913 3 push @clauses, @$item;
4914 }
4915 elsif (ref $item) {
4916 # hashrefs and literals (\'sql', \['sql', @bind]) pass through untouched
4917 6 push @clauses, $item;
4918 }
4919 ▶ elsif (defined $item and $item =~ /^-(asc|desc)$/i) {
Condition66%2/3
defined $item and $item =~ /^-(asc|desc)$/i
!ll&&!rl&&r
01915
MC/DC50%1/2
defined $item and $item =~ /^-(asc|desc)$/i
defined $item $item =~ /^-(asc|desc)$/i
Truth table66%2/3
A and B
A= defined $itemB= $item =~ /^-(asc|desc)$/i
ABresult
0X0
100
111
4920 15 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @queue and defined $queue[0] 3 12 15
Condition100%3/3
@queue and defined $queue[0]
!ll&&!rl&&r
2112
MC/DC100%2/2
@queue and defined $queue[0]
@queue defined $queue[0]
Truth table100%3/3
A and B
A= @queueB= defined $queue[0]
ABresult
0X0
100
111
4921 "Missing value after '$item' in order_by()"
4922 ) unless @queue and defined $queue[0];
4923 12 push @clauses, $self->_order_by_direction_clauses(lc $1, shift @queue);
4924 }
4925 else {
4926 19 push @clauses, $self->_order_by_magic_clauses($item);
4927 }
4928 }
4929  
4930 26 return @clauses;
4931 }
4932  
4933 # The value side of a flat '-asc'/'-desc' pair
4934 14 ▶sub _order_by_direction_clauses {
Subroutine _order_by_direction_clauses: called CC=3 SCAR=11.0
4935 14 my ($self, $dir, $value) = @_;
4936  
4937 14 ▶ return map { $self->_order_by_direction_clauses($dir, $_) } @$value
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 1 13 14
4938 if ref $value eq 'ARRAY';
4939  
4940 # anything else that is a ref goes to the direction untouched
4941 13 ▶ return { "-$dir" => $value } if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 1 12 13
4942  
4943 12 return map { +{ "-$dir" => $self->_order_by_qualify($_) } }
4944 split(/\s*,\s*/, $value);
4945 }
4946  
4947 # The FREW magic string syntax: '!' prefix means DESC, commas split columns
4948 19 ▶sub _order_by_magic_clauses {
Subroutine _order_by_magic_clauses: called CC=3 SCAR=11.0
4949 19 my ($self, $spec) = @_;
4950  
4951 19 my @clauses;
4952 19 for my $col (split(/\s*,\s*/, $spec)) {
4953 20 my $dir = 'asc';
4954 20 ▶ if (substr($col, 0, 1) eq '!') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($col, 0, 1) eq "!") 3 17 20
4955 3 $col = substr($col, 1);
4956 3 $dir = 'desc';
4957 }
4958 20 push @clauses, { "-$dir" => $self->_order_by_qualify($col) };
4959 }
4960 19 return @clauses;
4961 }
4962  
4963 33 ▶sub _order_by_qualify {
Subroutine _order_by_qualify: called CC=2 SCAR=6.9
4964 33 my ($self, $col) = @_;
4965  
4966 33 ▶ return $col if index($col, '.') != -1;
Branch: 1 branch
BranchTrueFalseTotal
if index($col, ".") != -1 2 31 33
4967 31 return CORE::join('.', $self->current_source_alias, $col);
4968 }
4969  
4970  
4971 5 ▶sub columns { $_[0]->search_rs(undef, { columns => $_[1] }) }
Subroutine columns: called CC=1 SCAR=0.0
Pod documented
4972  
4973  
4974 3 ▶sub add_columns {
Subroutine add_columns: called CC=1 SCAR=0.0
Pod documented
4975 3 return $_[0]->search_rs(undef, { '+columns' => $_[1] });
4976 }
4977  
4978  
4979 10 ▶sub remove_columns {
Subroutine remove_columns: called CC=1 SCAR=0.0
Pod documented
4980 10 return $_[0]->search_rs(undef, { remove_columns => $_[1] });
4981 }
4982  
4983  
4984 4 ▶sub distinct { $_[0]->search_rs(undef, { distinct => defined $_[1] ? $_[1] : 1 }) }
Subroutine distinct: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
defined $_[1] ? : 2 2 4
4985  
4986  
4987 9 ▶sub group_by { $_[0]->search_rs(undef, { group_by => $_[1] }) }
Subroutine group_by: called CC=1 SCAR=0.0
Pod documented
4988  
4989  
4990 14 ▶sub where {
Subroutine where: called CC=9 SCAR=22.0
Pod documented
4991 14 my $self = shift;
4992  
4993 # no args: return a clone without touching the condition
4994 14 ▶ return $self->search_rs if !@_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 1 13 14
4995  
4996 # a single ref is a full condition structure, passed through verbatim
4997 13 ▶ return $self->search_rs($_[0]) if @_ == 1 && ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 and ref $_[0] 3 10 13
Condition100%3/3
@_ == 1 and ref $_[0]
!ll&&!rl&&r
823
MC/DC100%2/2
@_ == 1 and ref $_[0]
@_ == 1 ref $_[0]
Truth table100%3/3
A and B
A= @_ == 1B= ref $_[0]
ABresult
0X0
100
111
4998  
4999 10 ▶ $self->throw_exception('Odd number of elements in where() condition')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 3 7 10
5000 if @_ % 2;
5001  
5002 7 for my $i (0 .. $#_) {
5003 12 ▶ next if $i % 2;
Branch: 1 branch
BranchTrueFalseTotal
if $i % 2 5 7 12
5004 7 ▶ $self->throw_exception('All keys in condition key/value pairs must be plain scalars')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_[$i] or ref $_[$i] ne "" 2 5 7
Condition66%2/3
not defined $_[$i] or ref $_[$i] ne ""
l!l&&r!l&&!r
025
MC/DC50%1/2
not defined $_[$i] or ref $_[$i] ne ""
not defined $_[$i] ref $_[$i] ne ""
Truth table66%2/3
not(A) or B
A= not defined $_[$i]B= ref $_[$i] ne ""
ABresult
1X1
011
000
5005 if (! defined $_[$i] or ref $_[$i] ne '');
5006 }
5007  
5008 5 return $self->search_rs({ @_ });
5009 }
5010  
5011  
5012 8 ▶sub having {
Subroutine having: called CC=9 SCAR=22.1
Pod documented
5013 8 my $self = shift;
5014  
5015 8 ▶ return $self->search_rs if !@_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 8 8
5016  
5017 8 ▶ return $self->search_rs(undef, { having => $_[0] }) if @_ == 1 && ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 and ref $_[0] 1 7 8
Condition66%2/3
@_ == 1 and ref $_[0]
!ll&&!rl&&r
701
MC/DC50%1/2
@_ == 1 and ref $_[0]
@_ == 1 ref $_[0]
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0]
ABresult
0X0
100
111
5018  
5019 7 ▶ $self->throw_exception('Odd number of elements in having() condition')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 6 7
5020 if @_ % 2;
5021  
5022 6 for my $i (0 .. $#_) {
5023 11 ▶ next if $i % 2;
Branch: 1 branch
BranchTrueFalseTotal
if $i % 2 5 6 11
5024 6 ▶ $self->throw_exception('All keys in condition key/value pairs must be plain scalars')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_[$i] or ref $_[$i] ne "" 1 5 6
Condition66%2/3
not defined $_[$i] or ref $_[$i] ne ""
l!l&&r!l&&!r
015
MC/DC50%1/2
not defined $_[$i] or ref $_[$i] ne ""
not defined $_[$i] ref $_[$i] ne ""
Truth table66%2/3
not(A) or B
A= not defined $_[$i]B= ref $_[$i] ne ""
ABresult
1X1
011
000
5025 if (! defined $_[$i] or ref $_[$i] ne '');
5026 }
5027  
5028 5 return $self->search_rs(undef, { having => { @_ } });
5029 }
5030  
5031  
5032 3 ▶sub offset { $_[0]->search_rs(undef, { offset => $_[1] }) }
Subroutine offset: called CC=1 SCAR=0.0
Pod documented
5033  
5034  
5035 4 ▶sub join { $_[0]->search_rs(undef, { join => $_[1] }) }
Subroutine join: called CC=1 SCAR=0.0
Pod documented
5036  
5037  
5038 8 ▶sub select {
Subroutine select: called CC=3 SCAR=11.0
Pod documented
5039 8 my $self = shift;
5040  
5041 # no args: return a clone without touching the projection
5042 8 ▶ return $self->search_rs if !@_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 2 6 8
5043  
5044 6 my $sel = $_[0];
5045 6 my $as = $_[1];
5046  
5047 6 ▶ return $self->search_rs(undef, {
Branch: 1 branch
BranchTrueFalseTotal
defined $as ? : 2 4 6
5048 select => $sel,
5049 (defined $as ? (as => $as) : ()),
5050 });
5051 }
5052  
5053  
5054 3 ▶sub as {
Subroutine as: called CC=2 SCAR=6.9
Pod documented
5055 3 my ($self, $as) = @_;
5056  
5057 my $sel = $self->{attrs}{select}
5058 3 ▶ or $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
my $sel = $self->{"attrs"}{"select"} or $self->throw_exception("as() needs a preceding select() - chain ->select(\\\@cols)->as(\\\@aliases), or pass both at once: ->select(\\\@cols, \\\@aliases)") 1 2 3
5059 'as() needs a preceding select() - chain ->select(\@cols)->as(\@aliases), '
5060 . 'or pass both at once: ->select(\@cols, \@aliases)'
5061 );
5062  
5063 1 return $self->search_rs(undef, { select => $sel, as => $as });
5064 }
5065  
5066  
5067 4 ▶sub hri {
Subroutine hri: called CC=1 SCAR=0.0
Pod documented
5068 4 $_[0]->search_rs(undef, {
5069 result_class => 'DBIO::ResultClass::HashRefInflator'
5070 })
5071 }
5072  
5073  
5074 14 ▶sub rows { $_[0]->search_rs(undef, { rows => $_[1] }) }
Subroutine rows: called CC=1 SCAR=0.0
Pod documented
5075  
5076  
5077 1 ▶sub limit { $_[0]->rows($_[1]) }
Subroutine limit: called CC=1 SCAR=0.0
Pod documented
5078  
5079  
5080 1 ▶sub has_rows { !! $_[0]->rows(1)->next }
Subroutine has_rows: called CC=1 SCAR=0.0
Pod documented
5081  
5082  
5083 3 ▶sub limited_page {
Subroutine limited_page: called CC=4 SCAR=14.8
Pod documented
5084 3 my $self = shift;
5085 3 ▶ if (@_ == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1) { } 1 2 3
elsif (@_ == 2) { } 2 0 2
5086 1 my $arg = shift;
5087 1 ▶ if (ref $arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg) 1 0 1
5088 1 return $self->page($arg->{page})->rows($arg->{rows});
5089 }
5090 0 return $self->page($arg);
5091 }
5092 elsif (@_ == 2) {
5093 2 return $self->page($_[0])->rows($_[1]);
5094 }
5095 0 $self->throw_exception('Invalid args passed to limited_page');
5096 }
5097  
5098  
5099 2 ▶sub prefetch { $_[0]->search_rs(undef, { prefetch => @_ > 2 ? [@_[1..$#_]] : $_[1] }) }
Subroutine prefetch: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ > 2 ? : 1 1 2
5100  
5101  
5102 9 ▶sub null {
Subroutine null: called CC=1 SCAR=0.0
Pod documented
5103 9 my ($self, @columns) = @_;
5104 9 return $self->_helper_apply_search(undef, @columns);
5105 }
5106  
5107  
5108 2 ▶sub not_null {
Subroutine not_null: called CC=1 SCAR=0.0
Pod documented
5109 2 my ($self, @columns) = @_;
5110 2 return $self->_helper_apply_search({ '!=' => undef }, @columns);
5111 }
5112  
5113  
5114 5 ▶sub like {
Subroutine like: called CC=3 SCAR=11.0
Pod documented
5115 5 my ($self, $columns, $cond) = @_;
5116 5 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if ref $columns and ref $columns ne "ARRAY" 3 2 5
Condition100%3/3
ref $columns and ref $columns ne "ARRAY"
!ll&&!rl&&r
113
MC/DC100%2/2
ref $columns and ref $columns ne "ARRAY"
ref $columns ref $columns ne "ARRAY"
Truth table100%3/3
A and B
A= ref $columnsB= ref $columns ne "ARRAY"
ABresult
0X0
100
111
5117 'like() expects a column name or an ARRAY reference of column names'
5118 ) if ref $columns and ref $columns ne 'ARRAY';
5119 2 return $self->_helper_apply_search({ -like => $cond }, $columns);
5120 }
5121  
5122  
5123 4 ▶sub not_like {
Subroutine not_like: called CC=3 SCAR=11.0
Pod documented
5124 4 my ($self, $columns, $cond) = @_;
5125 4 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if ref $columns and ref $columns ne "ARRAY" 2 2 4
Condition100%3/3
ref $columns and ref $columns ne "ARRAY"
!ll&&!rl&&r
112
MC/DC100%2/2
ref $columns and ref $columns ne "ARRAY"
ref $columns ref $columns ne "ARRAY"
Truth table100%3/3
A and B
A= ref $columnsB= ref $columns ne "ARRAY"
ABresult
0X0
100
111
5126 'not_like() expects a column name or an ARRAY reference of column names'
5127 ) if ref $columns and ref $columns ne 'ARRAY';
5128 2 return $self->_helper_apply_search({ -not_like => $cond }, $columns);
5129 }
5130  
5131 # Shared plumbing for null/not_null/like/not_like: unwrap an optional arrayref
5132 # of columns and chain one search() per column. Stays wordless - the public
5133 # method above is the one that validates its arguments and throws.
5134 15 ▶sub _helper_apply_search {
Subroutine _helper_apply_search: called CC=4 SCAR=13.9
5135 15 my ($self, $cond, @columns) = @_;
5136  
5137 15 ▶ @columns = @{ $columns[0] } if @columns == 1 && ref $columns[0] eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if @columns == 1 and ref $columns[0] eq "ARRAY" 7 8 15
Condition100%3/3
@columns == 1 and ref $columns[0] eq "ARRAY"
!ll&&!rl&&r
177
MC/DC100%2/2
@columns == 1 and ref $columns[0] eq "ARRAY"
@columns == 1 ref $columns[0] eq "ARRAY"
Truth table100%3/3
A and B
A= @columns == 1B= ref $columns[0] eq "ARRAY"
ABresult
0X0
100
111
5138  
5139 15 my $rs = $self;
5140 15 $rs = $rs->search_rs({ $self->_helper_meify($_) => $cond }) for @columns;
5141 15 return $rs;
5142 }
5143  
5144 # A leading '.' means "qualify me with this ResultSet's source alias", so that
5145 # '.title' becomes 'me.title' and stays unambiguous once a join is in play.
5146 20 ▶sub _helper_meify {
Subroutine _helper_meify: called CC=2 SCAR=6.9
5147 20 my ($self, $column) = @_;
5148  
5149 20 ▶ return $self->current_source_alias . $column if $column =~ m/^\./;
Branch: 1 branch
BranchTrueFalseTotal
if $column =~ /^\./ 8 12 20
5150 12 return $column;
5151 }
5152  
5153  
5154 20 ▶sub results_exist {
Subroutine results_exist: called CC=3 SCAR=11.0
Pod documented
5155 20 my ($self, $cond) = @_;
5156  
5157 20 my $storage = $self->result_source->schema->storage;
5158 20 my ($sql, @bind)
5159 = $self->_results_exist_statement($storage, 'results_exist', $cond);
5160  
5161 14 my (undef, $sth) = $storage->_execute_rendered($sql, \@bind);
5162  
5163 14 my $row = $sth->fetchall_arrayref->[0];
5164 14 ▶ return ($row && $row->[0]) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$row && $row->[0] ? : 10 4 14
Condition66%2/3
$row and $row->[0]
!ll&&!rl&&r
0410
MC/DC50%1/2
$row and $row->[0]
$row $row->[0]
Truth table66%2/3
A and B
A= $rowB= $row->[0]
ABresult
0X0
100
111
5165 }
5166  
5167  
5168 20 ▶sub results_exist_async {
Subroutine results_exist_async: called CC=1 SCAR=0.0
Pod documented
5169 20 my ($self, $cond) = @_;
5170  
5171 20 my $storage = $self->result_source->schema->storage;
5172 20 my ($sql, @bind)
5173 = $self->_results_exist_statement($storage, 'results_exist_async', $cond);
5174  
5175 return $self->_rs_run_async('results_exist',
5176 11 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
5177 11 my ($backend, $fc) = @_;
5178  
5179 # The binds of the statement are as_query's, pairs [ \%attrs => $value ].
5180 # A transport's runner takes bare values (DBIO::Storage::Async::_query_async,
5181 # karr k342), so a context or backend that is not a sync storage gets them
5182 # unpacked. The immediate mode runs the statement on the sync storage itself,
5183 # which takes pairs and keeps their column attributes: left as they are.
5184 11 ▶ my @run_bind = $backend->isa('DBIO::Storage::DBI') ? @bind : bare_binds(@bind);
Branch: 1 branch
BranchTrueFalseTotal
$backend->isa('DBIO::Storage::DBI') ? : 1 10 11
5185  
5186 11 ▶ return $backend->_query_async($sql, \@run_bind)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
5187 11 my ($raw_row) = @_;
5188 11 ▶ return ($raw_row && $raw_row->[0]) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$raw_row && $raw_row->[0] ? : 5 6 11
Condition100%3/3
$raw_row and $raw_row->[0]
!ll&&!rl&&r
245
MC/DC100%2/2
$raw_row and $raw_row->[0]
$raw_row $raw_row->[0]
Truth table100%3/3
A and B
A= $raw_rowB= $raw_row->[0]
ABresult
0X0
100
111
5189 11 });
5190 },
5191 1 ▶ sub { $self->results_exist($cond) },
Subroutine __ANON__: called CC=1 SCAR=0.0
5192 13 );
5193 }
5194  
5195  
5196 11 ▶sub results_exist_as_query {
Subroutine results_exist_as_query: called CC=1 SCAR=0.0
Pod documented
5197 11 my ($self, $cond) = @_;
5198  
5199 11 my $storage = $self->result_source->schema->storage;
5200 11 my ($sql, @bind)
5201 = $self->_results_exist_statement($storage, 'results_exist_as_query', $cond);
5202  
5203 5 return \[ "( $sql )", @bind ];
5204 }
5205  
5206 # The complete 1/0 statement all three results_exist* methods run on, plus its
5207 # binds. Core builds the inner subquery and hands it to the storage, which
5208 # renders the whole fragment (ADR 0037 section 2) -- core adds nothing to what
5209 # comes back, and holds no dummy-table knowledge.
5210 51 ▶sub _results_exist_statement {
Subroutine _results_exist_statement: called CC=1 SCAR=0.0
5211 51 my ($self, $storage, $method, $cond) = @_;
5212  
5213 51 $self->_assert_exists_query_supported($storage, $method);
5214  
5215 32 my $reified = $self->search_rs($cond, {
5216 columns => { _results_existence_check => \ '42' }
5217 })->as_query;
5218  
5219 32 my ($inner_sql, @bind) = @{$$reified};
5220  
5221 32 return ($storage->_exists_value_sql($inner_sql), @bind);
5222 }
5223  
5224 # No capability, no EXISTS query -- and never a silent degrade to has_rows:
5225 # the caller asked for the cheap server-side check and would get a different
5226 # query shape without being told, which is the over-promise ADR 0036 refused
5227 # for upsert. Rejecting the *silent* fallback is not rejecting the
5228 # alternative, so the message names it, together with the branch that picks
5229 # it. Thrown before any SQL is built or executed.
5230 51 ▶sub _assert_exists_query_supported {
Subroutine _assert_exists_query_supported: called CC=3 SCAR=11.0
5231 51 my ($self, $storage, $method) = @_;
5232  
5233 51 ▶ return 1
Branch: 1 branch
BranchTrueFalseTotal
if $storage->can("_use_supports_exists_query") and $storage->_use_supports_exists_query 32 19 51
Condition66%2/3
$storage->can("_use_supports_exists_query") and $storage->_use_supports_exists_query
!ll&&!rl&&r
01932
MC/DC50%1/2
$storage->can("_use_supports_exists_query") and $storage->_use_supports_exists_query
$storage->can("_use_supports_exists_query") $storage->_use_supports_exists_query
Truth table66%2/3
A and B
A= $storage->can("_use_supports_exists_query")B= $storage->_use_supports_exists_query
ABresult
0X0
100
111
5234 if $storage->can('_use_supports_exists_query')
5235 and $storage->_use_supports_exists_query;
5236  
5237 19 $self->throw_exception(
5238 "$method(): " . ref($storage) . ' does not declare the '
5239 . 'supports_exists_query capability -- this engine\'s driver has not '
5240 . 'declared that it can render a boolean-valued EXISTS query. Use '
5241 . '$rs->has_rows, which is portable and works everywhere, or branch on the '
5242 . 'capability: '
5243 . '$storage->_use_supports_exists_query ? $rs->results_exist : $rs->has_rows'
5244 );
5245 }
5246  
5247  
5248 5 ▶sub correlate {
Subroutine correlate: called CC=2 SCAR=6.9
Pod documented
5249 5 my ($self, $rel) = @_;
5250  
5251 5 my $source = $self->result_source;
5252  
5253 5 my $fresh_rs = $source->related_source($rel)->resultset;
5254  
5255 # ADR 0045 / karr k281: correlated to a context-bound resultset, it keeps the
5256 # pin (the ->search_rs below propagates it onto the returned clone).
5257 5 ▶ $fresh_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 2 3 5
5258  
5259 return $fresh_rs
5260 ->search_rs(
5261 $source->_resolve_relationship_condition(
5262 rel_name => $rel,
5263 foreign_alias => "${rel}_alias",
5264 self_alias => $self->current_source_alias,
5265 )->{condition},
5266 5 { alias => "${rel}_alias" }
5267 );
5268 }
5269  
5270  
5271 4 ▶sub search_or {
Subroutine search_or: called CC=2 SCAR=6.9
Pod documented
5272 4 my $self = shift;
5273 4 my @others = @{shift @_};
5274  
5275 $self->throw_exception(
5276 'All ResultSets passed to search_or must have the same result_source'
5277 4 ▶ ) if grep { $self->result_source != $_->result_source } @others;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$self->result_source != $_->result_source;} @others 2 2 4
5278  
5279 $self->search_rs({
5280 2 -or => [ map $_->_resolved_attrs->{where}, @others ],
5281 });
5282 }
5283  
5284  
5285 # The canonical operation name IS the method name. It goes to the storage
5286 # rather than a keyword, so there is exactly one call site asking (ADR 0039)
5287 # and the driver can refuse an operation as well as spell it. The old
5288 # driver-name comparison this replaced -- sqlt_type eq 'Oracle' -- reached
5289 # $dbh->{Driver}{Name} through _get_dbh, so it opened a database connection at
5290 # query-build time, on every call, purely to choose a word.
5291 25 ▶sub union { $_[0]->_set_operation('union' => $_[1]) }
Subroutine union: called CC=1 SCAR=0.0
Pod documented
5292 13 ▶sub union_all { $_[0]->_set_operation('union_all' => $_[1]) }
Subroutine union_all: called CC=1 SCAR=0.0
Pod documented
5293 13 ▶sub intersect { $_[0]->_set_operation('intersect' => $_[1]) }
Subroutine intersect: called CC=1 SCAR=0.0
Pod documented
5294 14 ▶sub intersect_all { $_[0]->_set_operation('intersect_all' => $_[1]) }
Subroutine intersect_all: called CC=1 SCAR=0.0
Pod documented
5295  
5296 15 ▶sub except { $_[0]->_set_operation('except' => $_[1]) }
Subroutine except: called CC=1 SCAR=0.0
Pod documented
5297 16 ▶sub except_all { $_[0]->_set_operation('except_all' => $_[1]) }
Subroutine except_all: called CC=1 SCAR=0.0
Pod documented
5298  
5299 # cribbed from perlfaq4
5300 154 ▶sub _compare_arrays {
Subroutine _compare_arrays: called CC=4 SCAR=13.9
5301 154 my ($self, $first, $second) = @_;
5302  
5303 379 ▶ no warnings; # silence spurious -w undef complaints
Subroutine BEGIN: called CC=1 SCAR=0.0
5304 154 ▶ return 0 unless @$first == @$second;
Branch: 1 branch
BranchTrueFalseTotal
unless @$first == @$second 1 153 154
5305 153 ▶ for (my $i = 0; $i < @$first; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$first) 436 144 580
5306 436 ▶ return 0 if $first->[$i] ne $second->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $first->[$i] ne $second->[$i] 9 427 436
5307 }
5308 144 return 1;
5309 }
5310  
5311 96 ▶sub _set_operation {
Subroutine _set_operation: called CC=7 SCAR=19.5
5312 96 my ($self, $op, $other) = @_;
5313  
5314 96 ▶ my @operands = ($self, ref $other eq 'ARRAY' ? @$other : $other);
Branch: 1 branch
BranchTrueFalseTotal
ref $other eq 'ARRAY' ? : 12 84 96
5315  
5316 # ADR 0045 / karr k324: the operands must be bound alike -- all unbound, or
5317 # all to the one context (identity). Asked first of all, before the engine
5318 # and before any operand is rendered, so the refusal depends on nothing the
5319 # driver answers and leaves nothing behind.
5320 {
5321 96 my @bound = map { $_->_async_context } @operands;
5322 96 ▶ my $key = sub { defined $_[0] ? Scalar::Util::refaddr($_[0]) : '' };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 75 130 205
5323 96 my $own = $key->($bound[0]);
5324 96 my @odd = grep { $key->($bound[$_]) ne $own } 1 .. $#bound;
5325  
5326 96 ▶ if (@odd) {
Branch: 1 branch
BranchTrueFalseTotal
if (@odd) 20 76 96
5327 40 ▶ my $says = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
5328 40 ▶ defined $bound[$_[0]] ? "bound to $bound[$_[0]]" : 'unbound';
Branch: 1 branch
BranchTrueFalseTotal
defined $bound[$_[0]] ? : 27 13 40
5329 20 };
5330 $self->throw_exception(
5331 "$op: the operands of a set operation must be bound alike, all "
5332 . 'unbound or all to the same async context -- operand 0 (the caller) is '
5333 20 . CORE::join(', ', $says->(0), map { "operand $_ is " . $says->($_) } @odd)
5334 );
5335 }
5336 }
5337  
5338 # Then, before a single operand is rendered: the engine either spells this
5339 # operation or refuses it (ADR 0039). Doing it here rather than after the
5340 # loop is the contract, not an accident -- a refusing engine must throw at
5341 # query-build time and never produce a fragment that could end up embedded
5342 # in a larger query.
5343 76 my $operation = $self->result_source->schema->storage
5344 ->_set_operation_keyword($op);
5345  
5346 72 my @sql;
5347 my @params;
5348 72 my $as = $self->_resolved_attrs->{as};
5349  
5350 72 for (@operands) {
5351 155 ▶ $self->throw_exception('ResultClass of ResultSets do not match!')
Branch: 1 branch
BranchTrueFalseTotal
unless $self->result_class eq $_->result_class 1 154 155
5352 unless $self->result_class eq $_->result_class;
5353  
5354 154 my $attrs = $_->_resolved_attrs;
5355  
5356 $self->throw_exception('ResultSets do not all have the same selected columns!')
5357 154 ▶ unless $self->_compare_arrays($as, $attrs->{as});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_compare_arrays($as, $attrs->{"as"}) 10 144 154
5358  
5359 144 my ($sql, @bind) = @{${$_->as_query}};
5360 144 $sql =~ s/^\s*\((.*)\)\s*$/$1/;
5361  
5362 144 push @sql, $sql;
5363 144 push @params, @bind;
5364 }
5365  
5366 61 my $query = q<(> . CORE::join(" $operation ", @sql) . q<)>;
5367 61 my $attrs = $self->_resolved_attrs;
5368  
5369 61 my $fresh_rs = $self->result_source->resultset;
5370  
5371 # ADR 0045 / karr k281: the result takes the binding of the operands, which
5372 # are all bound alike (karr k324, checked above); the ->search_rs below
5373 # propagates it onto the returned clone.
5374 61 ▶ $fresh_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 20 41 61
5375  
5376 return $fresh_rs->search_rs(undef, {
5377 alias => $self->current_source_alias,
5378 from => [{
5379 $self->current_source_alias => \[ $query, @params ],
5380 -alias => $self->current_source_alias,
5381 -rsrc => $self->result_source,
5382 }],
5383 columns => $attrs->{as},
5384 61 result_class => $self->result_class,
5385 });
5386 }
5387  
5388  
5389 # --- one_row: safe alternative to first() that exhausts cursor ---
5390 2 ▶sub one_row {
Subroutine one_row: called CC=1 SCAR=0.0
Pod documented
5391 2 my $self = shift;
5392 2 $self->search_rs(shift, { rows => 1 })->next;
5393 }
5394  
5395  
5396 # --- no_columns: clear column selection for custom projections ---
5397 2 ▶sub no_columns { $_[0]->search_rs(undef, { columns => [] }) }
Subroutine no_columns: called CC=1 SCAR=0.0
Pod documented
5398  
5399  
5400 # --- bare: get unsearched ResultSet from a searched one ---
5401 4 ▶sub bare {
Subroutine bare: called CC=2 SCAR=6.9
Pod documented
5402 4 my $self = shift;
5403 4 my $fresh_rs = $self->result_source->resultset;
5404 # ADR 0045 / karr k281: the search conditions and attributes go, the pin of a
5405 # context-bound resultset stays -- it is neither.
5406 4 ▶ $fresh_rs->{_async_context} = $self->{_async_context} if $self->{_async_context};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_context"} 2 2 4
5407 4 return $fresh_rs;
5408 }
5409  
5410  
5411 # --- rand: get random rows ---
5412 8 ▶sub rand {
Subroutine rand: called CC=4 SCAR=13.9
Pod documented
5413 8 my $self = shift;
5414 8 ▶ my $amount = @_ ? shift : 1;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 6 2 8
5415 8 ▶ $self->throw_exception('rand can only return a positive amount of rows')
Branch: 1 branch
BranchTrueFalseTotal
unless $amount > 0 3 5 8
5416 unless $amount > 0;
5417 5 ▶ $self->throw_exception('rand can only return an integer amount of rows')
Branch: 1 branch
BranchTrueFalseTotal
unless $amount == int $amount 1 4 5
5418 unless $amount == int $amount;
5419 4 my $rand_func = $self->result_source->storage->_random_function;
5420 4 $self->search_rs(undef, { rows => $amount, order_by => \$rand_func });
5421 }
5422  
5423  
5424 # --- explain: get query plan for debugging ---
5425 12 ▶sub explain {
Subroutine explain: called CC=1 SCAR=0.0
Pod documented
5426 12 my $self = shift;
5427 12 my $storage = $self->result_source->storage;
5428 12 my ($sql, @bind) = @{${$self->as_query}};
5429 # as_query parenthesises its output for use as a subquery; EXPLAIN wants the
5430 # statement. Stripped for every engine, not only SQLite (upstream's Helper
5431 # did it in the SQLite branch of a DBIx::Introspector dispatch).
5432 12 $sql =~ s/^\s*\((.*)\)\s*$/$1/s;
5433  
5434 # ADR 0040: the storage owns the WHOLE operation, not just the
5435 # spelling. Half this family cannot obtain a plan with one statement --
5436 # Oracle's EXPLAIN PLAN FOR returns no rows and needs a second query, SQL
5437 # Server drives it through a session setting across three round-trips,
5438 # Firebird reads it off the prepared statement -- so there is nothing left
5439 # here to compose. (Sybase ASE cannot be served at all: its plan arrives as
5440 # server messages rather than rows. ADR 0040 section 7.) The bind pairs
5441 # travel as they come:
5442 # [ \%attrs, $value ] is the native format of the statement path.
5443 #
5444 # What that path buys is listed here, and _explain_query's contract requires
5445 # every driver override to keep it: tracing and therefore redact_bind_value,
5446 # dbh_do retry, NoBindVars interpolation, and the read handler rather than
5447 # the master's handle on a replicated storage.
5448 12 return $storage->_explain_query($sql, \@bind);
5449 }
5450  
5451 379 1;
5452  
5453 __END__
« blib/lib/DBIO/SQL/Util.pm ↑ Summary blib/lib/DBIO/Storage/DBI/Cursor.pm »