Fix idiocy that snuck in bdbd2ae8a - I only want fatal undefs
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource / RowParser / Util.pm
CommitLineData
9f98c4b2 1package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser::Util;
3
4use strict;
5use warnings;
6
ce556881 7use List::Util 'first';
01b25f12 8use DBIx::Class::_Util 'perlstring';
9f98c4b2 9
cd784aab 10use constant HAS_DOR => ( $] < 5.010 ? 0 : 1 );
11
9f98c4b2 12use base 'Exporter';
13our @EXPORT_OK = qw(
14 assemble_simple_parser
15 assemble_collapsing_parser
16);
17
52864fbd 18# working title - we are hoping to extract this eventually...
19our $null_branch_class = 'DBIx::ResultParser::RelatedNullBranch';
20
9f7d5590 21sub __wrap_in_strictured_scope {
22 " { use strict; use warnings; use warnings FATAL => 'uninitialized';\n$_[0]\n }"
23}
24
9f98c4b2 25sub 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 my $parser_src = sprintf('$_ = %s for @{$_[0]}', __visit_infmap_simple($_[0]) );
38
39 # change the quoted placeholders to unquoted alias-references
40 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$_->[$1]"/gex;
41
9f7d5590 42 __wrap_in_strictured_scope($parser_src);
9f98c4b2 43}
44
45# the simple non-collapsing nested structure recursor
46sub __visit_infmap_simple {
47 my $args = shift;
48
49 my $my_cols = {};
50 my $rel_cols;
51 for (keys %{$args->{val_index}}) {
52 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
53 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
54 }
55 else {
56 $my_cols->{$_} = $args->{val_index}{$_};
57 }
58 }
59
60 my @relperl;
61 for my $rel (sort keys %$rel_cols) {
62
52864fbd 63 my $rel_struct = __visit_infmap_simple({ %$args,
9f98c4b2 64 val_index => $rel_cols->{$rel},
9f98c4b2 65 });
66
52864fbd 67 if (keys %$my_cols) {
ce556881 68
52864fbd 69 my $branch_null_checks = join ' && ', map
ce556881 70 { "( ! defined '\xFF__VALPOS__${_}__\xFF' )" }
71 sort { $a <=> $b } values %{$rel_cols->{$rel}}
72 ;
73
79adc44f 74 if ($args->{prune_null_branches}) {
52864fbd 75 $rel_struct = sprintf ( '( (%s) ? undef : %s )',
76 $branch_null_checks,
77 $rel_struct,
78 );
79 }
80 else {
81 $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 }
ce556881 88 }
52864fbd 89
90 push @relperl, sprintf '( %s => %s )',
91 perlstring($rel),
92 $rel_struct,
93 ;
94
9f98c4b2 95 }
96
ce556881 97 my $me_struct;
a8f62ee0 98 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
9f98c4b2 99
ce556881 100 if ($args->{hri_style}) {
101 $me_struct =~ s/^ \s* \{ | \} \s* $//gx
102 if $me_struct;
103
104 return sprintf '{ %s }', join (', ', $me_struct||(), @relperl);
105 }
106 else {
107 return sprintf '[%s]', join (',',
108 $me_struct || 'undef',
109 @relperl ? sprintf ('{ %s }', join (',', @relperl)) : (),
110 );
111 }
9f98c4b2 112}
113
114sub assemble_collapsing_parser {
115 my $args = shift;
116
06b3406d 117 # it may get unset further down
79adc44f 118 my $no_rowid_container = $args->{prune_null_branches};
06b3406d 119
9f98c4b2 120 my ($top_node_key, $top_node_key_assembler);
121
122 if (scalar @{$args->{collapse_map}{-identifying_columns}}) {
123 $top_node_key = join ('', map
124 { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
125 @{$args->{collapse_map}{-identifying_columns}}
126 );
127 }
128 elsif( my @variants = @{$args->{collapse_map}{-identifying_columns_variants}} ) {
129
130 my @path_parts = map { sprintf
131 "( ( defined '\xFF__VALPOS__%d__\xFF' ) && (join qq(\xFF), '', %s, '') )",
ce556881 132 $_->[0], # checking just first is enough - one ID defined, all defined
9f98c4b2 133 ( join ', ', map { "'\xFF__VALPOS__${_}__\xFF'" } @$_ ),
134 } @variants;
135
136 my $virtual_column_idx = (scalar keys %{$args->{val_index}} ) + 1;
137
7596ddca 138 $top_node_key = "{'\xFF__IDVALPOS__${virtual_column_idx}__\xFF'}";
9f98c4b2 139
7596ddca 140 $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 ;
9f98c4b2 144
145 $args->{collapse_map} = {
146 %{$args->{collapse_map}},
147 -custom_node_key => $top_node_key,
148 };
149
06b3406d 150 $no_rowid_container = 0;
9f98c4b2 151 }
152 else {
153 die('Unexpected collapse map contents');
154 }
155
156 my ($data_assemblers, $stats) = __visit_infmap_collapse ($args);
157
06b3406d 158 my @idcol_args = $no_rowid_container ? ('', '') : (
aa1d8a87 159 ', %cur_row_ids', # only declare the variable if we'll use it
2fdeef65 160 join ("\n", map {
161 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 $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 } sort { $a <=> $b } keys %{ $stats->{idcols_seen} } ),
7596ddca 169 );
9f98c4b2 170
7596ddca 171 my $parser_src = sprintf (<<'EOS', @idcol_args, $top_node_key_assembler||'', $top_node_key, join( "\n", @{$data_assemblers||[]} ) );
9f98c4b2 172### BEGIN LITERAL STRING EVAL
aa1d8a87 173 my $rows_pos = 0;
174 my ($result_pos, @collapse_idx, $cur_row_data %1$s);
175
9f98c4b2 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.
3b4cd124 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
5e6d06f4 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
7596ddca 191 #
9f98c4b2 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
ce556881 195 # (otherwise folding of optional 1:1s will be greatly confused
3b4cd124 196%2$s
9f98c4b2 197
7596ddca 198 # in the case of an underdefined root - calculate the virtual id (otherwise no code at all)
3b4cd124 199%3$s
9f98c4b2 200
aa1d8a87 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
3b4cd124 205$_[1] and $result_pos and ! $collapse_idx[0]%4$s and (unshift @{$_[2]}, $cur_row_data) and last;
9f98c4b2 206
207 # the rel assemblers
7596ddca 208%5$s
9f98c4b2 209
9f98c4b2 210 }
211
aa1d8a87 212 $#{$_[0]} = $result_pos - 1; # truncate the passed in array to where we filled it with results
9f98c4b2 213### END LITERAL STRING EVAL
214EOS
215
216 # !!! note - different var than the one above
217 # change the quoted placeholders to unquoted alias-references
218 $parser_src =~ s/ \' \xFF__VALPOS__(\d+)__\xFF \' /"\$cur_row_data->[$1]"/gex;
06b3406d 219 $parser_src =~ s/
220 \' \xFF__IDVALPOS__(\d+)__\xFF \'
221 /
222 $no_rowid_container ? "\$cur_row_data->[$1]" : "\$cur_row_ids{$1}"
223 /gex;
9f98c4b2 224
9f7d5590 225 __wrap_in_strictured_scope($parser_src);
9f98c4b2 226}
227
228
229# the collapsing nested structure recursor
230sub __visit_infmap_collapse {
231 my $args = {%{ shift() }};
232
233 my $cur_node_idx = ${ $args->{-node_idx_counter} ||= \do { my $x = 0} }++;
234
ce556881 235 my ($my_cols, $rel_cols) = {};
9f98c4b2 236 for ( keys %{$args->{val_index}} ) {
237 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
238 $rel_cols->{$1}{$2} = $args->{val_index}{$_};
239 }
240 else {
241 $my_cols->{$_} = $args->{val_index}{$_};
242 }
243 }
244
ce556881 245
ce556881 246 if ($args->{hri_style}) {
247 delete $my_cols->{$_} for grep { $rel_cols->{$_} } keys %$my_cols;
248 }
9f98c4b2 249
52864fbd 250 my $me_struct;
a8f62ee0 251 $me_struct = __result_struct_to_source($my_cols) if keys %$my_cols;
ce556881 252
52864fbd 253 $me_struct = sprintf( '[ %s ]', $me_struct||'' )
254 unless $args->{hri_style};
255
256
257 my $node_key = $args->{collapse_map}->{-custom_node_key} || join ('', map
258 { "{'\xFF__IDVALPOS__${_}__\xFF'}" }
259 @{$args->{collapse_map}->{-identifying_columns}}
260 );
ce556881 261 my $node_idx_slot = sprintf '$collapse_idx[%d]%s', $cur_node_idx, $node_key;
9f98c4b2 262
52864fbd 263
9f98c4b2 264 my @src;
ce556881 265
9f98c4b2 266 if ($cur_node_idx == 0) {
cd784aab 267 push @src, sprintf( '%s %s $_[0][$result_pos++] = %s;',
9f98c4b2 268 $node_idx_slot,
cd784aab 269 (HAS_DOR ? '//=' : '||='),
aa1d8a87 270 $me_struct || '{}',
271 );
9f98c4b2 272 }
9f98c4b2 273 else {
ce556881 274 my $parent_attach_slot = sprintf( '$collapse_idx[%d]%s%s{%s}',
275 @{$args}{qw/-parent_node_idx -parent_node_key/},
276 $args->{hri_style} ? '' : '[1]',
a5f5e470 277 perlstring($args->{-node_rel_name}),
9f98c4b2 278 );
ce556881 279
280 if ($args->{collapse_map}->{-is_single}) {
cd784aab 281 push @src, sprintf ( '%s %s %s%s;',
ce556881 282 $parent_attach_slot,
cd784aab 283 (HAS_DOR ? '//=' : '||='),
ce556881 284 $node_idx_slot,
aa1d8a87 285 $me_struct ? " = $me_struct" : '',
ce556881 286 );
287 }
288 else {
289 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 }
9f98c4b2 296 }
297
ce556881 298 my $known_present_ids = { map { $_ => 1 } @{$args->{collapse_map}{-identifying_columns}} };
299 my ($stats, $rel_src);
300
9f98c4b2 301 for my $rel (sort keys %$rel_cols) {
302
ce556881 303 my $relinfo = $args->{collapse_map}{$rel};
9f98c4b2 304
ce556881 305 ($rel_src, $stats->{$rel}) = __visit_infmap_collapse({ %$args,
9f98c4b2 306 val_index => $rel_cols->{$rel},
ce556881 307 collapse_map => $relinfo,
9f98c4b2 308 -parent_node_idx => $cur_node_idx,
309 -parent_node_key => $node_key,
a5f5e470 310 -node_rel_name => $rel,
9f98c4b2 311 });
312
ce556881 313 my $rel_src_pos = $#src + 1;
314 push @src, @$rel_src;
315
316 if (
ce556881 317 $relinfo->{-is_optional}
318 and
319 defined ( my $first_distinct_child_idcol = first
320 { ! $known_present_ids->{$_} }
321 @{$relinfo->{-identifying_columns}}
322 )
323 ) {
324
79adc44f 325 if ($args->{prune_null_branches}) {
ce556881 326
7596ddca 327 # start of wrap of the entire chain in a conditional
79adc44f 328 splice @src, $rel_src_pos, 0, sprintf "( ! defined %s )\n ? %s%s{%s} = %s\n : do {",
7596ddca 329 "'\xFF__VALPOS__${first_distinct_child_idcol}__\xFF'",
52864fbd 330 $node_idx_slot,
79adc44f 331 $args->{hri_style} ? '' : '[1]',
52864fbd 332 perlstring($rel),
79adc44f 333 ($args->{hri_style} && $relinfo->{-is_single}) ? 'undef' : '[]'
7596ddca 334 ;
335
336 # end of wrap
337 push @src, '};'
52864fbd 338 }
339 else {
340
341 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 }
ce556881 348 }
9f98c4b2 349 }
350
351 return (
ce556881 352 \@src,
9f98c4b2 353 {
354 idcols_seen => {
355 ( map { %{ $_->{idcols_seen} } } values %$stats ),
356 ( map { $_ => 1 } @{$args->{collapse_map}->{-identifying_columns}} ),
357 }
358 }
359 );
360}
361
a8f62ee0 362sub __result_struct_to_source {
363 sprintf( '{ %s }', join (', ', map
364 { sprintf "%s => '\xFF__VALPOS__%d__\xFF'", perlstring($_), $_[0]{$_} }
365 sort keys %{$_[0]}
366 ));
9f98c4b2 367}
368
3691;