1 package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser::Util;
7 use List::Util 'first';
12 assemble_simple_parser
13 assemble_collapsing_parser
16 # working title - we are hoping to extract this eventually...
17 our $null_branch_class = 'DBIx::ResultParser::RelatedNullBranch';
19 sub assemble_simple_parser {
22 # the non-collapsing assembler is easy
23 # FIXME SUBOPTIMAL there could be a yet faster way to do things here, but
24 # need to try an actual implementation and benchmark it:
26 # <timbunce_> First setup the nested data structure you want for each row
27 # Then call bind_col() to alias the row fields into the right place in
28 # the data structure, then to fetch the data do:
29 # push @rows, dclone($row_data_struct) while ($sth->fetchrow);
31 my $parser_src = sprintf('$_ = %s for @{$_[0]}', __visit_infmap_simple($_[0]) );
33 # change the quoted placeholders to unquoted alias-references
34 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$_->[$1]"/gex;
36 $parser_src = " { use strict; use warnings FATAL => 'all';\n$parser_src\n }";
39 # the simple non-collapsing nested structure recursor
40 sub __visit_infmap_simple {
45 for (keys %{$args->{val_index}}) {
46 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
47 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
50 $my_cols->{$_} = $args->{val_index}{$_};
55 for my $rel (sort keys %$rel_cols) {
57 my $rel_struct = __visit_infmap_simple({ %$args,
58 val_index => $rel_cols->{$rel},
63 my $branch_null_checks = join ' && ', map
64 { "( ! defined '\xFF__VALPOS__${_}__\xFF' )" }
65 sort { $a <=> $b } values %{$rel_cols->{$rel}}
68 if ($args->{hri_style}) {
69 $rel_struct = sprintf ( '( (%s) ? undef : %s )',
75 $rel_struct = sprintf ( '( (%s) ? bless( (%s), %s ) : %s )',
78 perlstring($null_branch_class),
84 push @relperl, sprintf '( %s => %s )',
92 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
94 if ($args->{hri_style}) {
95 $me_struct =~ s/^ \s* \{ | \} \s* $//gx
98 return sprintf '{ %s }', join (', ', $me_struct||(), @relperl);
101 return sprintf '[%s]', join (',',
102 $me_struct || 'undef',
103 @relperl ? sprintf ('{ %s }', join (',', @relperl)) : (),
108 sub assemble_collapsing_parser {
111 # it may get unset further down
112 my $no_rowid_container = $args->{hri_style};
114 my ($top_node_key, $top_node_key_assembler);
116 if (scalar @{$args->{collapse_map}{-identifying_columns}}) {
117 $top_node_key = join ('', map
118 { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
119 @{$args->{collapse_map}{-identifying_columns}}
122 elsif( my @variants = @{$args->{collapse_map}{-identifying_columns_variants}} ) {
124 my @path_parts = map { sprintf
125 "( ( defined '\xFF__VALPOS__%d__\xFF' ) && (join qq(\xFF), '', %s, '') )",
126 $_->[0], # checking just first is enough - one ID defined, all defined
127 ( join ', ', map { "'\xFF__VALPOS__${_}__\xFF'" } @$_ ),
130 my $virtual_column_idx = (scalar keys %{$args->{val_index}} ) + 1;
132 $top_node_key = "{'\xFF__IDVALPOS__${virtual_column_idx}__\xFF'}";
134 $top_node_key_assembler = sprintf "'\xFF__IDVALPOS__%d__\xFF' = (%s);",
136 "\n" . join( "\n or\n", @path_parts, qq{"\0\$rows_pos\0"} )
139 $args->{collapse_map} = {
140 %{$args->{collapse_map}},
141 -custom_node_key => $top_node_key,
144 $no_rowid_container = 0;
147 die('Unexpected collapse map contents');
150 my ($data_assemblers, $stats) = __visit_infmap_collapse ($args);
152 my @idcol_args = $no_rowid_container ? ('', '') : (
153 ', %cur_row_ids', # only declare the variable if we'll use it
155 sprintf( <<'EOS', join ', ', sort { $a <=> $b } keys %{ $stats->{idcols_seen} } ),
156 $cur_row_ids{$_} = defined($cur_row_data->[$_]) ? $cur_row_data->[$_] : "\0NULL\xFF$rows_pos\xFF$_\0"
161 my $parser_src = sprintf (<<'EOS', @idcol_args, $top_node_key_assembler||'', $top_node_key, join( "\n", @{$data_assemblers||[]} ) );
162 ### BEGIN LITERAL STRING EVAL
164 my ($result_pos, @collapse_idx, $cur_row_data %1$s);
166 # this loop is a bit arcane - the rationale is that the passed in
167 # $_[0] will either have only one row (->next) or will have all
168 # rows already pulled in (->all and/or unordered). Given that the
169 # result can be rather large - we reuse the same already allocated
170 # array, since the collapsed prefetch is smaller by definition.
171 # At the end we cut the leftovers away and move on.
172 while ($cur_row_data =
173 ( ( $rows_pos >= 0 and $_[0][$rows_pos++] ) or do { $rows_pos = -1; undef } )
175 ($_[1] and $_[1]->())
177 # this code exists only when we are *not* assembling direct to HRI
179 # due to left joins some of the ids may be NULL/undef, and
180 # won't play well when used as hash lookups
181 # we also need to differentiate NULLs on per-row/per-col basis
182 # (otherwise folding of optional 1:1s will be greatly confused
185 # in the case of an underdefined root - calculate the virtual id (otherwise no code at all)
188 # if we were supplied a coderef - we are collapsing lazily (the set
189 # is ordered properly)
190 # as long as we have a result already and the next result is new we
191 # return the pre-read data and bail
192 $_[1] and $result_pos and ! $collapse_idx[0]%4$s and (unshift @{$_[2]}, $cur_row_data) and last;
199 $#{$_[0]} = $result_pos - 1; # truncate the passed in array to where we filled it with results
200 ### END LITERAL STRING EVAL
203 # !!! note - different var than the one above
204 # change the quoted placeholders to unquoted alias-references
205 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$cur_row_data->[$1]"/gex;
207 \' \xFF__IDVALPOS__(\d+)__\xFF \'
209 $no_rowid_container ? "\$cur_row_data->[$1]" : "\$cur_row_ids{$1}"
212 $parser_src = " { use strict; use warnings FATAL => 'all';\n$parser_src\n }";
216 # the collapsing nested structure recursor
217 sub __visit_infmap_collapse {
218 my $args = {%{ shift() }};
220 my $cur_node_idx = ${ $args->{-node_idx_counter} ||= \do { my $x = 0} }++;
222 my ($my_cols, $rel_cols) = {};
223 for ( keys %{$args->{val_index}} ) {
224 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
225 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
228 $my_cols->{$_} = $args->{val_index}{$_};
233 if ($args->{hri_style}) {
234 delete $my_cols->{$_} for grep { $rel_cols->{$_} } keys %$my_cols;
238 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
240 $me_struct = sprintf( '[ %s ]', $me_struct||'' )
241 unless $args->{hri_style};
244 my $node_key = $args->{collapse_map}->{-custom_node_key} || join ('', map
245 { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
246 @{$args->{collapse_map}->{-identifying_columns}}
248 my $node_idx_slot = sprintf '$collapse_idx[%d]%s', $cur_node_idx, $node_key;
253 if ($cur_node_idx == 0) {
254 push @src, sprintf( '%s ||= $_[0][$result_pos++] = %s;',
260 my $parent_attach_slot = sprintf( '$collapse_idx[%d]%s%s{%s}',
261 @{$args}{qw/-parent_node_idx -parent_node_key/},
262 $args->{hri_style} ? '' : '[1]',
263 perlstring($args->{-node_relname}),
266 if ($args->{collapse_map}->{-is_single}) {
267 push @src, sprintf ( '%s ||= %s%s;',
270 $me_struct ? " = $me_struct" : '',
274 push @src, sprintf('(! %s) and push @{%s}, %s%s;',
278 $me_struct ? " = $me_struct" : '',
283 my $known_present_ids = { map { $_ => 1 } @{$args->{collapse_map}{-identifying_columns}} };
284 my ($stats, $rel_src);
286 for my $rel (sort keys %$rel_cols) {
288 my $relinfo = $args->{collapse_map}{$rel};
290 ($rel_src, $stats->{$rel}) = __visit_infmap_collapse({ %$args,
291 val_index => $rel_cols->{$rel},
292 collapse_map => $relinfo,
293 -parent_node_idx => $cur_node_idx,
294 -parent_node_key => $node_key,
295 -node_relname => $rel,
298 my $rel_src_pos = $#src + 1;
299 push @src, @$rel_src;
302 $relinfo->{-is_optional}
304 defined ( my $first_distinct_child_idcol = first
305 { ! $known_present_ids->{$_} }
306 @{$relinfo->{-identifying_columns}}
310 if ($args->{hri_style}) {
312 # start of wrap of the entire chain in a conditional
313 splice @src, $rel_src_pos, 0, sprintf "( ! defined %s )\n ? %s{%s} = %s\n : do {",
314 "'\xFF__VALPOS__${first_distinct_child_idcol}__\xFF'",
317 $relinfo->{-is_single} ? 'undef' : '[]'
325 splice @src, $rel_src_pos + 1, 0, sprintf ( '(defined %s) or bless (%s[1]{%s}, %s);',
326 "'\xFF__VALPOS__${first_distinct_child_idcol}__\xFF'",
329 perlstring($null_branch_class),
339 ( map { %{ $_->{idcols_seen} } } values %$stats ),
340 ( map { $_ => 1 } @{$args->{collapse_map}->{-identifying_columns}} ),
346 sub __result_struct_to_source {
347 sprintf( '{ %s }', join (', ', map
348 { sprintf "%s => '\xFF__VALPOS__%d__\xFF'", perlstring($_), $_[0]{$_} }