1 package # hide from the pauses
2 DBIx::Class::ResultSource::RowParser;
7 use base 'DBIx::Class';
10 use List::Util qw(first max);
12 use DBIx::Class::ResultSource::RowParser::Util qw(
13 assemble_simple_parser
14 assemble_collapsing_parser
19 # Accepts one or more relationships for the current source and returns an
20 # array of column names for each of those relationships. Column names are
21 # prefixed relative to the current source, in accordance with where they appear
22 # in the supplied relationships.
23 sub _resolve_prefetch {
24 my ($self, $pre, $alias, $alias_map, $order, $pref_path) = @_;
27 if (not defined $pre or not length $pre) {
30 elsif( ref $pre eq 'ARRAY' ) {
32 map { $self->_resolve_prefetch( $_, $alias, $alias_map, $order, [ @$pref_path ] ) }
35 elsif( ref $pre eq 'HASH' ) {
38 $self->_resolve_prefetch($_, $alias, $alias_map, $order, [ @$pref_path ] ),
39 $self->related_source($_)->_resolve_prefetch(
40 $pre->{$_}, "${alias}.$_", $alias_map, $order, [ @$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 my $as = shift @{$p->{-join_aliases}};
59 my $rel_info = $self->relationship_info( $pre );
60 $self->throw_exception( $self->source_name . " has no such relationship '$pre'" )
63 my $as_prefix = ($alias =~ /^.*?\.(.+)$/ ? $1.'.' : '');
65 return map { [ "${as}.$_", "${as_prefix}${pre}.$_", ] }
66 $self->related_source($pre)->columns;
70 # Takes an arrayref of {as} dbic column aliases and the collapse and select
71 # attributes from the same $rs (the selector requirement is a temporary
72 # workaround... I hope), and returns a coderef capable of:
73 # my $me_pref_clps = $coderef->([$rs->cursor->next/all])
74 # Where the $me_pref_clps arrayref is the future argument to inflate_result()
76 # For an example of this coderef in action (and to see its guts) look at
77 # t/resultset/rowparser_internals.t
79 # This is a huge performance win, as we call the same code for every row
80 # returned from the db, thus avoiding repeated method lookups when traversing
83 # Also since the coderef is completely stateless (the returned structure is
84 # always fresh on every new invocation) this is a very good opportunity for
85 # memoization if further speed improvements are needed
87 # The way we construct this coderef is somewhat fugly, although the result is
88 # really worth it. The final coderef does not perform any kind of recursion -
89 # the entire nested structure constructor is rolled out into a single scope.
91 # In any case - the output of this thing is meticulously micro-tested, so
92 # any sort of adjustment/rewrite should be relatively easy (fsvo relatively)
95 # $args and $attrs are separated to delineate what is core collapser stuff and
96 # what is dbic $rs specific
97 my ($self, $args, $attrs) = @_;
99 die "HRI without pruning makes zero sense"
100 if ( $args->{hri_style} && ! $args->{prune_null_branches} );
103 hri_style => $args->{hri_style},
104 prune_null_branches => $args->{prune_null_branches},
106 { $args->{inflate_map}[$_] => $_ }
107 ( 0 .. $#{$args->{inflate_map}} )
111 my $check_null_columns;
113 my $src = (! $args->{collapse} ) ? assemble_simple_parser(\%common) : do {
114 my $collapse_map = $self->_resolve_collapse ({
116 # only consider real columns (not functions) during collapse resolution
117 # this check shouldn't really be here, as fucktards are not supposed to
118 # alias random crap to existing column names anyway, but still - just in
120 # FIXME !!!! - this does not yet deal with unbalanced selectors correctly
121 # (it is now trivial as the attrs specify where things go out of sync
124 { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
125 keys %{$common{val_index}}
127 premultiplied => $args->{premultiplied},
130 $check_null_columns = $collapse_map->{-identifying_columns}
131 if @{$collapse_map->{-identifying_columns}};
133 assemble_collapsing_parser({
135 collapse_map => $collapse_map,
140 $args->{eval} ? ( eval "sub $src" || die $@ ) : $src,
146 # Takes an arrayref selection list and generates a collapse-map representing
147 # row-object fold-points. Every relationship is assigned a set of unique,
148 # non-nullable columns (which may *not even be* from the same resultset)
149 # and the collapser will use this information to correctly distinguish
150 # data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
151 # for extensive RV examples
152 sub _resolve_collapse {
153 my ($self, $args, $common_args) = @_;
155 # for comprehensible error messages put ourselves at the head of the relationship chain
156 $args->{_rel_chain} ||= [ $self->source_name ];
158 # record top-level fully-qualified column index, signify toplevelness
159 unless ($common_args->{_as_fq_idx}) {
160 $common_args->{_as_fq_idx} = { %{$args->{as}} };
161 $args->{_is_top_level} = 1;
164 my ($my_cols, $rel_cols);
165 for (keys %{$args->{as}}) {
166 if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
167 $rel_cols->{$1}{$2} = 1;
170 $my_cols->{$_} = {}; # important for ||='s below
175 # run through relationships, collect metadata
176 for my $rel (keys %$rel_cols) {
177 my $inf = $self->relationship_info ($rel);
180 is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
181 is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
182 rsrc => $self->related_source($rel),
185 # FIME - need to use _resolve_cond here instead
186 my $cond = $inf->{cond};
193 ! defined first { $_ !~ /^foreign\./ } (keys %$cond)
195 ! defined first { $_ !~ /^self\./ } (values %$cond)
197 for my $f (keys %$cond) {
199 $_ =~ s/^ (?: foreign | self ) \.//x for ($f, $s);
200 $relinfo->{$rel}{fk_map}{$s} = $f;
205 # inject non-left fk-bridges from *INNER-JOINED* children (if any)
206 for my $rel (grep { $relinfo->{$_}{is_inner} } keys %$relinfo) {
207 my $ri = $relinfo->{$rel};
208 for (keys %{$ri->{fk_map}} ) {
209 # need to know source from *our* pov, hence $rel.col
210 $my_cols->{$_} ||= { via_fk => "$rel.$ri->{fk_map}{$_}" }
211 if defined $rel_cols->{$rel}{$ri->{fk_map}{$_}} # in fact selected
215 # if the parent is already defined *AND* we have an inner reverse relationship
216 # (i.e. do not exist without it) , assume all of its related FKs are selected
217 # (even if they in fact are NOT in the select list). Keep a record of what we
218 # assumed, and if any such phantom-column becomes part of our own collapser,
219 # throw everything assumed-from-parent away and replace with the collapser of
220 # the parent (whatever it may be)
221 my $assumed_from_parent;
222 if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
223 for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
224 next if exists $my_cols->{$col};
225 $my_cols->{$col} = { via_collapse => $args->{_parent_info}{collapse_on_idcols} };
226 $assumed_from_parent->{columns}{$col}++;
230 # get colinfo for everything
232 my $ci = $self->columns_info;
233 $my_cols->{$_}{colinfo} = $ci->{$_} for keys %$my_cols;
238 # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
239 # (makes for a leaner coderef later)
240 unless ($collapse_map->{-identifying_columns}) {
241 $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
242 if $args->{_parent_info}{collapser_reusable};
245 # Still don't know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
247 ! $collapse_map->{-identifying_columns}
251 my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
253 # see if the resulting collapser relies on any implied columns,
254 # and fix stuff up if this is the case
255 my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
257 $collapse_map->{-identifying_columns} = [ __unique_numlist(
258 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
263 @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
264 ( $my_cols->{$_}{via_fk} || $_ ),
267 $common_args->{_as_fq_idx}->{$fqc};
274 # Stil don't know how to collapse - keep descending down 1:1 chains - if
275 # a related non-LEFT 1:1 is resolvable - its condition will collapse us
277 unless ($collapse_map->{-identifying_columns}) {
280 for my $rel (keys %$relinfo) {
281 next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
283 if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
284 as => $rel_cols->{$rel},
285 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
286 _parent_info => { underdefined => 1 },
288 push @candidates, $rel_collapse->{-identifying_columns};
292 # get the set with least amount of columns
293 # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
294 # to a single varchar)
296 ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
300 # Stil don't know how to collapse, and we are the root node. Last ditch
301 # effort in case we are *NOT* premultiplied.
302 # Run through *each multi* all the way down, left or not, and all
303 # *left* singles (a single may become a multi underneath) . When everything
304 # gets back see if all the rels link to us definitively. If this is the
305 # case we are good - either one of them will define us, or if all are NULLs
306 # we know we are "unique" due to the "non-premultiplied" check
308 ! $collapse_map->{-identifying_columns}
310 ! $args->{premultiplied}
312 $args->{_is_top_level}
314 my (@collapse_sets, $uncollapsible_chain);
316 for my $rel (keys %$relinfo) {
318 # we already looked at these higher up
319 next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
321 if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
322 as => $rel_cols->{$rel},
323 _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
324 _parent_info => { underdefined => 1 },
327 # for singles use the idcols wholesale (either there or not)
328 if ($relinfo->{$rel}{is_single}) {
329 push @collapse_sets, $clps->{-identifying_columns};
331 elsif (! $relinfo->{$rel}{fk_map}) {
332 $uncollapsible_chain = 1;
336 my $defined_cols_parent_side;
338 for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
339 my ($col) = $fq_col =~ /([^\.]+)$/;
341 $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
342 { $relinfo->{$rel}{fk_map}{$_} eq $col }
343 keys %{$relinfo->{$rel}{fk_map}}
347 if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
348 push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
351 $uncollapsible_chain = 1;
357 $uncollapsible_chain = 1;
362 unless ($uncollapsible_chain) {
363 # if we got here - we are good to go, but the construction is tricky
364 # since our children will want to include our collapse criteria - we
365 # don't give them anything (safe, since they are all collapsible on their own)
366 # in addition we record the individual collapse possibilities
367 # of all left children node collapsers, and merge them in the rowparser
369 $collapse_map->{-identifying_columns} = [];
370 $collapse_map->{-identifying_columns_variants} = [ sort {
371 (scalar @$a) <=> (scalar @$b) or max(@$a) <=> max(@$b)
376 # stop descending into children if we were called by a parent for first-pass
377 # and don't despair if nothing was found (there may be other parallel branches
379 if ($args->{_parent_info}{underdefined}) {
380 return $collapse_map->{-identifying_columns} ? $collapse_map : undef
382 # nothing down the chain resolved - can't calculate a collapse-map
383 elsif (! $collapse_map->{-identifying_columns}) {
384 $self->throw_exception ( sprintf
385 "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
387 @{$args->{_rel_chain}} > 1
388 ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
394 # If we got that far - we are collapsable - GREAT! Now go down all children
395 # a second time, and fill in the rest
397 $collapse_map->{-identifying_columns} = [ __unique_numlist(
398 @{ $args->{_parent_info}{collapse_on_idcols}||[] },
399 @{ $collapse_map->{-identifying_columns} },
403 for my $rel (sort keys %$relinfo) {
405 $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
406 as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
407 _rel_chain => [ @{$args->{_rel_chain}}, $rel],
410 collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
412 rel_condition => $relinfo->{$rel}{fk_map},
414 is_optional => ! $relinfo->{$rel}{is_inner},
416 # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
417 # we can safely assume that the child can not exist without us
418 rev_rel_is_optional => ( first
419 { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
420 values %{ $self->reverse_relationship_info($rel) },
423 # if this is a 1:1 our own collapser can be used as a collapse-map
424 # (regardless of left or not)
425 collapser_reusable => (
426 $relinfo->{$rel}{is_single}
428 $relinfo->{$rel}{is_inner}
430 @{$collapse_map->{-identifying_columns}}
435 $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
436 $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
439 return $collapse_map;
442 # adding a dep on MoreUtils *just* for this is retarded
443 sub __unique_numlist {
444 sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}