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