Explicitly disallow redirection of has_many columns to main object
[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 use B 'perlstring';
12
13 use DBIx::Class::ResultSource::RowParser::Util qw(
14   assemble_simple_parser
15   assemble_collapsing_parser
16 );
17
18 use namespace::clean;
19
20 # Accepts one or more relationships for the current source and returns an
21 # array of column names for each of those relationships. Column names are
22 # prefixed relative to the current source, in accordance with where they appear
23 # in the supplied relationships.
24 sub _resolve_prefetch {
25   my ($self, $pre, $alias, $alias_map, $order, $pref_path) = @_;
26   $pref_path ||= [];
27
28   if (not defined $pre or not length $pre) {
29     return ();
30   }
31   elsif( ref $pre eq 'ARRAY' ) {
32     return
33       map { $self->_resolve_prefetch( $_, $alias, $alias_map, $order, [ @$pref_path ] ) }
34         @$pre;
35   }
36   elsif( ref $pre eq 'HASH' ) {
37     my @ret =
38     map {
39       $self->_resolve_prefetch($_, $alias, $alias_map, $order, [ @$pref_path ] ),
40       $self->related_source($_)->_resolve_prefetch(
41          $pre->{$_}, "${alias}.$_", $alias_map, $order, [ @$pref_path, $_] )
42     } keys %$pre;
43     return @ret;
44   }
45   elsif( ref $pre ) {
46     $self->throw_exception(
47       "don't know how to resolve prefetch reftype ".ref($pre));
48   }
49   else {
50     my $p = $alias_map;
51     $p = $p->{$_} for (@$pref_path, $pre);
52
53     $self->throw_exception (
54       "Unable to resolve prefetch '$pre' - join alias map does not contain an entry for path: "
55       . join (' -> ', @$pref_path, $pre)
56     ) if (ref $p->{-join_aliases} ne 'ARRAY' or not @{$p->{-join_aliases}} );
57
58     my $as = shift @{$p->{-join_aliases}};
59
60     my $rel_info = $self->relationship_info( $pre );
61     $self->throw_exception( $self->source_name . " has no such relationship '$pre'" )
62       unless $rel_info;
63
64     my $as_prefix = ($alias =~ /^.*?\.(.+)$/ ? $1.'.' : '');
65
66     return map { [ "${as}.$_", "${as_prefix}${pre}.$_", ] }
67       $self->related_source($pre)->columns;
68   }
69 }
70
71 # Takes an arrayref of {as} dbic column aliases and the collapse and select
72 # attributes from the same $rs (the selector requirement is a temporary
73 # workaround... I hope), and returns a coderef capable of:
74 # my $me_pref_clps = $coderef->([$rs->cursor->next/all])
75 # Where the $me_pref_clps arrayref is the future argument to inflate_result()
76 #
77 # For an example of this coderef in action (and to see its guts) look at
78 # t/resultset/rowparser_internals.t
79 #
80 # This is a huge performance win, as we call the same code for every row
81 # returned from the db, thus avoiding repeated method lookups when traversing
82 # relationships
83 #
84 # Also since the coderef is completely stateless (the returned structure is
85 # always fresh on every new invocation) this is a very good opportunity for
86 # memoization if further speed improvements are needed
87 #
88 # The way we construct this coderef is somewhat fugly, although the result is
89 # really worth it. The final coderef does not perform any kind of recursion -
90 # the entire nested structure constructor is rolled out into a single scope.
91 #
92 # In any case - the output of this thing is meticulously micro-tested, so
93 # any sort of adjustment/rewrite should be relatively easy (fsvo relatively)
94 #
95 sub _mk_row_parser {
96   # $args and $attrs are seperated to delineate what is core collapser stuff and
97   # what is dbic $rs specific
98   my ($self, $args, $attrs) = @_;
99
100   die "HRI without pruning makes zero sense"
101   if ( $args->{hri_style} && ! $args->{prune_null_branches} );
102
103   my %common = (
104     hri_style => $args->{hri_style},
105     prune_null_branches => $args->{prune_null_branches},
106     val_index => { map
107       { $args->{inflate_map}[$_] => $_ }
108       ( 0 .. $#{$args->{inflate_map}} )
109     },
110   );
111
112   my $src = $args->{collapse}
113     ? assemble_collapsing_parser({
114       %common,
115       collapse_map => $self->_resolve_collapse ({
116         # FIXME
117         # only consider real columns (not functions) during collapse resolution
118         # this check shouldn't really be here, as fucktards are not supposed to
119         # alias random crap to existing column names anyway, but still - just in
120         # case
121         # FIXME !!!! - this does not yet deal with unbalanced selectors correctly
122         # (it is now trivial as the attrs specify where things go out of sync
123         # needs MOAR tests)
124         as => { map
125           { ref $attrs->{select}[$common{val_index}{$_}] ? () : ( $_ => $common{val_index}{$_} ) }
126           keys %{$common{val_index}}
127         },
128         premultiplied => $args->{premultiplied},
129       })
130     })
131     : assemble_simple_parser(
132       \%common
133     )
134   ;
135
136   return $args->{eval}
137     ? ( eval "sub $src" || die $@ )
138     : $src
139   ;
140 }
141
142
143 # Takes an arrayref selection list and generates a collapse-map representing
144 # row-object fold-points. Every relationship is assigned a set of unique,
145 # non-nullable columns (which may *not even be* from the same resultset)
146 # and the collapser will use this information to correctly distinguish
147 # data of individual to-be-row-objects. See t/resultset/rowparser_internals.t
148 # for extensive RV examples
149 sub _resolve_collapse {
150   my ($self, $args, $common_args) = @_;
151
152   # for comprehensible error messages put ourselves at the head of the relationship chain
153   $args->{_rel_chain} ||= [ $self->source_name ];
154
155   # record top-level fully-qualified column index, signify toplevelness
156   unless ($common_args->{_as_fq_idx}) {
157     $common_args->{_as_fq_idx} = { %{$args->{as}} };
158     $args->{_is_top_level} = 1;
159   };
160
161   my ($my_cols, $rel_cols);
162   for (keys %{$args->{as}}) {
163     if ($_ =~ /^ ([^\.]+) \. (.+) /x) {
164       $rel_cols->{$1}{$2} = 1;
165     }
166     else {
167       $my_cols->{$_} = {};  # important for ||='s below
168     }
169   }
170
171   my $relinfo;
172   # run through relationships, collect metadata
173   for my $rel (keys %$rel_cols) {
174     my $inf = $self->relationship_info ($rel);
175
176     $relinfo->{$rel} = {
177       is_single => ( $inf->{attrs}{accessor} && $inf->{attrs}{accessor} ne 'multi' ),
178       is_inner => ( ( $inf->{attrs}{join_type} || '' ) !~ /^left/i),
179       rsrc => $self->related_source($rel),
180     };
181
182     # FIME - need to use _resolve_cond here instead
183     my $cond = $inf->{cond};
184
185     if (
186       ref $cond eq 'HASH'
187         and
188       keys %$cond
189         and
190       ! defined first { $_ !~ /^foreign\./ } (keys %$cond)
191         and
192       ! defined first { $_ !~ /^self\./ } (values %$cond)
193     ) {
194       for my $f (keys %$cond) {
195         my $s = $cond->{$f};
196         $_ =~ s/^ (?: foreign | self ) \.//x for ($f, $s);
197         $relinfo->{$rel}{fk_map}{$s} = $f;
198       }
199     }
200   }
201
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
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
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;
219   if ( ! $args->{_parent_info}{underdefined} and ! $args->{_parent_info}{rev_rel_is_optional} ) {
220     for my $col ( values %{$args->{_parent_info}{rel_condition} || {}} ) {
221       next if exists $my_cols->{$col};
222       $my_cols->{$col} = { via_collapse => $args->{_parent_info}{collapse_on_idcols} };
223       $assumed_from_parent->{columns}{$col}++;
224     }
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
235   # first try to reuse the parent's collapser (i.e. reuse collapser over 1:1)
236   # (makes for a leaner coderef later)
237   unless ($collapse_map->{-identifying_columns}) {
238     $collapse_map->{-identifying_columns} = $args->{_parent_info}{collapse_on_idcols}
239       if $args->{_parent_info}{collapser_reusable};
240   }
241
242   # Still dont know how to collapse - try to resolve based on our columns (plus already inserted FK bridges)
243   if (
244     ! $collapse_map->{-identifying_columns}
245       and
246     $my_cols
247       and
248     my $idset = $self->_identifying_column_set ({map { $_ => $my_cols->{$_}{colinfo} } keys %$my_cols})
249   ) {
250     # see if the resulting collapser relies on any implied columns,
251     # and fix stuff up if this is the case
252     my @reduced_set = grep { ! $assumed_from_parent->{columns}{$_} } @$idset;
253
254     $collapse_map->{-identifying_columns} = [ __unique_numlist(
255       @{ $args->{_parent_info}{collapse_on_idcols}||[] },
256
257       (map
258         {
259           my $fqc = join ('.',
260             @{$args->{_rel_chain}}[1 .. $#{$args->{_rel_chain}}],
261             ( $my_cols->{$_}{via_fk} || $_ ),
262           );
263
264           $common_args->{_as_fq_idx}->{$fqc};
265         }
266         @reduced_set
267       ),
268     )];
269   }
270
271   # Stil don't know how to collapse - keep descending down 1:1 chains - if
272   # a related non-LEFT 1:1 is resolvable - its condition will collapse us
273   # too
274   unless ($collapse_map->{-identifying_columns}) {
275     my @candidates;
276
277     for my $rel (keys %$relinfo) {
278       next unless ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
279
280       if ( my $rel_collapse = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
281         as => $rel_cols->{$rel},
282         _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
283         _parent_info => { underdefined => 1 },
284       }, $common_args)) {
285         push @candidates, $rel_collapse->{-identifying_columns};
286       }
287     }
288
289     # get the set with least amount of columns
290     # FIXME - maybe need to implement a data type order as well (i.e. prefer several ints
291     # to a single varchar)
292     if (@candidates) {
293       ($collapse_map->{-identifying_columns}) = sort { scalar @$a <=> scalar @$b } (@candidates);
294     }
295   }
296
297   # Stil don't know how to collapse, and we are the root node. Last ditch
298   # effort in case we are *NOT* premultiplied.
299   # Run through *each multi* all the way down, left or not, and all
300   # *left* singles (a single may become a multi underneath) . When everything
301   # gets back see if all the rels link to us definitively. If this is the
302   # case we are good - either one of them will define us, or if all are NULLs
303   # we know we are "unique" due to the "non-premultiplied" check
304   if (
305     ! $collapse_map->{-identifying_columns}
306       and
307     ! $args->{premultiplied}
308       and
309     $args->{_is_top_level}
310   ) {
311     my (@collapse_sets, $uncollapsible_chain);
312
313     for my $rel (keys %$relinfo) {
314
315       # we already looked at these higher up
316       next if ($relinfo->{$rel}{is_single} && $relinfo->{$rel}{is_inner});
317
318       if (my $clps = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
319         as => $rel_cols->{$rel},
320         _rel_chain => [ @{$args->{_rel_chain}}, $rel ],
321         _parent_info => { underdefined => 1 },
322       }, $common_args) ) {
323
324         # for singles use the idcols wholesale (either there or not)
325         if ($relinfo->{$rel}{is_single}) {
326           push @collapse_sets, $clps->{-identifying_columns};
327         }
328         elsif (! $relinfo->{$rel}{fk_map}) {
329           $uncollapsible_chain = 1;
330           last;
331         }
332         else {
333           my $defined_cols_parent_side;
334
335           for my $fq_col ( grep { /^$rel\.[^\.]+$/ } keys %{$args->{as}} ) {
336             my ($col) = $fq_col =~ /([^\.]+)$/;
337
338             $defined_cols_parent_side->{$_} = $args->{as}{$fq_col} for grep
339               { $relinfo->{$rel}{fk_map}{$_} eq $col }
340               keys %{$relinfo->{$rel}{fk_map}}
341             ;
342           }
343
344           if (my $set = $self->_identifying_column_set([ keys %$defined_cols_parent_side ]) ) {
345             push @collapse_sets, [ sort map { $defined_cols_parent_side->{$_} } @$set ];
346           }
347           else {
348             $uncollapsible_chain = 1;
349             last;
350           }
351         }
352       }
353       else {
354         $uncollapsible_chain = 1;
355         last;
356       }
357     }
358
359     unless ($uncollapsible_chain) {
360       # if we got here - we are good to go, but the construction is tricky
361       # since our children will want to include our collapse criteria - we
362       # don't give them anything (safe, since they are all collapsible on their own)
363       # in addition we record the individual collapse posibilities
364       # of all left children node collapsers, and merge them in the rowparser
365       # coderef later
366       $collapse_map->{-identifying_columns} = [];
367       $collapse_map->{-identifying_columns_variants} = [ sort {
368         (scalar @$a) <=> (scalar @$b) or max(@$a) <=> max(@$b)
369       } @collapse_sets ];
370     }
371   }
372
373   # stop descending into children if we were called by a parent for first-pass
374   # and don't despair if nothing was found (there may be other parallel branches
375   # to dive into)
376   if ($args->{_parent_info}{underdefined}) {
377     return $collapse_map->{-identifying_columns} ? $collapse_map : undef
378   }
379   # nothing down the chain resolved - can't calculate a collapse-map
380   elsif (! $collapse_map->{-identifying_columns}) {
381     $self->throw_exception ( sprintf
382       "Unable to calculate a definitive collapse column set for %s%s: fetch more unique non-nullable columns",
383       $self->source_name,
384       @{$args->{_rel_chain}} > 1
385         ? sprintf (' (last member of the %s chain)', join ' -> ', @{$args->{_rel_chain}} )
386         : ''
387       ,
388     );
389   }
390
391   # If we got that far - we are collapsable - GREAT! Now go down all children
392   # a second time, and fill in the rest
393
394   $collapse_map->{-identifying_columns} = [ __unique_numlist(
395     @{ $args->{_parent_info}{collapse_on_idcols}||[] },
396     @{ $collapse_map->{-identifying_columns} },
397   )];
398
399   my @id_sets;
400   for my $rel (sort keys %$relinfo) {
401
402     $collapse_map->{$rel} = $relinfo->{$rel}{rsrc}->_resolve_collapse ({
403       as => { map { $_ => 1 } ( keys %{$rel_cols->{$rel}} ) },
404       _rel_chain => [ @{$args->{_rel_chain}}, $rel],
405       _parent_info => {
406         # shallow copy
407         collapse_on_idcols => [ @{$collapse_map->{-identifying_columns}} ],
408
409         rel_condition => $relinfo->{$rel}{fk_map},
410
411         is_optional => ! $relinfo->{$rel}{is_inner},
412
413         # if there is at least one *inner* reverse relationship which is HASH-based (equality only)
414         # we can safely assume that the child can not exist without us
415         rev_rel_is_optional => ( first
416           { ref $_->{cond} eq 'HASH' and ($_->{attrs}{join_type}||'') !~ /^left/i }
417           values %{ $self->reverse_relationship_info($rel) },
418         ) ? 0 : 1,
419
420         # if this is a 1:1 our own collapser can be used as a collapse-map
421         # (regardless of left or not)
422         collapser_reusable => (
423           $relinfo->{$rel}{is_single}
424             &&
425           $relinfo->{$rel}{is_inner}
426             &&
427           @{$collapse_map->{-identifying_columns}}
428         ) ? 1 : 0,
429       },
430     }, $common_args );
431
432     $collapse_map->{$rel}{-is_single} = 1 if $relinfo->{$rel}{is_single};
433     $collapse_map->{$rel}{-is_optional} ||= 1 unless $relinfo->{$rel}{is_inner};
434   }
435
436   return $collapse_map;
437 }
438
439 # adding a dep on MoreUtils *just* for this is retarded
440 sub __unique_numlist {
441   sort { $a <=> $b } keys %{ {map { $_ => 1 } @_ }}
442 }
443
444 1;