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