Step up the error reporting on unexpected NULLs during collapse
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource / RowParser.pm
CommitLineData
4e9fc3f3 1package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser;
76031e14 3
4use strict;
5use warnings;
6
9f98c4b2 7use base 'DBIx::Class';
8
76031e14 9use Try::Tiny;
fcf32d04 10use List::Util qw(first max);
76031e14 11
9f98c4b2 12use DBIx::Class::ResultSource::RowParser::Util qw(
13 assemble_simple_parser
14 assemble_collapsing_parser
15);
76031e14 16
47dba3e3 17use DBIx::Class::Carp;
18
9f98c4b2 19use namespace::clean;
76031e14 20
47dba3e3 21# Accepts a prefetch map (one or more relationships for the current source),
22# returns a set of select/as pairs for each of those relationships. Columns
23# are fully qualified inflation_slot names
24sub _resolve_selection_from_prefetch {
25 my ($self, $pre, $alias_map, $pref_path) = @_;
26
27 # internal recursion marker
76031e14 28 $pref_path ||= [];
29
30 if (not defined $pre or not length $pre) {
31 return ();
32 }
33 elsif( ref $pre eq 'ARRAY' ) {
47dba3e3 34 map { $self->_resolve_selection_from_prefetch( $_, $alias_map, [ @$pref_path ] ) }
35 @$pre;
76031e14 36 }
37 elsif( ref $pre eq 'HASH' ) {
76031e14 38 map {
47dba3e3 39 $self->_resolve_selection_from_prefetch($_, $alias_map, [ @$pref_path ] ),
40 $self->related_source($_)->_resolve_selection_from_prefetch(
41 $pre->{$_}, $alias_map, [ @$pref_path, $_] )
76031e14 42 } keys %$pre;
76031e14 43 }
44 elsif( ref $pre ) {
45 $self->throw_exception(
46 "don't know how to resolve prefetch reftype ".ref($pre));
47 }
48 else {
49 my $p = $alias_map;
47dba3e3 50 $p = $p->{$_} for @$pref_path, $pre;
76031e14 51
52 $self->throw_exception (
53 "Unable to resolve prefetch '$pre' - join alias map does not contain an entry for path: "
54 . join (' -> ', @$pref_path, $pre)
55 ) if (ref $p->{-join_aliases} ne 'ARRAY' or not @{$p->{-join_aliases}} );
56
47dba3e3 57 # this shift() is critical - it is what allows prefetch => [ (foo) x 2 ] to work
58 my $src_alias = shift @{$p->{-join_aliases}};
76031e14 59
47dba3e3 60 # ordered [select => as] pairs
61 map { [
62 "${src_alias}.$_" => join ( '.',
63 @$pref_path,
64 $pre,
65 $_,
66 )
67 ] } $self->related_source($pre)->columns;
68 }
69}
76031e14 70
47dba3e3 71sub _resolve_prefetch {
72 carp_unique(
73 'There is no good reason to call this internal deprecated method - '
74 . 'please open a ticket detailing your usage, so that a better plan can '
75 . 'be devised for your case. In either case _resolve_prefetch() is '
76 . 'deprecated in favor of _resolve_selection_from_prefetch(), which has '
77 . 'a greatly simplified arglist.'
78 );
76031e14 79
47dba3e3 80 $_[0]->_resolve_selection_from_prefetch( $_[1], $_[3] );
76031e14 81}
82
47dba3e3 83
9f98c4b2 84# Takes an arrayref of {as} dbic column aliases and the collapse and select
85# attributes from the same $rs (the selector requirement is a temporary
86# workaround... I hope), and returns a coderef capable of:
87# my $me_pref_clps = $coderef->([$rs->cursor->next/all])
88# Where the $me_pref_clps arrayref is the future argument to inflate_result()
89#
90# For an example of this coderef in action (and to see its guts) look at
91# t/resultset/rowparser_internals.t
92#
93# This is a huge performance win, as we call the same code for every row
94# returned from the db, thus avoiding repeated method lookups when traversing
95# relationships
96#
97# Also since the coderef is completely stateless (the returned structure is
98# always fresh on every new invocation) this is a very good opportunity for
99# memoization if further speed improvements are needed
100#
101# The way we construct this coderef is somewhat fugly, although the result is
102# really worth it. The final coderef does not perform any kind of recursion -
103# the entire nested structure constructor is rolled out into a single scope.
104#
105# In any case - the output of this thing is meticulously micro-tested, so
106# any sort of adjustment/rewrite should be relatively easy (fsvo relatively)
107#
108sub _mk_row_parser {
4a0eed52 109 # $args and $attrs are separated to delineate what is core collapser stuff and
5b309063 110 # what is dbic $rs specific
111 my ($self, $args, $attrs) = @_;
9f98c4b2 112
79adc44f 113 die "HRI without pruning makes zero sense"
114 if ( $args->{hri_style} && ! $args->{prune_null_branches} );
115
116 my %common = (
117 hri_style => $args->{hri_style},
118 prune_null_branches => $args->{prune_null_branches},
119 val_index => { map
120 { $args->{inflate_map}[$_] => $_ }
121 ( 0 .. $#{$args->{inflate_map}} )
122 },
123 );
124
02a73c96 125 my $src = (! $args->{collapse} ) ? assemble_simple_parser(\%common) : do {
126 my $collapse_map = $self->_resolve_collapse ({
127 # FIXME
128 # only consider real columns (not functions) during collapse resolution
129 # this check shouldn't really be here, as fucktards are not supposed to
130 # alias random crap to existing column names anyway, but still - just in
131 # case
132 # FIXME !!!! - this does not yet deal with unbalanced selectors correctly
133 # (it is now trivial as the attrs specify where things go out of sync
134 # needs MOAR tests)
135 as => { map
136 { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
137 keys %{$common{val_index}}
138 },
139 premultiplied => $args->{premultiplied},
140 });
141
02a73c96 142 assemble_collapsing_parser({
79adc44f 143 %common,
02a73c96 144 collapse_map => $collapse_map,
145 });
146 };
147
2fdeef65 148 utf8::upgrade($src)
149 if DBIx::Class::_ENV_::STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE;
150
02a73c96 151 return (
152 $args->{eval} ? ( eval "sub $src" || die $@ ) : $src,
02a73c96 153 );
9f98c4b2 154}
155
156
2d0b795a 157# Takes an arrayref selection list and generates a collapse-map representing
76031e14 158# row-object fold-points. Every relationship is assigned a set of unique,
159# non-nullable columns (which may *not even be* from the same resultset)
160# and the collapser will use this information to correctly distinguish
2d0b795a 161# data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
162# for extensive RV examples
76031e14 163sub _resolve_collapse {
82f0e0aa 164 my ($self, $args, $common_args) = @_;
76031e14 165
166 # for comprehensible error messages put ourselves at the head of the relationship chain
82f0e0aa 167 $args->{_rel_chain} ||= [ $self->source_name ];
76031e14 168
9f98c4b2 169 # record top-level fully-qualified column index, signify toplevelness
170 unless ($common_args->{_as_fq_idx}) {
171 $common_args->{_as_fq_idx} = { %{$args->{as}} };
172 $args->{_is_top_level} = 1;
82f0e0aa 173 };
76031e14 174
fd2d3c95 175 my ($my_cols, $rel_cols, $native_cols);
82f0e0aa 176 for (keys %{$args->{as}}) {
76031e14 177 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
178 $rel_cols->{$1}{$2} = 1;
179 }
180 else {
fd2d3c95 181 $native_cols->{$_} = $my_cols->{$_} = {}; # important for ||='s below
76031e14 182 }
183 }
184
185 my $relinfo;
fcf32d04 186 # run through relationships, collect metadata
76031e14 187 for my $rel (keys %$rel_cols) {
76031e14 188 my $inf = $self->relationship_info ($rel);
189
95e41036 190 $relinfo->{$rel} = {
191 is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
192 is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
193 rsrc => $self->related_source($rel),
a4e58b18 194 fk_map => $self->_resolve_relationship_condition(
195 rel_name => $rel,
196 self_alias => "\xFE", # irrelevant
197 foreign_alias => "\xFF", # irrelevant
198 )->{identity_map},
95e41036 199 };
76031e14 200 }
201
fcf32d04 202 # inject non-left fk-bridges from *INNER-JOINED* children (if any)
203 for my $rel (grep { $relinfo->{$_}{is_inner} } keys %$relinfo) {
204 my $ri = $relinfo->{$rel};
205 for (keys %{$ri->{fk_map}} ) {
206 # need to know source from *our* pov, hence $rel.col
207 $my_cols->{$_} ||= { via_fk => "$rel.$ri->{fk_map}{$_}" }
208 if defined $rel_cols->{$rel}{$ri->{fk_map}{$_}} # in fact selected
209 }
210 }
211
a0726a33 212 # if the parent is already defined *AND* we have an inner reverse relationship
213 # (i.e. do not exist without it) , assume all of its related FKs are selected
76031e14 214 # (even if they in fact are NOT in the select list). Keep a record of what we
215 # assumed, and if any such phantom-column becomes part of our own collapser,
216 # throw everything assumed-from-parent away and replace with the collapser of
217 # the parent (whatever it may be)
218 my $assumed_from_parent;
a0726a33 219 if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
fcf32d04 220 for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
221 next if exists $my_cols->{$col};
27f3e97d 222 $my_cols->{$col} = {};
fcf32d04 223 $assumed_from_parent->{columns}{$col}++;
224 }
76031e14 225 }
226
227 # get colinfo for everything
228 if ($my_cols) {
229 my $ci = $self->columns_info;
230 $my_cols->{$_}{colinfo} = $ci->{$_} for keys %$my_cols;
231 }
232
233 my $collapse_map;
234
3faac878 235 # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
236 # (makes for a leaner coderef later)
fd2d3c95 237 if(
238 ! $collapse_map->{-identifying_columns}
239 and
240 $args->{_parent_info}{collapser_reusable}
241 ) {
9f98c4b2 242 $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
fd2d3c95 243 }
244
245 # Still don't know how to collapse - in case we are a *single* relationship
246 # AND our parent is defined AND we have any *native* non-nullable pieces: then
247 # we are still good to go
248 # NOTE: it doesn't matter if the nonnullable set is unique or not - it will be
249 # made unique by the parents identifying cols
250 if(
251 ! $collapse_map->{-identifying_columns}
252 and
253 $args->{_parent_info}{is_single}
254 and
255 @{ $args->{_parent_info}{collapse_on_idcols} }
256 and
257 ( my @native_nonnull_cols = grep {
258 $native_cols->{$_}{colinfo}
259 and
260 ! $native_cols->{$_}{colinfo}{is_nullable}
261 } keys %$native_cols )
262 ) {
263
264 $collapse_map->{-identifying_columns} = [ __unique_numlist(
265 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
266
267 # FIXME - we don't really need *all* of the columns, $our_nonnull_cols[0]
268 # is sufficient. However map the entire thing to engage the extra nonnull
269 # explicit checks, just to be on the safe side
270 # Remove some day in the future
271 (map
272 {
273 $common_args->{_as_fq_idx}{join ('.',
274 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
275 $_,
276 )}
277 }
278 @native_nonnull_cols
279 ),
280 )];
3faac878 281 }
282
4a0eed52 283 # Still don't know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
76031e14 284 if (
9f98c4b2 285 ! $collapse_map->{-identifying_columns}
3faac878 286 and
76031e14 287 $my_cols
288 and
4e9fc3f3 289 my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
76031e14 290 ) {
291 # see if the resulting collapser relies on any implied columns,
292 # and fix stuff up if this is the case
4e9fc3f3 293 my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
76031e14 294
9f98c4b2 295 $collapse_map->{-identifying_columns} = [ __unique_numlist(
3faac878 296 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
297
76031e14 298 (map
299 {
300 my $fqc = join ('.',
82f0e0aa 301 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
76031e14 302 ( $my_cols->{$_}{via_fk} || $_ ),
303 );
304
82f0e0aa 305 $common_args->{_as_fq_idx}->{$fqc};
76031e14 306 }
4e9fc3f3 307 @reduced_set
76031e14 308 ),
3faac878 309 )];
76031e14 310 }
311
312 # Stil don't know how to collapse - keep descending down 1:1 chains - if
313 # a related non-LEFT 1:1 is resolvable - its condition will collapse us
314 # too
9f98c4b2 315 unless ($collapse_map->{-identifying_columns}) {
76031e14 316 my @candidates;
317
318 for my $rel (keys %$relinfo) {
319 next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
320
82f0e0aa 321 if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
322 as => $rel_cols->{$rel},
323 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
324 _parent_info => { underdefined => 1 },
325 }, $common_args)) {
9f98c4b2 326 push @candidates, $rel_collapse->{-identifying_columns};
76031e14 327 }
328 }
329
330 # get the set with least amount of columns
331 # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
332 # to a single varchar)
333 if (@candidates) {
9f98c4b2 334 ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
76031e14 335 }
336 }
337
fcf32d04 338 # Stil don't know how to collapse, and we are the root node. Last ditch
339 # effort in case we are *NOT* premultiplied.
340 # Run through *each multi* all the way down, left or not, and all
341 # *left* singles (a single may become a multi underneath) . When everything
342 # gets back see if all the rels link to us definitively. If this is the
343 # case we are good - either one of them will define us, or if all are NULLs
344 # we know we are "unique" due to the "non-premultiplied" check
345 if (
9f98c4b2 346 ! $collapse_map->{-identifying_columns}
fcf32d04 347 and
348 ! $args->{premultiplied}
349 and
9f98c4b2 350 $args->{_is_top_level}
fcf32d04 351 ) {
352 my (@collapse_sets, $uncollapsible_chain);
353
354 for my $rel (keys %$relinfo) {
355
356 # we already looked at these higher up
357 next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
358
359 if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
360 as => $rel_cols->{$rel},
361 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
362 _parent_info => { underdefined => 1 },
363 }, $common_args) ) {
364
365 # for singles use the idcols wholesale (either there or not)
366 if ($relinfo->{$rel}{is_single}) {
9f98c4b2 367 push @collapse_sets, $clps->{-identifying_columns};
fcf32d04 368 }
369 elsif (! $relinfo->{$rel}{fk_map}) {
370 $uncollapsible_chain = 1;
371 last;
372 }
373 else {
374 my $defined_cols_parent_side;
375
376 for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
377 my ($col) = $fq_col =~ /([^\.]+)$/;
378
379 $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
380 { $relinfo->{$rel}{fk_map}{$_} eq $col }
381 keys %{$relinfo->{$rel}{fk_map}}
382 ;
383 }
384
385 if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
386 push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
387 }
388 else {
389 $uncollapsible_chain = 1;
390 last;
391 }
392 }
393 }
394 else {
395 $uncollapsible_chain = 1;
396 last;
397 }
398 }
399
400 unless ($uncollapsible_chain) {
401 # if we got here - we are good to go, but the construction is tricky
402 # since our children will want to include our collapse criteria - we
403 # don't give them anything (safe, since they are all collapsible on their own)
4a0eed52 404 # in addition we record the individual collapse possibilities
fcf32d04 405 # of all left children node collapsers, and merge them in the rowparser
406 # coderef later
9f98c4b2 407 $collapse_map->{-identifying_columns} = [];
408 $collapse_map->{-identifying_columns_variants} = [ sort {
fcf32d04 409 (scalar @$a) <=> (scalar @$b) or max(@$a) <=> max(@$b)
410 } @collapse_sets ];
411 }
412 }
413
76031e14 414 # stop descending into children if we were called by a parent for first-pass
415 # and don't despair if nothing was found (there may be other parallel branches
416 # to dive into)
82f0e0aa 417 if ($args->{_parent_info}{underdefined}) {
9f98c4b2 418 return $collapse_map->{-identifying_columns} ? $collapse_map : undef
76031e14 419 }
420 # nothing down the chain resolved - can't calculate a collapse-map
9f98c4b2 421 elsif (! $collapse_map->{-identifying_columns}) {
76031e14 422 $self->throw_exception ( sprintf
423 "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
424 $self->source_name,
82f0e0aa 425 @{$args->{_rel_chain}} > 1
426 ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
76031e14 427 : ''
428 ,
429 );
430 }
431
432 # If we got that far - we are collapsable - GREAT! Now go down all children
433 # a second time, and fill in the rest
434
a0726a33 435 $collapse_map->{-identifying_columns} = [ __unique_numlist(
436 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
437 @{ $collapse_map->{-identifying_columns} },
438 )];
3faac878 439
76031e14 440 for my $rel (sort keys %$relinfo) {
441
82f0e0aa 442 $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
443 as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
444 _rel_chain => [ @{$args->{_rel_chain}}, $rel],
445 _parent_info => {
3faac878 446 # shallow copy
9f98c4b2 447 collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
76031e14 448
449 rel_condition => $relinfo->{$rel}{fk_map},
450
a0726a33 451 is_optional => ! $relinfo->{$rel}{is_inner},
452
fd2d3c95 453 is_single => $relinfo->{$rel}{is_single},
454
a0726a33 455 # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
456 # we can safely assume that the child can not exist without us
457 rev_rel_is_optional => ( first
458 { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
459 values %{ $self->reverse_relationship_info($rel) },
460 ) ? 0 : 1,
76031e14 461
462 # if this is a 1:1 our own collapser can be used as a collapse-map
463 # (regardless of left or not)
3d8caf63 464 collapser_reusable => (
465 $relinfo->{$rel}{is_single}
466 &&
467 $relinfo->{$rel}{is_inner}
468 &&
469 @{$collapse_map->{-identifying_columns}}
470 ) ? 1 : 0,
76031e14 471 },
82f0e0aa 472 }, $common_args );
76031e14 473
474 $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
475 $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
3faac878 476 }
76031e14 477
478 return $collapse_map;
479}
480
76031e14 481# adding a dep on MoreUtils *just* for this is retarded
482sub __unique_numlist {
3faac878 483 sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}
76031e14 484}
485
76031e14 4861;