Switch a couple 'no-brainer' spots to _resolve_relationship_condition
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource / RowParser.pm
1 package # hide from the pauses
2   DBIx::Class::ResultSource::RowParser;
3
4 use strict;
5 use warnings;
6
7 use base 'DBIx::Class';
8
9 use Try::Tiny;
10 use List::Util qw(first max);
11
12 use DBIx::Class::ResultSource::RowParser::Util qw(
13   assemble_simple_parser
14   assemble_collapsing_parser
15 );
16
17 use DBIx::Class::Carp;
18
19 use namespace::clean;
20
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) = @_;
26
27   # internal recursion marker
28   $pref_path ||= [];
29
30   if (not defined $pre or not length $pre) {
31     return ();
32   }
33   elsif( ref $pre eq 'ARRAY' ) {
34     map { $self->_resolve_selection_from_prefetch( $_, $alias_map, [ @$pref_path ] ) }
35       @$pre;
36   }
37   elsif( ref $pre eq 'HASH' ) {
38     map {
39       $self->_resolve_selection_from_prefetch($_, $alias_map, [ @$pref_path ] ),
40       $self->related_source($_)->_resolve_selection_from_prefetch(
41          $pre->{$_}, $alias_map, [ @$pref_path, $_] )
42     } keys %$pre;
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;
50     $p = $p->{$_} for @$pref_path, $pre;
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
57     # this shift() is critical - it is what allows prefetch => [ (foo) x 2 ] to work
58     my $src_alias = shift @{$p->{-join_aliases}};
59
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 }
70
71 sub _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   );
79
80   $_[0]->_resolve_selection_from_prefetch( $_[1], $_[3] );
81 }
82
83
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 #
108 sub _mk_row_parser {
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) = @_;
112
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
125   my $check_null_columns;
126
127   my $src = (! $args->{collapse} ) ? assemble_simple_parser(\%common) : do {
128     my $collapse_map = $self->_resolve_collapse ({
129       # FIXME
130       # only consider real columns (not functions) during collapse resolution
131       # this check shouldn't really be here, as fucktards are not supposed to
132       # alias random crap to existing column names anyway, but still - just in
133       # case
134       # FIXME !!!! - this does not yet deal with unbalanced selectors correctly
135       # (it is now trivial as the attrs specify where things go out of sync
136       # needs MOAR tests)
137       as => { map
138         { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
139         keys %{$common{val_index}}
140       },
141       premultiplied => $args->{premultiplied},
142     });
143
144     $check_null_columns = $collapse_map->{-identifying_columns}
145       if @{$collapse_map->{-identifying_columns}};
146
147     assemble_collapsing_parser({
148       %common,
149       collapse_map => $collapse_map,
150     });
151   };
152
153   utf8::upgrade($src)
154     if DBIx::Class::_ENV_::STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE;
155
156   return (
157     $args->{eval} ? ( eval "sub $src" || die $@ ) : $src,
158     $check_null_columns,
159   );
160 }
161
162
163 # Takes an arrayref selection list and generates a collapse-map representing
164 # row-object fold-points. Every relationship is assigned a set of unique,
165 # non-nullable columns (which may *not even be* from the same resultset)
166 # and the collapser will use this information to correctly distinguish
167 # data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
168 # for extensive RV examples
169 sub _resolve_collapse {
170   my ($self, $args, $common_args) = @_;
171
172   # for comprehensible error messages put ourselves at the head of the relationship chain
173   $args->{_rel_chain} ||= [ $self->source_name ];
174
175   # record top-level fully-qualified column index, signify toplevelness
176   unless ($common_args->{_as_fq_idx}) {
177     $common_args->{_as_fq_idx} = { %{$args->{as}} };
178     $args->{_is_top_level} = 1;
179   };
180
181   my ($my_cols, $rel_cols);
182   for (keys %{$args->{as}}) {
183     if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
184       $rel_cols->{$1}{$2} = 1;
185     }
186     else {
187       $my_cols->{$_} = {};  # important for ||='s below
188     }
189   }
190
191   my $relinfo;
192   # run through relationships, collect metadata
193   for my $rel (keys %$rel_cols) {
194     my $inf = $self->relationship_info ($rel);
195
196     $relinfo->{$rel} = {
197       is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
198       is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
199       rsrc => $self->related_source($rel),
200       fk_map => $self->_resolve_relationship_condition(
201         rel_name => $rel,
202         self_alias => "\xFE", # irrelevant
203         foreign_alias => "\xFF", # irrelevant
204       )->{identity_map},
205     };
206   }
207
208   # inject non-left fk-bridges from *INNER-JOINED* children (if any)
209   for my $rel (grep { $relinfo->{$_}{is_inner} } keys %$relinfo) {
210     my $ri = $relinfo->{$rel};
211     for (keys %{$ri->{fk_map}} ) {
212       # need to know source from *our* pov, hence $rel.col
213       $my_cols->{$_} ||= { via_fk => "$rel.$ri->{fk_map}{$_}" }
214         if defined $rel_cols->{$rel}{$ri->{fk_map}{$_}} # in fact selected
215     }
216   }
217
218   # if the parent is already defined *AND* we have an inner reverse relationship
219   # (i.e. do not exist without it) , assume all of its related FKs are selected
220   # (even if they in fact are NOT in the select list). Keep a record of what we
221   # assumed, and if any such phantom-column becomes part of our own collapser,
222   # throw everything assumed-from-parent away and replace with the collapser of
223   # the parent (whatever it may be)
224   my $assumed_from_parent;
225   if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
226     for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
227       next if exists $my_cols->{$col};
228       $my_cols->{$col} = { via_collapse => $args->{_parent_info}{collapse_on_idcols} };
229       $assumed_from_parent->{columns}{$col}++;
230     }
231   }
232
233   # get colinfo for everything
234   if ($my_cols) {
235     my $ci = $self->columns_info;
236     $my_cols->{$_}{colinfo} = $ci->{$_} for keys %$my_cols;
237   }
238
239   my $collapse_map;
240
241   # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
242   # (makes for a leaner coderef later)
243   unless ($collapse_map->{-identifying_columns}) {
244     $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
245       if $args->{_parent_info}{collapser_reusable};
246   }
247
248   # Still don't know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
249   if (
250     ! $collapse_map->{-identifying_columns}
251       and
252     $my_cols
253       and
254     my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
255   ) {
256     # see if the resulting collapser relies on any implied columns,
257     # and fix stuff up if this is the case
258     my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
259
260     $collapse_map->{-identifying_columns} = [ __unique_numlist(
261       @{ $args->{_parent_info}{collapse_on_idcols}||[] },
262
263       (map
264         {
265           my $fqc = join ('.',
266             @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
267             ( $my_cols->{$_}{via_fk} || $_ ),
268           );
269
270           $common_args->{_as_fq_idx}->{$fqc};
271         }
272         @reduced_set
273       ),
274     )];
275   }
276
277   # Stil don't know how to collapse - keep descending down 1:1 chains - if
278   # a related non-LEFT 1:1 is resolvable - its condition will collapse us
279   # too
280   unless ($collapse_map->{-identifying_columns}) {
281     my @candidates;
282
283     for my $rel (keys %$relinfo) {
284       next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
285
286       if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
287         as => $rel_cols->{$rel},
288         _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
289         _parent_info => { underdefined => 1 },
290       }, $common_args)) {
291         push @candidates, $rel_collapse->{-identifying_columns};
292       }
293     }
294
295     # get the set with least amount of columns
296     # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
297     # to a single varchar)
298     if (@candidates) {
299       ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
300     }
301   }
302
303   # Stil don't know how to collapse, and we are the root node. Last ditch
304   # effort in case we are *NOT* premultiplied.
305   # Run through *each multi* all the way down, left or not, and all
306   # *left* singles (a single may become a multi underneath) . When everything
307   # gets back see if all the rels link to us definitively. If this is the
308   # case we are good - either one of them will define us, or if all are NULLs
309   # we know we are "unique" due to the "non-premultiplied" check
310   if (
311     ! $collapse_map->{-identifying_columns}
312       and
313     ! $args->{premultiplied}
314       and
315     $args->{_is_top_level}
316   ) {
317     my (@collapse_sets, $uncollapsible_chain);
318
319     for my $rel (keys %$relinfo) {
320
321       # we already looked at these higher up
322       next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
323
324       if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
325         as => $rel_cols->{$rel},
326         _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
327         _parent_info => { underdefined => 1 },
328       }, $common_args) ) {
329
330         # for singles use the idcols wholesale (either there or not)
331         if ($relinfo->{$rel}{is_single}) {
332           push @collapse_sets, $clps->{-identifying_columns};
333         }
334         elsif (! $relinfo->{$rel}{fk_map}) {
335           $uncollapsible_chain = 1;
336           last;
337         }
338         else {
339           my $defined_cols_parent_side;
340
341           for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
342             my ($col) = $fq_col =~ /([^\.]+)$/;
343
344             $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
345               { $relinfo->{$rel}{fk_map}{$_} eq $col }
346               keys %{$relinfo->{$rel}{fk_map}}
347             ;
348           }
349
350           if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
351             push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
352           }
353           else {
354             $uncollapsible_chain = 1;
355             last;
356           }
357         }
358       }
359       else {
360         $uncollapsible_chain = 1;
361         last;
362       }
363     }
364
365     unless ($uncollapsible_chain) {
366       # if we got here - we are good to go, but the construction is tricky
367       # since our children will want to include our collapse criteria - we
368       # don't give them anything (safe, since they are all collapsible on their own)
369       # in addition we record the individual collapse possibilities
370       # of all left children node collapsers, and merge them in the rowparser
371       # coderef later
372       $collapse_map->{-identifying_columns} = [];
373       $collapse_map->{-identifying_columns_variants} = [ sort {
374         (scalar @$a) <=> (scalar @$b) or max(@$a) <=> max(@$b)
375       } @collapse_sets ];
376     }
377   }
378
379   # stop descending into children if we were called by a parent for first-pass
380   # and don't despair if nothing was found (there may be other parallel branches
381   # to dive into)
382   if ($args->{_parent_info}{underdefined}) {
383     return $collapse_map->{-identifying_columns} ? $collapse_map : undef
384   }
385   # nothing down the chain resolved - can't calculate a collapse-map
386   elsif (! $collapse_map->{-identifying_columns}) {
387     $self->throw_exception ( sprintf
388       "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
389       $self->source_name,
390       @{$args->{_rel_chain}} > 1
391         ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
392         : ''
393       ,
394     );
395   }
396
397   # If we got that far - we are collapsable - GREAT! Now go down all children
398   # a second time, and fill in the rest
399
400   $collapse_map->{-identifying_columns} = [ __unique_numlist(
401     @{ $args->{_parent_info}{collapse_on_idcols}||[] },
402     @{ $collapse_map->{-identifying_columns} },
403   )];
404
405   my @id_sets;
406   for my $rel (sort keys %$relinfo) {
407
408     $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
409       as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
410       _rel_chain => [ @{$args->{_rel_chain}}, $rel],
411       _parent_info => {
412         # shallow copy
413         collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
414
415         rel_condition => $relinfo->{$rel}{fk_map},
416
417         is_optional => ! $relinfo->{$rel}{is_inner},
418
419         # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
420         # we can safely assume that the child can not exist without us
421         rev_rel_is_optional => ( first
422           { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
423           values %{ $self->reverse_relationship_info($rel) },
424         ) ? 0 : 1,
425
426         # if this is a 1:1 our own collapser can be used as a collapse-map
427         # (regardless of left or not)
428         collapser_reusable => (
429           $relinfo->{$rel}{is_single}
430             &&
431           $relinfo->{$rel}{is_inner}
432             &&
433           @{$collapse_map->{-identifying_columns}}
434         ) ? 1 : 0,
435       },
436     }, $common_args );
437
438     $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
439     $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
440   }
441
442   return $collapse_map;
443 }
444
445 # adding a dep on MoreUtils *just* for this is retarded
446 sub __unique_numlist {
447   sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}
448 }
449
450 1;