1 package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser;
7 use base 'DBIx::Class';
12 use DBIx::Class::ResultSource::RowParser::Util qw(
13 assemble_simple_parser
14 assemble_collapsing_parser
17 use DBIx::Class::Carp;
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
24 sub _resolve_selection_from_prefetch {
25 my ($self, $pre, $alias_map, $pref_path) = @_;
27 # internal recursion marker
30 if (not defined $pre or not length $pre) {
33 elsif( ref $pre eq 'ARRAY' ) {
34 map { $self->_resolve_selection_from_prefetch( $_, $alias_map, [ @$pref_path ] ) }
37 elsif( ref $pre eq 'HASH' ) {
39 $self->_resolve_selection_from_prefetch($_, $alias_map, [ @$pref_path ] ),
40 $self->related_source($_)->_resolve_selection_from_prefetch(
41 $pre->{$_}, $alias_map, [ @$pref_path, $_] )
45 $self->throw_exception(
46 "don't know how to resolve prefetch reftype ".ref($pre));
50 $p = $p->{$_} for @$pref_path, $pre;
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}} );
57 # this shift() is critical - it is what allows prefetch => [ (foo) x 2 ] to work
58 my $src_alias = shift @{$p->{-join_aliases}};
60 # ordered [select => as] pairs
62 "${src_alias}.$_" => join ( '.',
67 ] } $self->related_source($pre)->columns;
71 sub _resolve_prefetch {
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.'
80 $_[0]->_resolve_selection_from_prefetch( $_[1], $_[3] );
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()
90 # For an example of this coderef in action (and to see its guts) look at
91 # t/resultset/rowparser_internals.t
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
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
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.
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)
109 # $args and $attrs are separated to delineate what is core collapser stuff and
110 # what is dbic $rs specific
111 my ($self, $args, $attrs) = @_;
113 die "HRI without pruning makes zero sense"
114 if ( $args->{hri_style} && ! $args->{prune_null_branches} );
117 hri_style => $args->{hri_style},
118 prune_null_branches => $args->{prune_null_branches},
120 { $args->{inflate_map}[$_] => $_ }
121 ( 0 .. $#{$args->{inflate_map}} )
125 my $src = (! $args->{collapse} ) ? assemble_simple_parser(\%common) : do {
126 my $collapse_map = $self->_resolve_collapse ({
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
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
136 { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
137 keys %{$common{val_index}}
139 premultiplied => $args->{premultiplied},
142 assemble_collapsing_parser({
144 collapse_map => $collapse_map,
149 if DBIx::Class::_ENV_::STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE;
155 # Takes an arrayref selection list and generates a collapse-map representing
156 # row-object fold-points. Every relationship is assigned a set of unique,
157 # non-nullable columns (which may *not even be* from the same resultset)
158 # and the collapser will use this information to correctly distinguish
159 # data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
160 # for extensive RV examples
161 sub _resolve_collapse {
162 my ($self, $args, $common_args) = @_;
164 # for comprehensible error messages put ourselves at the head of the relationship chain
165 $args->{_rel_chain} ||= [ $self->source_name ];
167 # record top-level fully-qualified column index, signify toplevelness
168 unless ($common_args->{_as_fq_idx}) {
169 $common_args->{_as_fq_idx} = { %{$args->{as}} };
170 $args->{_is_top_level} = 1;
173 my ($my_cols, $rel_cols, $native_cols);
174 for (keys %{$args->{as}}) {
175 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
176 $rel_cols->{$1}{$2} = 1;
179 $native_cols->{$_} = $my_cols->{$_} = {}; # important for ||='s below
184 # run through relationships, collect metadata
185 for my $rel (keys %$rel_cols) {
186 my $inf = $self->relationship_info ($rel);
189 is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
190 is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
191 rsrc => $self->related_source($rel),
192 fk_map => $self->_resolve_relationship_condition(
194 self_alias => "\xFE", # irrelevant
195 foreign_alias => "\xFF", # irrelevant
200 # inject non-left fk-bridges from *INNER-JOINED* children (if any)
201 for my $rel (grep { $relinfo->{$_}{is_inner} } keys %$relinfo) {
202 my $ri = $relinfo->{$rel};
203 for (keys %{$ri->{fk_map}} ) {
204 # need to know source from *our* pov, hence $rel.col
205 $my_cols->{$_} ||= { via_fk => "$rel.$ri->{fk_map}{$_}" }
206 if defined $rel_cols->{$rel}{$ri->{fk_map}{$_}} # in fact selected
210 # if the parent is already defined *AND* we have an inner reverse relationship
211 # (i.e. do not exist without it) , assume all of its related FKs are selected
212 # (even if they in fact are NOT in the select list). Keep a record of what we
213 # assumed, and if any such phantom-column becomes part of our own collapser,
214 # throw everything assumed-from-parent away and replace with the collapser of
215 # the parent (whatever it may be)
216 my $assumed_from_parent;
217 if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
218 for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
219 next if exists $my_cols->{$col};
220 $my_cols->{$col} = {};
221 $assumed_from_parent->{columns}{$col}++;
225 # get colinfo for everything
227 my $ci = $self->columns_info;
228 $my_cols->{$_}{colinfo} = $ci->{$_} for keys %$my_cols;
233 # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
234 # (makes for a leaner coderef later)
236 ! $collapse_map->{-identifying_columns}
238 $args->{_parent_info}{collapser_reusable}
240 $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
243 # Still don't know how to collapse - in case we are a *single* relationship
244 # AND our parent is defined AND we have any *native* non-nullable pieces: then
245 # we are still good to go
246 # NOTE: it doesn't matter if the nonnullable set is unique or not - it will be
247 # made unique by the parents identifying cols
249 ! $collapse_map->{-identifying_columns}
251 $args->{_parent_info}{is_single}
253 @{ $args->{_parent_info}{collapse_on_idcols} }
255 ( my @native_nonnull_cols = grep {
256 $native_cols->{$_}{colinfo}
258 ! $native_cols->{$_}{colinfo}{is_nullable}
259 } keys %$native_cols )
262 $collapse_map->{-identifying_columns} = [ __unique_numlist(
263 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
265 # FIXME - we don't really need *all* of the columns, $our_nonnull_cols[0]
266 # is sufficient. However map the entire thing to engage the extra nonnull
267 # explicit checks, just to be on the safe side
268 # Remove some day in the future
271 $common_args->{_as_fq_idx}{join ('.',
272 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
281 # Still don't know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
283 ! $collapse_map->{-identifying_columns}
287 my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
289 # see if the resulting collapser relies on any implied columns,
290 # and fix stuff up if this is the case
291 my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
293 $collapse_map->{-identifying_columns} = [ __unique_numlist(
294 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
299 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
300 ( $my_cols->{$_}{via_fk} || $_ ),
303 $common_args->{_as_fq_idx}->{$fqc};
310 # Stil don't know how to collapse - keep descending down 1:1 chains - if
311 # a related non-LEFT 1:1 is resolvable - its condition will collapse us
313 unless ($collapse_map->{-identifying_columns}) {
316 for my $rel (keys %$relinfo) {
317 next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
319 if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
320 as => $rel_cols->{$rel},
321 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
322 _parent_info => { underdefined => 1 },
324 push @candidates, $rel_collapse->{-identifying_columns};
328 # get the set with least amount of columns
329 # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
330 # to a single varchar)
332 ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
336 # Stil don't know how to collapse, and we are the root node. Last ditch
337 # effort in case we are *NOT* premultiplied.
338 # Run through *each multi* all the way down, left or not, and all
339 # *left* singles (a single may become a multi underneath) . When everything
340 # gets back see if all the rels link to us definitively. If this is the
341 # case we are good - either one of them will define us, or if all are NULLs
342 # we know we are "unique" due to the "non-premultiplied" check
344 ! $collapse_map->{-identifying_columns}
346 ! $args->{premultiplied}
348 $args->{_is_top_level}
350 my (@collapse_sets, $uncollapsible_chain);
352 for my $rel (keys %$relinfo) {
354 # we already looked at these higher up
355 next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
357 if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
358 as => $rel_cols->{$rel},
359 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
360 _parent_info => { underdefined => 1 },
363 # for singles use the idcols wholesale (either there or not)
364 if ($relinfo->{$rel}{is_single}) {
365 push @collapse_sets, $clps->{-identifying_columns};
367 elsif (! $relinfo->{$rel}{fk_map}) {
368 $uncollapsible_chain = 1;
372 my $defined_cols_parent_side;
374 for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
375 my ($col) = $fq_col =~ /([^\.]+)$/;
377 $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
378 { $relinfo->{$rel}{fk_map}{$_} eq $col }
379 keys %{$relinfo->{$rel}{fk_map}}
383 if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
384 push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
387 $uncollapsible_chain = 1;
393 $uncollapsible_chain = 1;
398 unless ($uncollapsible_chain) {
399 # if we got here - we are good to go, but the construction is tricky
400 # since our children will want to include our collapse criteria - we
401 # don't give them anything (safe, since they are all collapsible on their own)
402 # in addition we record the individual collapse possibilities
403 # of all left children node collapsers, and merge them in the rowparser
405 $collapse_map->{-identifying_columns} = [];
406 $collapse_map->{-identifying_columns_variants} = [ sort {
407 (scalar @$a) <=> (scalar @$b)
411 ( sort { $b <=> $a } @$a )[0]
413 ( sort { $b <=> $a } @$b )[0]
419 # stop descending into children if we were called by a parent for first-pass
420 # and don't despair if nothing was found (there may be other parallel branches
422 if ($args->{_parent_info}{underdefined}) {
423 return $collapse_map->{-identifying_columns} ? $collapse_map : undef
425 # nothing down the chain resolved - can't calculate a collapse-map
426 elsif (! $collapse_map->{-identifying_columns}) {
427 $self->throw_exception ( sprintf
428 "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
430 @{$args->{_rel_chain}} > 1
431 ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
437 # If we got that far - we are collapsable - GREAT! Now go down all children
438 # a second time, and fill in the rest
440 $collapse_map->{-identifying_columns} = [ __unique_numlist(
441 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
442 @{ $collapse_map->{-identifying_columns} },
445 for my $rel (sort keys %$relinfo) {
447 $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
448 as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
449 _rel_chain => [ @{$args->{_rel_chain}}, $rel],
452 collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
454 rel_condition => $relinfo->{$rel}{fk_map},
456 is_optional => ! $relinfo->{$rel}{is_inner},
458 is_single => $relinfo->{$rel}{is_single},
460 # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
461 # we can safely assume that the child can not exist without us
462 rev_rel_is_optional => ( grep
463 { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
464 values %{ $self->reverse_relationship_info($rel) },
467 # if this is a 1:1 our own collapser can be used as a collapse-map
468 # (regardless of left or not)
469 collapser_reusable => (
470 $relinfo->{$rel}{is_single}
472 $relinfo->{$rel}{is_inner}
474 @{$collapse_map->{-identifying_columns}}
479 $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
480 $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
483 return $collapse_map;
486 # adding a dep on MoreUtils *just* for this is retarded
487 sub __unique_numlist {
488 sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}