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