File Coverage

blib/lib/DBIx/Class/ResultSource/RowParser/Util.pm
Criterion Covered Total %
statement 177 178 99.4
branch 77 80 96.2
condition 38 40 95.0
subroutine 11 11 100.0
pod 0 2 0.0
total 303 311 97.4


line stmt bran cond sub pod time code
1             package # hide from the pauses
2             DBIx::Class::ResultSource::RowParser::Util;
3              
4 312     312   2008 use strict;
  312         725  
  312         9121  
5 312     312   1637 use warnings;
  312         694  
  312         8508  
6              
7 312     312   1756 use DBIx::Class::_Util qw( perlstring dump_value );
  312         736  
  312         20703  
8              
9 312     312   2086 use constant HAS_DOR => ( ( DBIx::Class::_ENV_::PERL_VERSION < 5.010 ) ? 0 : 1 );
  312         759  
  312         23066  
10              
11 312     312   2059 use base 'Exporter';
  312         759  
  312         744378  
12             our @EXPORT_OK = qw(
13             assemble_simple_parser
14             assemble_collapsing_parser
15             );
16              
17             # working title - we are hoping to extract this eventually...
18             our $null_branch_class = 'DBIx::ResultParser::RelatedNullBranch';
19              
20             sub __wrap_in_strictured_scope {
21 242     242   2869 "sub { use strict; use warnings; use warnings FATAL => 'uninitialized';\n$_[0]\n }"
22             }
23              
24             sub assemble_simple_parser {
25             #my ($args) = @_;
26              
27             # the non-collapsing assembler is easy
28             # FIXME SUBOPTIMAL there could be a yet faster way to do things here, but
29             # need to try an actual implementation and benchmark it:
30             #
31             # First setup the nested data structure you want for each row
32             # Then call bind_col() to alias the row fields into the right place in
33             # the data structure, then to fetch the data do:
34             # push @rows, dclone($row_data_struct) while ($sth->fetchrow);
35             #
36              
37 68     68 0 330 __wrap_in_strictured_scope( sprintf
38             '$_ = %s for @{$_[0]}',
39             __visit_infmap_simple( $_[0] )
40             );
41             }
42              
43             # the simple non-collapsing nested structure recursor
44             sub __visit_infmap_simple {
45 198     198   449 my $args = shift;
46              
47 198         1727 my $my_cols = {};
48 198         361 my $rel_cols;
49 198         369 for (keys %{$args->{val_index}}) {
  198         837  
50 1111 100       3405 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
51 550         2005 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
52             }
53             else {
54 561         1209 $my_cols->{$_} = $args->{val_index}{$_};
55             }
56             }
57              
58 198         737 my @relperl;
59 198         1125 for my $rel (sort keys %$rel_cols) {
60              
61             my $rel_struct = __visit_infmap_simple({ %$args,
62 130         1020 val_index => $rel_cols->{$rel},
63             });
64              
65 130 100       650 if (keys %$my_cols) {
66              
67             my $branch_null_checks = join ' && ', map
68 498         1447 { "( ! defined \$_->[$_] )" }
69 104         226 sort { $a <=> $b } values %{$rel_cols->{$rel}}
  847         1410  
  104         567  
70             ;
71              
72 104 100       412 if ($args->{prune_null_branches}) {
73 90         420 $rel_struct = sprintf ( '( (%s) ? undef : %s )',
74             $branch_null_checks,
75             $rel_struct,
76             );
77             }
78             else {
79 14         49 $rel_struct = sprintf ( '( (%s) ? bless( (%s), %s ) : %s )',
80             $branch_null_checks,
81             $rel_struct,
82             perlstring($null_branch_class),
83             $rel_struct,
84             );
85             }
86             }
87              
88 130         447 push @relperl, sprintf '( %s => %s )',
89             perlstring($rel),
90             $rel_struct,
91             ;
92              
93             }
94              
95 198         411 my $me_struct;
96 198 100       1065 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
97              
98 198 100       3573 if ($args->{hri_style}) {
99 36 100       248 $me_struct =~ s/^ \s* \{ | \} \s* $//gx
100             if $me_struct;
101              
102 36   66     283 return sprintf '{ %s }', join (', ', $me_struct||(), @relperl);
103             }
104             else {
105 162 100 100     1905 return sprintf '[%s]', join (',',
106             $me_struct || 'undef',
107             @relperl ? sprintf ('{ %s }', join (',', @relperl)) : (),
108             );
109             }
110             }
111              
112             sub assemble_collapsing_parser {
113 174     174 0 497 my $args = shift;
114              
115 174         472 my ($top_node_key, $top_node_key_assembler, $variant_idcols);
116              
117 174 100       376 if (scalar @{$args->{collapse_map}{-identifying_columns}}) {
  174 50       782  
118             $top_node_key = join ('', map
119 166         871 { "{ \$cur_row_ids{$_} }" }
120 159         386 @{$args->{collapse_map}{-identifying_columns}}
  159         581  
121             );
122              
123 159         473 $top_node_key_assembler = '';
124             }
125 15         96 elsif( my @variants = @{$args->{collapse_map}{-identifying_columns_variants}} ) {
126              
127 15         55 my @path_parts = map { sprintf
128             "( ( defined \$cur_row_data->[%d] ) && (join qq(\xFF), '', %s, '') )",
129             $_->[0], # checking just first is enough - one ID defined, all defined
130 23         79 ( join ', ', map { $variant_idcols->{$_} = 1; " \$cur_row_ids{$_} " } @$_ ),
  23         74  
  23         212  
131             } @variants;
132              
133 15         43 my $virtual_column_idx = (scalar keys %{$args->{val_index}} ) + 1;
  15         65  
134              
135 15         64 $top_node_key = "{ \$cur_row_ids{$virtual_column_idx} }";
136              
137 15         104 $top_node_key_assembler = sprintf "( \$cur_row_ids{%d} = (%s) ),",
138             $virtual_column_idx,
139             "\n" . join( "\n or\n", @path_parts, qq{"\0\$rows_pos\0"} )
140             ;
141              
142             $args->{collapse_map} = {
143 15         46 %{$args->{collapse_map}},
  15         122  
144             -custom_node_key => $top_node_key,
145             };
146             }
147             else {
148             DBIx::Class::Exception->throw(
149             'Unexpected collapse map contents: ' . dump_value $args->{collapse_map},
150 0         0 1,
151             )
152             }
153              
154 174         773 my ($data_assemblers, $stats) = __visit_infmap_collapse ($args);
155              
156             # variants do not necessarily overlap with true idcols
157 174         467 my @row_ids = sort { $a <=> $b } keys %{ {
  542         1401  
158 174 100       993 %{ $variant_idcols || {} },
159 174         387 %{ $stats->{idcols_seen} },
  174         1367  
160             } };
161              
162             my $row_id_defs = sprintf "( \@cur_row_ids{( %s )} = (\n%s\n ) ),",
163             join (', ', @row_ids ),
164             # in case we prune - we will never hit undefs/NULLs as pigeon-hole-criteria
165             ( $args->{prune_null_branches}
166             ? sprintf( '@{$cur_row_data}[( %s )]', join ', ', @row_ids )
167             : join (",\n", map {
168 174 100       1595 $stats->{nullchecks}{mandatory}{$_}
169             ? qq!( \$cur_row_data->[$_] )!
170 38 100       105 : do {
171 29         61 my $quoted_null_val = qq("\0NULL\xFF\${rows_pos}\xFF${_}\0");
172 29         102 HAS_DOR
173             ? qq!( \$cur_row_data->[$_] // $quoted_null_val )!
174             : qq!( defined(\$cur_row_data->[$_]) ? \$cur_row_data->[$_] : $quoted_null_val )!
175             }
176             } @row_ids)
177             )
178             ;
179              
180 174         492 my $null_checks = '';
181              
182 174         389 for my $c ( sort { $a <=> $b } keys %{$stats->{nullchecks}{mandatory}} ) {
  7         25  
  174         785  
183 166         709 $null_checks .= sprintf <<'EOS', $c
184             ( defined( $cur_row_data->[%1$s] ) or $_[3]->{%1$s} = 1 ),
185              
186             EOS
187             }
188              
189 174 100       445 for my $set ( @{ $stats->{nullchecks}{from_first_encounter} || [] } ) {
  174         1103  
190 47         91 my @sub_checks;
191              
192 47         217 for my $i (0 .. $#$set - 1) {
193              
194             push @sub_checks, sprintf
195             '( not defined $cur_row_data->[%1$s] ) ? ( %2$s or ( $_[3]->{%1$s} = 1 ) )',
196             $set->[$i],
197             join( ' and ', map
198 104         329 { "( not defined \$cur_row_data->[$set->[$_]] )" }
  209         808  
199             ( $i+1 .. $#$set )
200             ),
201             ;
202             }
203              
204 47         131 $null_checks .= "(\n @{[ join qq(\n: ), @sub_checks, '()' ]} \n),\n";
  47         322  
205             }
206              
207 174 100       460 for my $set ( @{ $stats->{nullchecks}{all_or_nothing} || [] } ) {
  174         980  
208              
209             $null_checks .= sprintf "(\n( %s )\n or\n(\n%s\n)\n),\n",
210             join ( ' and ', map
211 156         620 { "( not defined \$cur_row_data->[$_] )" }
212 105         313 sort { $a <=> $b } keys %$set
213             ),
214             join ( ",\n", map
215 156         722 { "( defined(\$cur_row_data->[$_]) or \$_[3]->{$_} = 1 )" }
216 68         290 sort { $a <=> $b } keys %$set
  105         274  
217             ),
218             ;
219             }
220              
221             # If any of the above generators produced something, we need to add the
222             # final "if seen any violations - croak" part
223             # Do not throw from within the string eval itself as it does not have
224             # the necessary metadata to construct a nice exception text. As a bonus
225             # we get to entirely avoid https://github.com/Test-More/Test2/issues/16
226             # and https://rt.perl.org/Public/Bug/Display.html?id=127774
227              
228 174 100       732 $null_checks .= <<'EOS' if $null_checks;
229              
230             ( keys %{$_[3]} and (
231             ( @{$_[2]} = $cur_row_data ),
232             ( $result_pos = 0 ),
233             last
234             ) ),
235             EOS
236              
237              
238 174         2265 my $parser_src = sprintf (<<'EOS', $null_checks, $row_id_defs, $top_node_key_assembler, $top_node_key, join( "\n", @$data_assemblers ) );
239             ### BEGIN LITERAL STRING EVAL
240             my $rows_pos = 0;
241             my ($result_pos, @collapse_idx, $cur_row_data, %%cur_row_ids );
242              
243             # this loop is a bit arcane - the rationale is that the passed in
244             # $_[0] will either have only one row (->next) or will have all
245             # rows already pulled in (->all and/or unordered). Given that the
246             # result can be rather large - we reuse the same already allocated
247             # array, since the collapsed prefetch is smaller by definition.
248             # At the end we cut the leftovers away and move on.
249             while ($cur_row_data = (
250             (
251             $rows_pos >= 0
252             and
253             (
254             $_[0][$rows_pos++]
255             or
256             # It may be tempting to drop the -1 and undef $rows_pos instead
257             # thus saving the >= comparison above as well
258             # However NULL-handlers and underdefined root markers both use
259             # $rows_pos as a last-resort-uniqueness marker (it either is
260             # monotonically increasing while we parse ->all, or is set at
261             # a steady -1 when we are dealing with a single root node). For
262             # the time being the complication of changing all callsites seems
263             # overkill, for what is going to be a very modest saving of ops
264             ( ($rows_pos = -1), undef )
265             )
266             )
267             or
268             ( $_[1] and $_[1]->() )
269             ) ) {
270              
271             # column_info metadata historically hasn't been too reliable.
272             # We need to start fixing this somehow (the collapse resolver
273             # can't work without it). Add explicit checks for several cases
274             # of "unexpected NULL", based on the metadata returned by
275             # __visit_infmap_collapse
276             #
277             # FIXME - this is a temporary kludge that reduces performance
278             # It is however necessary for the time being, until way into the
279             # future when the extra errors clear out all invalid metadata
280             %s
281              
282             # due to left joins some of the ids may be NULL/undef, and
283             # won't play well when used as hash lookups
284             # we also need to differentiate NULLs on per-row/per-col basis
285             # (otherwise folding of optional 1:1s will be greatly confused
286             #
287             # the undef checks may or may not be there depending on whether
288             # we prune or not
289             %s
290              
291             # in the case of an underdefined root - calculate the virtual id (otherwise no code at all)
292             %s
293              
294             # if we were supplied a coderef - we are collapsing lazily (the set
295             # is ordered properly)
296             # as long as we have a result already and the next result is new we
297             # return the pre-read data and bail
298             ( $_[1] and $result_pos and ! $collapse_idx[0]%s and (unshift @{$_[2]}, $cur_row_data) and last ),
299              
300             # the rel assemblers
301             %s
302              
303             }
304              
305             $#{$_[0]} = $result_pos - 1; # truncate the passed in array to where we filled it with results
306             ### END LITERAL STRING EVAL
307             EOS
308              
309 174         763 __wrap_in_strictured_scope($parser_src);
310             }
311              
312              
313             # the collapsing nested structure recursor
314             sub __visit_infmap_collapse {
315 541     541   1044 my $args = {%{ shift() }};
  541         3061  
316              
317 541   100     1300 my $cur_node_idx = ${ $args->{-node_idx_counter} ||= \do { my $x = 0} }++;
  541         1910  
  174         866  
318              
319 541   100     2083 $args->{-mandatory_ids} ||= {};
320 541   100     1832 $args->{-seen_ids} ||= {};
321 541   100     1937 $args->{-all_or_nothing_sets} ||= [];
322 541   100     1939 $args->{-null_from} ||= [];
323              
324             $args->{-seen_ids}{$_} = 1
325 541         892 for @{$args->{collapse_map}->{-identifying_columns}};
  541         2287  
326              
327 509         1430 my $node_specific_ids = { map { $_ => 1 } grep
328 1085         2834 { ! $args->{-parent_ids}{$_} }
329 541         1060 @{$args->{collapse_map}->{-identifying_columns}}
  541         1341  
330             };
331              
332 541 100 100     3276 if (not ( $args->{-chain_is_optional} ||= $args->{collapse_map}{-is_optional} ) ) {
    100          
333             $args->{-mandatory_ids}{$_} = 1
334 212         474 for @{$args->{collapse_map}->{-identifying_columns}};
  212         884  
335             }
336             elsif ( keys %$node_specific_ids > 1 ) {
337 68         154 push @{$args->{-all_or_nothing_sets}}, $node_specific_ids;
  68         202  
338             }
339              
340 541         1495 my ($my_cols, $rel_cols) = {};
341 541         968 for ( keys %{$args->{val_index}} ) {
  541         2022  
342 3511 100       9680 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
343 1824         5601 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
344             }
345             else {
346 1687         3402 $my_cols->{$_} = $args->{val_index}{$_};
347             }
348             }
349              
350              
351 541 100       1741 if ($args->{hri_style}) {
352 177         531 delete $my_cols->{$_} for grep { $rel_cols->{$_} } keys %$my_cols;
  543         1011  
353             }
354              
355 541         988 my $me_struct;
356 541 100       2137 $me_struct = __result_struct_to_source($my_cols, 1) if keys %$my_cols;
357              
358             $me_struct = sprintf( '[ %s ]', $me_struct||'' )
359 541 100 100     2753 unless $args->{hri_style};
360              
361              
362             my $node_key = $args->{collapse_map}->{-custom_node_key} || join ('', map
363             { "{ \$cur_row_ids{$_} }" }
364 541   66     1782 @{$args->{collapse_map}->{-identifying_columns}}
365             );
366 541         2096 my $node_idx_slot = sprintf '$collapse_idx[%d]%s', $cur_node_idx, $node_key;
367              
368              
369 541         1072 my @src;
370              
371 541 100       1348 if ($cur_node_idx == 0) {
372 174   100     1109 push @src, sprintf( '( %s %s $_[0][$result_pos++] = %s ),',
373             $node_idx_slot,
374             (HAS_DOR ? '//=' : '||='),
375             $me_struct || '{}',
376             );
377             }
378             else {
379             my $parent_attach_slot = sprintf( '$collapse_idx[%d]%s%s{%s}',
380 367         1643 @{$args}{qw/-parent_node_idx -parent_node_key/},
381             $args->{hri_style} ? '' : '[1]',
382 367 100       723 perlstring($args->{-node_rel_name}),
383             );
384              
385 367 100       1118 if ($args->{collapse_map}->{-is_single}) {
386 151   100     924 push @src, sprintf ( '( %s %s %s = %s ),',
387             $parent_attach_slot,
388             (HAS_DOR ? '//=' : '||='),
389             $node_idx_slot,
390             $me_struct || '{}',
391             );
392             }
393             else {
394 216   100     1311 push @src, sprintf('( (! %s) and push @{%s}, %s = %s ),',
395             $node_idx_slot,
396             $parent_attach_slot,
397             $node_idx_slot,
398             $me_struct || '{}',
399             );
400             }
401             }
402              
403 541         1068 my $known_present_ids = { map { $_ => 1 } @{$args->{collapse_map}{-identifying_columns}} };
  1085         2679  
  541         1332  
404 541         1182 my $rel_src;
405              
406 541         1921 for my $rel (sort keys %$rel_cols) {
407              
408 367         859 my $relinfo = $args->{collapse_map}{$rel};
409              
410             ($rel_src) = __visit_infmap_collapse({ %$args,
411             val_index => $rel_cols->{$rel},
412             collapse_map => $relinfo,
413             -parent_node_idx => $cur_node_idx,
414             -parent_node_key => $node_key,
415 367 100       2541 -parent_id_path => [ @{$args->{-parent_id_path}||[]}, sort { $a <=> $b } keys %$node_specific_ids ],
  56         252  
416 734         4723 -parent_ids => { map { %$_ } $node_specific_ids, $args->{-parent_ids}||{} },
417 367   100     1736 -node_rel_name => $rel,
418             });
419              
420 367         1827 my $rel_src_pos = $#src + 1;
421 367         945 push @src, @$rel_src;
422              
423 367 100       1116 if (
424             $relinfo->{-is_optional}
425             ) {
426              
427             my ($first_distinct_child_idcol) = grep
428 693         1683 { ! $known_present_ids->{$_} }
429 253         518 @{$relinfo->{-identifying_columns}}
  253         648  
430             ;
431              
432             DBIx::Class::Exception->throw(
433             "An optional node *without* a distinct identifying set shouldn't be possible: " . dump_value $args->{collapse_map},
434 253 50       800 1,
435             ) unless defined $first_distinct_child_idcol;
436              
437 253 100       679 if ($args->{prune_null_branches}) {
438              
439             # start of wrap of the entire chain in a conditional
440             splice @src, $rel_src_pos, 0, sprintf "( ( ! defined %s )\n ? %s%s{%s} = %s\n : do {",
441             "\$cur_row_data->[$first_distinct_child_idcol]",
442             $node_idx_slot,
443             $args->{hri_style} ? '' : '[1]',
444             perlstring($rel),
445 230 100 100     1316 ($args->{hri_style} && $relinfo->{-is_single}) ? 'undef' : '[]'
    100          
446             ;
447              
448             # end of wrap
449 230         831 push @src, '} ),'
450             }
451             else {
452              
453 23         95 splice @src, $rel_src_pos + 1, 0, sprintf ( '( (defined %s) or bless (%s[1]{%s}, %s) ),',
454             "\$cur_row_data->[$first_distinct_child_idcol]",
455             $node_idx_slot,
456             perlstring($rel),
457             perlstring($null_branch_class),
458             );
459             }
460             }
461             }
462              
463 541 100 100     1815 if (
      100        
464              
465             # calculation only valid for leaf nodes
466             ! values %$rel_cols
467              
468             and
469              
470             # child of underdefined path doesn't leave us anything to test
471 217 100       1353 @{$args->{-parent_id_path} || []}
472              
473             and
474              
475             (my @nullable_portion = grep
476 517         1877 { ! $args->{-mandatory_ids}{$_} }
477             (
478 194         863 @{$args->{-parent_id_path}},
479 47         157 sort { $a <=> $b } keys %$node_specific_ids
480             )
481             ) > 1
482             ) {
483             # there may be 1:1 overlap with a specific all_or_nothing
484 47         171 push @{$args->{-null_from}}, \@nullable_portion unless grep
485             {
486 65         154 my $a_o_n_set = $_;
487              
488             keys %$a_o_n_set == @nullable_portion
489             and
490 65 100       313 ! grep { ! $a_o_n_set->{$_} } @nullable_portion
  88         375  
491             }
492 90 50       217 @{ $args->{-all_or_nothing_sets} || [] }
  90 100       427  
493             ;
494             }
495              
496             return (
497             \@src,
498             ( $cur_node_idx != 0 ) ? () : {
499             idcols_seen => $args->{-seen_ids},
500             nullchecks => {
501 174         771 ( keys %{$args->{-mandatory_ids} }
502             ? ( mandatory => $args->{-mandatory_ids} )
503             : ()
504             ),
505 174         615 ( @{$args->{-all_or_nothing_sets}}
506             ? ( all_or_nothing => $args->{-all_or_nothing_sets} )
507             : ()
508             ),
509 174         1984 ( @{$args->{-null_from}}
510             ? ( from_first_encounter => $args->{-null_from} )
511 541 100       3248 : ()
    100          
    100          
    100          
512             ),
513             },
514             },
515             );
516             }
517              
518             sub __result_struct_to_source {
519 656     656   1626 my ($data, $is_collapsing) = @_;
520              
521             sprintf( '{ %s }',
522             join (', ', map {
523 2239 100       6058 sprintf ( "%s => %s",
524             perlstring($_),
525             $is_collapsing
526             ? "\$cur_row_data->[$data->{$_}]"
527             : "\$_->[ $data->{$_} ]"
528             )
529 656         1305 } sort keys %{$data}
  656         2581  
530             )
531             );
532             }
533              
534             1;