1 package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser;
7 use base 'DBIx::Class';
11 use DBIx::Class::ResultSource::RowParser::Util qw(
12 assemble_simple_parser
13 assemble_collapsing_parser
16 use DBIx::Class::Carp;
20 # Accepts a prefetch map (one or more relationships for the current source),
21 # returns a set of select/as pairs for each of those relationships. Columns
22 # are fully qualified inflation_slot names
23 sub _resolve_selection_from_prefetch {
24 my ($self, $pre, $alias_map, $pref_path) = @_;
26 # internal recursion marker
29 if (not defined $pre or not length $pre) {
32 elsif( ref $pre eq 'ARRAY' ) {
33 map { $self->_resolve_selection_from_prefetch( $_, $alias_map, [ @$pref_path ] ) }
36 elsif( ref $pre eq 'HASH' ) {
38 $self->_resolve_selection_from_prefetch($_, $alias_map, [ @$pref_path ] ),
39 $self->related_source($_)->_resolve_selection_from_prefetch(
40 $pre->{$_}, $alias_map, [ @$pref_path, $_] )
44 $self->throw_exception(
45 "don't know how to resolve prefetch reftype ".ref($pre));
49 $p = $p->{$_} for @$pref_path, $pre;
51 $self->throw_exception (
52 "Unable to resolve prefetch '$pre' - join alias map does not contain an entry for path: "
53 . join (' -> ', @$pref_path, $pre)
54 ) if (ref $p->{-join_aliases} ne 'ARRAY' or not @{$p->{-join_aliases}} );
56 # this shift() is critical - it is what allows prefetch => [ (foo) x 2 ] to work
57 my $src_alias = shift @{$p->{-join_aliases}};
59 # ordered [select => as] pairs
61 "${src_alias}.$_" => join ( '.',
66 ] } $self->related_source($pre)->columns;
70 sub _resolve_prefetch {
72 'There is no good reason to call this internal deprecated method - '
73 . 'please open a ticket detailing your usage, so that a better plan can '
74 . 'be devised for your case. In either case _resolve_prefetch() is '
75 . 'deprecated in favor of _resolve_selection_from_prefetch(), which has '
76 . 'a greatly simplified arglist.'
79 $_[0]->_resolve_selection_from_prefetch( $_[1], $_[3] );
83 # Takes an arrayref of {as} dbic column aliases and the collapse and select
84 # attributes from the same $rs (the selector requirement is a temporary
85 # workaround... I hope), and returns a coderef capable of:
86 # my $me_pref_clps = $coderef->([$rs->cursor->next/all])
87 # Where the $me_pref_clps arrayref is the future argument to inflate_result()
89 # For an example of this coderef in action (and to see its guts) look at
90 # t/resultset/rowparser_internals.t
92 # This is a huge performance win, as we call the same code for every row
93 # returned from the db, thus avoiding repeated method lookups when traversing
96 # Also since the coderef is completely stateless (the returned structure is
97 # always fresh on every new invocation) this is a very good opportunity for
98 # memoization if further speed improvements are needed
100 # The way we construct this coderef is somewhat fugly, although the result is
101 # really worth it. The final coderef does not perform any kind of recursion -
102 # the entire nested structure constructor is rolled out into a single scope.
104 # In any case - the output of this thing is meticulously micro-tested, so
105 # any sort of adjustment/rewrite should be relatively easy (fsvo relatively)
108 # $args and $attrs are separated to delineate what is core collapser stuff and
109 # what is dbic $rs specific
110 my ($self, $args, $attrs) = @_;
112 die "HRI without pruning makes zero sense"
113 if ( $args->{hri_style} && ! $args->{prune_null_branches} );
116 hri_style => $args->{hri_style},
117 prune_null_branches => $args->{prune_null_branches},
119 { $args->{inflate_map}[$_] => $_ }
120 ( 0 .. $#{$args->{inflate_map}} )
124 my $src = (! $args->{collapse} ) ? assemble_simple_parser(\%common) : do {
125 my $collapse_map = $self->_resolve_collapse ({
127 # only consider real columns (not functions) during collapse resolution
128 # this check shouldn't really be here, as fucktards are not supposed to
129 # alias random crap to existing column names anyway, but still - just in
131 # FIXME !!!! - this does not yet deal with unbalanced selectors correctly
132 # (it is now trivial as the attrs specify where things go out of sync
135 { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
136 keys %{$common{val_index}}
138 premultiplied => $args->{premultiplied},
141 assemble_collapsing_parser({
143 collapse_map => $collapse_map,
148 if DBIx::Class::_ENV_::STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE;
154 # Takes an arrayref selection list and generates a collapse-map representing
155 # row-object fold-points. Every relationship is assigned a set of unique,
156 # non-nullable columns (which may *not even be* from the same resultset)
157 # and the collapser will use this information to correctly distinguish
158 # data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
159 # for extensive RV examples
160 sub _resolve_collapse {
161 my ($self, $args, $common_args) = @_;
163 # for comprehensible error messages put ourselves at the head of the relationship chain
164 $args->{_rel_chain} ||= [ $self->source_name ];
166 # record top-level fully-qualified column index, signify toplevelness
167 unless ($common_args->{_as_fq_idx}) {
168 $common_args->{_as_fq_idx} = { %{$args->{as}} };
169 $args->{_is_top_level} = 1;
172 my ($my_cols, $rel_cols, $native_cols);
173 for (keys %{$args->{as}}) {
174 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
175 $rel_cols->{$1}{$2} = 1;
178 $native_cols->{$_} = $my_cols->{$_} = {}; # important for ||='s below
183 # run through relationships, collect metadata
184 for my $rel (keys %$rel_cols) {
185 my $inf = $self->relationship_info ($rel);
188 is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
189 is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
190 rsrc => $self->related_source($rel),
191 fk_map => $self->_resolve_relationship_condition(
193 self_alias => "\xFE", # irrelevant
194 foreign_alias => "\xFF", # irrelevant
199 # inject non-left fk-bridges from *INNER-JOINED* children (if any)
200 for my $rel (grep { $relinfo->{$_}{is_inner} } keys %$relinfo) {
201 my $ri = $relinfo->{$rel};
202 for (keys %{$ri->{fk_map}} ) {
203 # need to know source from *our* pov, hence $rel.col
204 $my_cols->{$_} ||= { via_fk => "$rel.$ri->{fk_map}{$_}" }
205 if defined $rel_cols->{$rel}{$ri->{fk_map}{$_}} # in fact selected
209 # if the parent is already defined *AND* we have an inner reverse relationship
210 # (i.e. do not exist without it) , assume all of its related FKs are selected
211 # (even if they in fact are NOT in the select list). Keep a record of what we
212 # assumed, and if any such phantom-column becomes part of our own collapser,
213 # throw everything assumed-from-parent away and replace with the collapser of
214 # the parent (whatever it may be)
215 my $assumed_from_parent;
216 if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
217 for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
218 next if exists $my_cols->{$col};
219 $my_cols->{$col} = {};
220 $assumed_from_parent->{columns}{$col}++;
224 # get colinfo for everything
226 my $ci = $self->columns_info;
227 $my_cols->{$_}{colinfo} = $ci->{$_} for keys %$my_cols;
232 # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
233 # (makes for a leaner coderef later)
235 ! $collapse_map->{-identifying_columns}
237 $args->{_parent_info}{collapser_reusable}
239 $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
242 # Still don't know how to collapse - in case we are a *single* relationship
243 # AND our parent is defined AND we have any *native* non-nullable pieces: then
244 # we are still good to go
245 # NOTE: it doesn't matter if the nonnullable set is unique or not - it will be
246 # made unique by the parents identifying cols
248 ! $collapse_map->{-identifying_columns}
250 $args->{_parent_info}{is_single}
252 @{ $args->{_parent_info}{collapse_on_idcols} }
254 ( my @native_nonnull_cols = grep {
255 $native_cols->{$_}{colinfo}
257 ! $native_cols->{$_}{colinfo}{is_nullable}
258 } keys %$native_cols )
261 $collapse_map->{-identifying_columns} = [ __unique_numlist(
262 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
264 # FIXME - we don't really need *all* of the columns, $our_nonnull_cols[0]
265 # is sufficient. However map the entire thing to engage the extra nonnull
266 # explicit checks, just to be on the safe side
267 # Remove some day in the future
270 $common_args->{_as_fq_idx}{join ('.',
271 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
280 # Still don't know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
282 ! $collapse_map->{-identifying_columns}
286 my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
288 # see if the resulting collapser relies on any implied columns,
289 # and fix stuff up if this is the case
290 my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
292 $collapse_map->{-identifying_columns} = [ __unique_numlist(
293 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
298 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
299 ( $my_cols->{$_}{via_fk} || $_ ),
302 $common_args->{_as_fq_idx}->{$fqc};
309 # Stil don't know how to collapse - keep descending down 1:1 chains - if
310 # a related non-LEFT 1:1 is resolvable - its condition will collapse us
312 unless ($collapse_map->{-identifying_columns}) {
315 for my $rel (keys %$relinfo) {
316 next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
318 if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
319 as => $rel_cols->{$rel},
320 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
321 _parent_info => { underdefined => 1 },
323 push @candidates, $rel_collapse->{-identifying_columns};
327 # get the set with least amount of columns
328 # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
329 # to a single varchar)
331 ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
335 # Stil don't know how to collapse, and we are the root node. Last ditch
336 # effort in case we are *NOT* premultiplied.
337 # Run through *each multi* all the way down, left or not, and all
338 # *left* singles (a single may become a multi underneath) . When everything
339 # gets back see if all the rels link to us definitively. If this is the
340 # case we are good - either one of them will define us, or if all are NULLs
341 # we know we are "unique" due to the "non-premultiplied" check
343 ! $collapse_map->{-identifying_columns}
345 ! $args->{premultiplied}
347 $args->{_is_top_level}
349 my (@collapse_sets, $uncollapsible_chain);
351 for my $rel (keys %$relinfo) {
353 # we already looked at these higher up
354 next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
356 if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
357 as => $rel_cols->{$rel},
358 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
359 _parent_info => { underdefined => 1 },
362 # for singles use the idcols wholesale (either there or not)
363 if ($relinfo->{$rel}{is_single}) {
364 push @collapse_sets, $clps->{-identifying_columns};
366 elsif (! $relinfo->{$rel}{fk_map}) {
367 $uncollapsible_chain = 1;
371 my $defined_cols_parent_side;
373 for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
374 my ($col) = $fq_col =~ /([^\.]+)$/;
376 $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
377 { $relinfo->{$rel}{fk_map}{$_} eq $col }
378 keys %{$relinfo->{$rel}{fk_map}}
382 if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
383 push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
386 $uncollapsible_chain = 1;
392 $uncollapsible_chain = 1;
397 unless ($uncollapsible_chain) {
398 # if we got here - we are good to go, but the construction is tricky
399 # since our children will want to include our collapse criteria - we
400 # don't give them anything (safe, since they are all collapsible on their own)
401 # in addition we record the individual collapse possibilities
402 # of all left children node collapsers, and merge them in the rowparser
404 $collapse_map->{-identifying_columns} = [];
405 $collapse_map->{-identifying_columns_variants} = [ sort {
406 (scalar @$a) <=> (scalar @$b)
410 ( sort { $b <=> $a } @$a )[0]
412 ( sort { $b <=> $a } @$b )[0]
418 # stop descending into children if we were called by a parent for first-pass
419 # and don't despair if nothing was found (there may be other parallel branches
421 if ($args->{_parent_info}{underdefined}) {
422 return $collapse_map->{-identifying_columns} ? $collapse_map : undef
424 # nothing down the chain resolved - can't calculate a collapse-map
425 elsif (! $collapse_map->{-identifying_columns}) {
426 $self->throw_exception ( sprintf
427 "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
429 @{$args->{_rel_chain}} > 1
430 ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
436 # If we got that far - we are collapsable - GREAT! Now go down all children
437 # a second time, and fill in the rest
439 $collapse_map->{-identifying_columns} = [ __unique_numlist(
440 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
441 @{ $collapse_map->{-identifying_columns} },
444 for my $rel (sort keys %$relinfo) {
446 $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
447 as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
448 _rel_chain => [ @{$args->{_rel_chain}}, $rel],
451 collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
453 rel_condition => $relinfo->{$rel}{fk_map},
455 is_optional => ! $relinfo->{$rel}{is_inner},
457 is_single => $relinfo->{$rel}{is_single},
459 # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
460 # we can safely assume that the child can not exist without us
461 rev_rel_is_optional => ( grep
462 { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
463 values %{ $self->reverse_relationship_info($rel) },
466 # if this is a 1:1 our own collapser can be used as a collapse-map
467 # (regardless of left or not)
468 collapser_reusable => (
469 $relinfo->{$rel}{is_single}
471 $relinfo->{$rel}{is_inner}
473 @{$collapse_map->{-identifying_columns}}
478 $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
479 $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
482 return $collapse_map;
485 # adding a dep on MoreUtils *just* for this is retarded
486 sub __unique_numlist {
487 sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}