File Coverage

blib/lib/DBIx/Class/ResultSource/RowParser/Util.pm
Criterion Covered Total %
statement 132 133 99.2
branch 50 54 92.5
condition 19 22 86.3
subroutine 13 13 100.0
pod 0 2 0.0
total 214 224 95.5


line stmt bran cond sub pod time code
1             package # hide from the pauses
2             DBIx::Class::ResultSource::RowParser::Util;
3              
4 379     379   3368 use strict;
  379         1251  
  379         11189  
5 379     379   2268 use warnings;
  379         1205  
  379         10091  
6              
7 379     379   2258 use List::Util 'first';
  379         1255  
  379         21435  
8 379     379   2968 use DBIx::Class::_Util 'perlstring';
  379         1241  
  379         25631  
9              
10 379 50   379   3157 use constant HAS_DOR => ( $] < 5.010 ? 0 : 1 );
  379         1351  
  379         34795  
11              
12 379     379   3506 use base 'Exporter';
  379         1278  
  379         805395  
13             our @EXPORT_OK = qw(
14             assemble_simple_parser
15             assemble_collapsing_parser
16             );
17              
18             # working title - we are hoping to extract this eventually...
19             our $null_branch_class = 'DBIx::ResultParser::RelatedNullBranch';
20              
21             sub __wrap_in_strictured_scope {
22 233     233   2514 " { use strict; use warnings; use warnings FATAL => 'uninitialized';\n$_[0]\n }"
23             }
24              
25             sub assemble_simple_parser {
26             #my ($args) = @_;
27              
28             # the non-collapsing assembler is easy
29             # FIXME SUBOPTIMAL there could be a yet faster way to do things here, but
30             # need to try an actual implementation and benchmark it:
31             #
32             # <timbunce_> First setup the nested data structure you want for each row
33             # Then call bind_col() to alias the row fields into the right place in
34             # the data structure, then to fetch the data do:
35             # push @rows, dclone($row_data_struct) while ($sth->fetchrow);
36             #
37 68     68 0 293 my $parser_src = sprintf('$_ = %s for @{$_[0]}', __visit_infmap_simple($_[0]) );
38              
39             # change the quoted placeholders to unquoted alias-references
40 68         609 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$_->[$1]"/gex;
  1198         3657  
41              
42 68         304 __wrap_in_strictured_scope($parser_src);
43             }
44              
45             # the simple non-collapsing nested structure recursor
46             sub __visit_infmap_simple {
47 198     198   371 my $args = shift;
48              
49 198         347 my $my_cols = {};
50 198         303 my $rel_cols;
51 198         345 for (keys %{$args->{val_index}}) {
  198         755  
52 1111 100       2881 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
53 550         1620 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
54             }
55             else {
56 561         1066 $my_cols->{$_} = $args->{val_index}{$_};
57             }
58             }
59              
60 198         418 my @relperl;
61 198         608 for my $rel (sort keys %$rel_cols) {
62              
63             my $rel_struct = __visit_infmap_simple({ %$args,
64 130         788 val_index => $rel_cols->{$rel},
65             });
66              
67 130 100       609 if (keys %$my_cols) {
68              
69             my $branch_null_checks = join ' && ', map
70 498         1237 { "( ! defined '\xFF__VALPOS__${_}__\xFF' )" }
71 104         233 sort { $a <=> $b } values %{$rel_cols->{$rel}}
  856         1187  
  104         465  
72             ;
73              
74 104 100       363 if ($args->{prune_null_branches}) {
75 90         389 $rel_struct = sprintf ( '( (%s) ? undef : %s )',
76             $branch_null_checks,
77             $rel_struct,
78             );
79             }
80             else {
81 14         46 $rel_struct = sprintf ( '( (%s) ? bless( (%s), %s ) : %s )',
82             $branch_null_checks,
83             $rel_struct,
84             perlstring($null_branch_class),
85             $rel_struct,
86             );
87             }
88             }
89              
90 130         416 push @relperl, sprintf '( %s => %s )',
91             perlstring($rel),
92             $rel_struct,
93             ;
94              
95             }
96              
97 198         404 my $me_struct;
98 198 100       713 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
99              
100 198 100       607 if ($args->{hri_style}) {
101 36 100       274 $me_struct =~ s/^ \s* \{ | \} \s* $//gx
102             if $me_struct;
103              
104 36   66     301 return sprintf '{ %s }', join (', ', $me_struct||(), @relperl);
105             }
106             else {
107 162 100 100     1780 return sprintf '[%s]', join (',',
108             $me_struct || 'undef',
109             @relperl ? sprintf ('{ %s }', join (',', @relperl)) : (),
110             );
111             }
112             }
113              
114             sub assemble_collapsing_parser {
115 165     165 0 428 my $args = shift;
116              
117             # it may get unset further down
118 165         607 my $no_rowid_container = $args->{prune_null_branches};
119              
120 165         388 my ($top_node_key, $top_node_key_assembler);
121              
122 165 100       330 if (scalar @{$args->{collapse_map}{-identifying_columns}}) {
  165 50       642  
123             $top_node_key = join ('', map
124 159         789 { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
125 152         353 @{$args->{collapse_map}{-identifying_columns}}
  152         519  
126             );
127             }
128 13         77 elsif( my @variants = @{$args->{collapse_map}{-identifying_columns_variants}} ) {
129              
130 13         38 my @path_parts = map { sprintf
131             "( ( defined '\xFF__VALPOS__%d__\xFF' ) && (join qq(\xFF), '', %s, '') )",
132             $_->[0], # checking just first is enough - one ID defined, all defined
133 20         64 ( join ', ', map { "'\xFF__VALPOS__${_}__\xFF'" } @$_ ),
  20         161  
134             } @variants;
135              
136 13         31 my $virtual_column_idx = (scalar keys %{$args->{val_index}} ) + 1;
  13         47  
137              
138 13         43 $top_node_key = "{'\xFF__IDVALPOS__${virtual_column_idx}__\xFF'}";
139              
140 13         94 $top_node_key_assembler = sprintf "'\xFF__IDVALPOS__%d__\xFF' = (%s);",
141             $virtual_column_idx,
142             "\n" . join( "\n or\n", @path_parts, qq{"\0\$rows_pos\0"} )
143             ;
144              
145             $args->{collapse_map} = {
146 13         27 %{$args->{collapse_map}},
  13         74  
147             -custom_node_key => $top_node_key,
148             };
149              
150 13         38 $no_rowid_container = 0;
151             }
152             else {
153 0         0 die('Unexpected collapse map contents');
154             }
155              
156 165         900 my ($data_assemblers, $stats) = __visit_infmap_collapse ($args);
157              
158             my @idcol_args = $no_rowid_container ? ('', '') : (
159             ', %cur_row_ids', # only declare the variable if we'll use it
160             join ("\n", map {
161 66         147 my $quoted_null_val = qq( "\0NULL\xFF\${rows_pos}\xFF${_}\0" );
162             qq(\$cur_row_ids{$_} = ) . (
163             # in case we prune - we will never hit these undefs
164 66 100       309 $args->{prune_null_branches} ? qq( \$cur_row_data->[$_]; )
165             : HAS_DOR ? qq( \$cur_row_data->[$_] // $quoted_null_val; )
166             : qq( defined(\$cur_row_data->[$_]) ? \$cur_row_data->[$_] : $quoted_null_val; )
167             )
168 165 100       803 } sort { $a <=> $b } keys %{ $stats->{idcols_seen} } ),
  79         156  
  18         91  
169             );
170              
171 165 50 100     931 my $parser_src = sprintf (<<'EOS', @idcol_args, $top_node_key_assembler||'', $top_node_key, join( "\n", @{$data_assemblers||[]} ) );
  165         2342  
172             ### BEGIN LITERAL STRING EVAL
173             my $rows_pos = 0;
174             my ($result_pos, @collapse_idx, $cur_row_data %1$s);
175              
176             # this loop is a bit arcane - the rationale is that the passed in
177             # $_[0] will either have only one row (->next) or will have all
178             # rows already pulled in (->all and/or unordered). Given that the
179             # result can be rather large - we reuse the same already allocated
180             # array, since the collapsed prefetch is smaller by definition.
181             # At the end we cut the leftovers away and move on.
182             while ($cur_row_data = (
183             ( $rows_pos >= 0 and $_[0][$rows_pos++] )
184             or
185             ( $_[1] and $rows_pos = -1 and $_[1]->() )
186             ) ) {
187              
188             # this code exists only when we are using a cur_row_ids
189             # furthermore the undef checks may or may not be there
190             # depending on whether we prune or not
191             #
192             # due to left joins some of the ids may be NULL/undef, and
193             # won't play well when used as hash lookups
194             # we also need to differentiate NULLs on per-row/per-col basis
195             # (otherwise folding of optional 1:1s will be greatly confused
196             %2$s
197              
198             # in the case of an underdefined root - calculate the virtual id (otherwise no code at all)
199             %3$s
200              
201             # if we were supplied a coderef - we are collapsing lazily (the set
202             # is ordered properly)
203             # as long as we have a result already and the next result is new we
204             # return the pre-read data and bail
205             $_[1] and $result_pos and ! $collapse_idx[0]%4$s and (unshift @{$_[2]}, $cur_row_data) and last;
206              
207             # the rel assemblers
208             %5$s
209              
210             }
211              
212             $#{$_[0]} = $result_pos - 1; # truncate the passed in array to where we filled it with results
213             ### END LITERAL STRING EVAL
214             EOS
215              
216             # !!! note - different var than the one above
217             # change the quoted placeholders to unquoted alias-references
218 165         2274 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$cur_row_data->[$1]"/gex;
  1915         7208  
219 165         1256 $parser_src =~ s/
220             \' \xFF__IDVALPOS__(\d+)__\xFF \'
221             /
222 2472 100       9023 $no_rowid_container ? "\$cur_row_data->[$1]" : "\$cur_row_ids{$1}"
223             /gex;
224              
225 165         820 __wrap_in_strictured_scope($parser_src);
226             }
227              
228              
229             # the collapsing nested structure recursor
230             sub __visit_infmap_collapse {
231 489     489   927 my $args = {%{ shift() }};
  489         2232  
232              
233 489   100     1025 my $cur_node_idx = ${ $args->{-node_idx_counter} ||= \do { my $x = 0} }++;
  489         1651  
  165         795  
234              
235 489         1229 my ($my_cols, $rel_cols) = {};
236 489         879 for ( keys %{$args->{val_index}} ) {
  489         1713  
237 3409 100       9048 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
238 1757         4966 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
239             }
240             else {
241 1652         3178 $my_cols->{$_} = $args->{val_index}{$_};
242             }
243             }
244              
245              
246 489 100       1522 if ($args->{hri_style}) {
247 154         462 delete $my_cols->{$_} for grep { $rel_cols->{$_} } keys %$my_cols;
  527         1000  
248             }
249              
250 489         969 my $me_struct;
251 489 100       1832 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
252              
253             $me_struct = sprintf( '[ %s ]', $me_struct||'' )
254 489 100 100     2323 unless $args->{hri_style};
255              
256              
257             my $node_key = $args->{collapse_map}->{-custom_node_key} || join ('', map
258             { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
259 489   66     1606 @{$args->{collapse_map}->{-identifying_columns}}
260             );
261 489         1644 my $node_idx_slot = sprintf '$collapse_idx[%d]%s', $cur_node_idx, $node_key;
262              
263              
264 489         856 my @src;
265              
266 489 100       1280 if ($cur_node_idx == 0) {
267 165   100     993 push @src, sprintf( '%s %s $_[0][$result_pos++] = %s;',
268             $node_idx_slot,
269             (HAS_DOR ? '//=' : '||='),
270             $me_struct || '{}',
271             );
272             }
273             else {
274             my $parent_attach_slot = sprintf( '$collapse_idx[%d]%s%s{%s}',
275 324         1418 @{$args}{qw/-parent_node_idx -parent_node_key/},
276             $args->{hri_style} ? '' : '[1]',
277 324 100       698 perlstring($args->{-node_rel_name}),
278             );
279              
280 324 100       1061 if ($args->{collapse_map}->{-is_single}) {
281 122 100       735 push @src, sprintf ( '%s %s %s%s;',
282             $parent_attach_slot,
283             (HAS_DOR ? '//=' : '||='),
284             $node_idx_slot,
285             $me_struct ? " = $me_struct" : '',
286             );
287             }
288             else {
289 202 50       1459 push @src, sprintf('(! %s) and push @{%s}, %s%s;',
290             $node_idx_slot,
291             $parent_attach_slot,
292             $node_idx_slot,
293             $me_struct ? " = $me_struct" : '',
294             );
295             }
296             }
297              
298 489         928 my $known_present_ids = { map { $_ => 1 } @{$args->{collapse_map}{-identifying_columns}} };
  925         2193  
  489         1124  
299 489         1138 my ($stats, $rel_src);
300              
301 489         1660 for my $rel (sort keys %$rel_cols) {
302              
303 324         767 my $relinfo = $args->{collapse_map}{$rel};
304              
305             ($rel_src, $stats->{$rel}) = __visit_infmap_collapse({ %$args,
306 324         3284 val_index => $rel_cols->{$rel},
307             collapse_map => $relinfo,
308             -parent_node_idx => $cur_node_idx,
309             -parent_node_key => $node_key,
310             -node_rel_name => $rel,
311             });
312              
313 324         1240 my $rel_src_pos = $#src + 1;
314 324         852 push @src, @$rel_src;
315              
316 324 100 66     1650 if (
317             $relinfo->{-is_optional}
318             and
319             defined ( my $first_distinct_child_idcol = first
320 496     496   1405 { ! $known_present_ids->{$_} }
321 232         1021 @{$relinfo->{-identifying_columns}}
322             )
323             ) {
324              
325 232 100       679 if ($args->{prune_null_branches}) {
326              
327             # start of wrap of the entire chain in a conditional
328             splice @src, $rel_src_pos, 0, sprintf "( ! defined %s )\n ? %s%s{%s} = %s\n : do {",
329             "'\xFF__VALPOS__${first_distinct_child_idcol}__\xFF'",
330             $node_idx_slot,
331             $args->{hri_style} ? '' : '[1]',
332             perlstring($rel),
333 213 100 100     1595 ($args->{hri_style} && $relinfo->{-is_single}) ? 'undef' : '[]'
    100          
334             ;
335              
336             # end of wrap
337 213         1090 push @src, '};'
338             }
339             else {
340              
341 19         86 splice @src, $rel_src_pos + 1, 0, sprintf ( '(defined %s) or bless (%s[1]{%s}, %s);',
342             "'\xFF__VALPOS__${first_distinct_child_idcol}__\xFF'",
343             $node_idx_slot,
344             perlstring($rel),
345             perlstring($null_branch_class),
346             );
347             }
348             }
349             }
350              
351             return (
352             \@src,
353             {
354             idcols_seen => {
355 324         554 ( map { %{ $_->{idcols_seen} } } values %$stats ),
  324         1099  
356 489         1594 ( map { $_ => 1 } @{$args->{collapse_map}->{-identifying_columns}} ),
  925         4567  
  489         1220  
357             }
358             }
359             );
360             }
361              
362             sub __result_struct_to_source {
363             sprintf( '{ %s }', join (', ', map
364 2204         5417 { sprintf "%s => '\xFF__VALPOS__%d__\xFF'", perlstring($_), $_[0]{$_} }
365 627     627   1199 sort keys %{$_[0]}
  627         2395  
366             ));
367             }
368              
369             1;