There is no point of ordering the insides of a complex prefetch without a limit
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBIHacks.pm
CommitLineData
c443438f 1package #hide from PAUSE
2 DBIx::Class::Storage::DBIHacks;
d28bb90d 3
4#
5# This module contains code that should never have seen the light of day,
6# does not belong in the Storage, or is otherwise unfit for public
6a6394f1 7# display. The arrival of SQLA2 should immediately obsolete 90% of this
d28bb90d 8#
9
10use strict;
11use warnings;
12
13use base 'DBIx::Class::Storage';
14use mro 'c3';
15
6298a324 16use List::Util 'first';
17use Scalar::Util 'blessed';
ea5c7509 18use Sub::Name 'subname';
6298a324 19use namespace::clean;
d28bb90d 20
21#
052e8431 22# This code will remove non-selecting/non-restricting joins from
4b1b5ea3 23# {from} specs, aiding the RDBMS query optimizer
052e8431 24#
25sub _prune_unused_joins {
ea95892e 26 my $self = shift;
97e130fa 27 my ($from, $select, $where, $attrs, $ignore_multiplication) = @_;
052e8431 28
ea95892e 29 return $from unless $self->_use_join_optimizer;
30
052e8431 31 if (ref $from ne 'ARRAY' || ref $from->[0] ne 'HASH' || ref $from->[1] ne 'ARRAY') {
32 return $from; # only standard {from} specs are supported
33 }
34
4b1b5ea3 35 my $aliastypes = $self->_resolve_aliastypes_from_select_args(@_);
36
97e130fa 37 # don't care
38 delete $aliastypes->{joining};
39
4b1b5ea3 40 # a grouped set will not be affected by amount of rows. Thus any
41 # {multiplying} joins can go
97e130fa 42 delete $aliastypes->{multiplying}
43 if $ignore_multiplication or $attrs->{group_by};
4b1b5ea3 44
052e8431 45 my @newfrom = $from->[0]; # FROM head is always present
46
a4812caa 47 my %need_joins;
97e130fa 48
a4812caa 49 for (values %$aliastypes) {
50 # add all requested aliases
51 $need_joins{$_} = 1 for keys %$_;
52
53 # add all their parents (as per joinpath which is an AoH { table => alias })
97e130fa 54 $need_joins{$_} = 1 for map { values %$_ } map { @{$_->{-parents}} } values %$_;
a4812caa 55 }
97e130fa 56
052e8431 57 for my $j (@{$from}[1..$#$from]) {
539ffe87 58 push @newfrom, $j if (
4b1b5ea3 59 (! $j->[0]{-alias}) # legacy crap
539ffe87 60 ||
61 $need_joins{$j->[0]{-alias}}
62 );
052e8431 63 }
64
65 return \@newfrom;
66}
67
052e8431 68#
d28bb90d 69# This is the code producing joined subqueries like:
8273e845 70# SELECT me.*, other.* FROM ( SELECT me.* FROM ... ) JOIN other ON ...
d28bb90d 71#
72sub _adjust_select_args_for_complex_prefetch {
73 my ($self, $from, $select, $where, $attrs) = @_;
74
75 $self->throw_exception ('Nothing to prefetch... how did we get here?!')
a59246c3 76 if not @{$attrs->{_prefetch_selector_range}||[]};
d28bb90d 77
78 $self->throw_exception ('Complex prefetches are not supported on resultsets with a custom from attribute')
79 if (ref $from ne 'ARRAY' || ref $from->[0] ne 'HASH' || ref $from->[1] ne 'ARRAY');
80
d28bb90d 81 # generate inner/outer attribute lists, remove stuff that doesn't apply
82 my $outer_attrs = { %$attrs };
83 delete $outer_attrs->{$_} for qw/where bind rows offset group_by having/;
84
186ba34c 85 my $inner_attrs = { %$attrs };
908aa1bb 86 delete $inner_attrs->{$_} for qw/for collapse _prefetch_selector_range select as/;
d28bb90d 87
4df1400e 88 # there is no point of ordering the insides if there is no limit
89 delete $inner_attrs->{order_by} if (
90 delete $inner_attrs->{_order_is_artificial}
91 or
92 ! $inner_attrs->{rows}
93 );
946f6260 94
d28bb90d 95 # generate the inner/outer select lists
96 # for inside we consider only stuff *not* brought in by the prefetch
97 # on the outside we substitute any function for its alias
98 my $outer_select = [ @$select ];
97e130fa 99 my $inner_select;
36fd7f07 100
97e130fa 101 my ($root_node, $root_node_offset);
27e0370d 102
103 for my $i (0 .. $#$from) {
104 my $node = $from->[$i];
105 my $h = (ref $node eq 'HASH') ? $node
106 : (ref $node eq 'ARRAY' and ref $node->[0] eq 'HASH') ? $node->[0]
107 : next
108 ;
109
97e130fa 110 if ( ($h->{-alias}||'') eq $attrs->{alias} and $h->{-rsrc} ) {
111 $root_node = $h;
112 $root_node_offset = $i;
27e0370d 113 last;
114 }
115 }
116
117 $self->throw_exception ('Complex prefetches are not supported on resultsets with a custom from attribute')
97e130fa 118 unless $root_node;
27e0370d 119
120 # use the heavy duty resolver to take care of aliased/nonaliased naming
121 my $colinfo = $self->_resolve_column_info($from);
122 my $selected_root_columns;
123
36fd7f07 124 my ($p_start, $p_end) = @{$outer_attrs->{_prefetch_selector_range}};
125 for my $i (0 .. $p_start - 1, $p_end + 1 .. $#$outer_select) {
d28bb90d 126 my $sel = $outer_select->[$i];
127
128 if (ref $sel eq 'HASH' ) {
129 $sel->{-as} ||= $attrs->{as}[$i];
130 $outer_select->[$i] = join ('.', $attrs->{alias}, ($sel->{-as} || "inner_column_$i") );
131 }
27e0370d 132 elsif (! ref $sel and my $ci = $colinfo->{$sel}) {
133 $selected_root_columns->{$ci->{-colname}} = 1;
134 }
d28bb90d 135
136 push @$inner_select, $sel;
bb9bffea 137
138 push @{$inner_attrs->{as}}, $attrs->{as}[$i];
d28bb90d 139 }
140
97e130fa 141 # We will need to fetch all native columns in the inner subquery, which may
142 # be a part of an *outer* join condition, or an order_by (which needs to be
143 # preserved outside)
144 # We can not just fetch everything because a potential has_many restricting
145 # join collapse *will not work* on heavy data types.
146 my $connecting_aliastypes = $self->_resolve_aliastypes_from_select_args(
147 [grep { ref($_) eq 'ARRAY' or ref($_) eq 'HASH' } @{$from}[$root_node_offset .. $#$from]],
148 [],
149 $where,
150 $inner_attrs
151 );
152
153 for (sort map { keys %{$_->{-seen_columns}||{}} } map { values %$_ } values %$connecting_aliastypes) {
154 my $ci = $colinfo->{$_} or next;
155 if (
156 $ci->{-source_alias} eq $attrs->{alias}
157 and
158 ! $selected_root_columns->{$ci->{-colname}}++
159 ) {
160 # adding it to both to keep limits not supporting dark selectors happy
161 push @$inner_select, $ci->{-fq_colname};
162 push @{$inner_attrs->{as}}, $ci->{-fq_colname};
27e0370d 163 }
164 }
165
ea95892e 166 # construct the inner $from and lock it in a subquery
48580715 167 # we need to prune first, because this will determine if we need a group_by below
97e130fa 168 # throw away all non-selecting, non-restricting multijoins
169 # (since we def. do not care about multiplication those inside the subquery)
6395604e 170 my $inner_subq = do {
ea95892e 171
172 # must use it here regardless of user requests
173 local $self->{_use_join_optimizer} = 1;
174
97e130fa 175 # throw away multijoins since we def. do not care about those inside the subquery
176 my $inner_from = $self->_prune_unused_joins ($from, $inner_select, $where, $inner_attrs, 'ignore_multiplication');
ea95892e 177
887a0aef 178 my $inner_aliastypes =
179 $self->_resolve_aliastypes_from_select_args( $inner_from, $inner_select, $where, $inner_attrs );
180
a4812caa 181 # we need to simulate collapse in the subq if a multiplying join is pulled
182 # by being a non-selecting restrictor
0a3441ee 183 if (
184 ! $inner_attrs->{group_by}
185 and
887a0aef 186 first {
187 $inner_aliastypes->{restricting}{$_}
188 and
189 ! $inner_aliastypes->{selecting}{$_}
190 } ( keys %{$inner_aliastypes->{multiplying}||{}} )
0a3441ee 191 ) {
14e26c5f 192 my $unprocessed_order_chunks;
193 ($inner_attrs->{group_by}, $unprocessed_order_chunks) = $self->_group_over_selection (
0a3441ee 194 $inner_from, $inner_select, $inner_attrs->{order_by}
195 );
14e26c5f 196
197 $self->throw_exception (
198 'A required group_by clause could not be constructed automatically due to a complex '
199 . 'order_by criteria. Either order_by columns only (no functions) or construct a suitable '
200 . 'group_by by hand'
201 ) if $unprocessed_order_chunks;
0a3441ee 202 }
d28bb90d 203
ea95892e 204 # we already optimized $inner_from above
97e130fa 205 # and already local()ized
206 $self->{_use_join_optimizer} = 0;
d28bb90d 207
ea95892e 208 # generate the subquery
6395604e 209 $self->_select_args_to_query (
ea95892e 210 $inner_from,
211 $inner_select,
212 $where,
213 $inner_attrs,
214 );
d28bb90d 215 };
216
217 # Generate the outer from - this is relatively easy (really just replace
218 # the join slot with the subquery), with a major caveat - we can not
219 # join anything that is non-selecting (not part of the prefetch), but at
220 # the same time is a multi-type relationship, as it will explode the result.
221 #
222 # There are two possibilities here
223 # - either the join is non-restricting, in which case we simply throw it away
224 # - it is part of the restrictions, in which case we need to collapse the outer
225 # result by tackling yet another group_by to the outside of the query
226
27e0370d 227 # work on a shallow copy
052e8431 228 $from = [ @$from ];
052e8431 229
d28bb90d 230 my @outer_from;
53c29913 231
27e0370d 232 # we may not be the head
97e130fa 233 if ($root_node_offset) {
27e0370d 234 # first generate the outer_from, up to the substitution point
97e130fa 235 @outer_from = splice @$from, 0, $root_node_offset;
27e0370d 236
237 push @outer_from, [
238 {
239 -alias => $attrs->{alias},
97e130fa 240 -rsrc => $root_node->{-rsrc},
27e0370d 241 $attrs->{alias} => $inner_subq,
242 },
97e130fa 243 @{$from->[0]}[1 .. $#{$from->[0]}],
27e0370d 244 ];
245 }
246 else {
27e0370d 247 @outer_from = {
248 -alias => $attrs->{alias},
249 -rsrc => $root_node->{-rsrc},
250 $attrs->{alias} => $inner_subq,
251 };
d28bb90d 252 }
253
97e130fa 254 shift @$from; # it's replaced in @outer_from already
255
ea95892e 256 # scan the *remaining* from spec against different attributes, and see which joins are needed
052e8431 257 # in what role
258 my $outer_aliastypes =
539ffe87 259 $self->_resolve_aliastypes_from_select_args( $from, $outer_select, $where, $outer_attrs );
052e8431 260
a4812caa 261 # unroll parents
262 my ($outer_select_chain, $outer_restrict_chain) = map { +{
97e130fa 263 map { $_ => 1 } map { values %$_} map { @{$_->{-parents}} } values %{ $outer_aliastypes->{$_} }
a4812caa 264 } } qw/selecting restricting/;
265
d28bb90d 266 # see what's left - throw away if not selecting/restricting
a4812caa 267 # also throw in a group_by if a non-selecting multiplier,
268 # to guard against cross-join explosions
36fd7f07 269 my $need_outer_group_by;
d28bb90d 270 while (my $j = shift @$from) {
271 my $alias = $j->[0]{-alias};
272
a4812caa 273 if (
274 $outer_select_chain->{$alias}
275 ) {
276 push @outer_from, $j
d28bb90d 277 }
a4812caa 278 elsif ($outer_restrict_chain->{$alias}) {
d28bb90d 279 push @outer_from, $j;
a4812caa 280 $need_outer_group_by ||= $outer_aliastypes->{multiplying}{$alias} ? 1 : 0;
d28bb90d 281 }
282 }
283
36fd7f07 284 if ($need_outer_group_by and ! $outer_attrs->{group_by}) {
285
286 my $unprocessed_order_chunks;
287 ($outer_attrs->{group_by}, $unprocessed_order_chunks) = $self->_group_over_selection (
288 \@outer_from, $outer_select, $outer_attrs->{order_by}
289 );
290
291 $self->throw_exception (
292 'A required group_by clause could not be constructed automatically due to a complex '
293 . 'order_by criteria. Either order_by columns only (no functions) or construct a suitable '
294 . 'group_by by hand'
295 ) if $unprocessed_order_chunks;
296
297 }
298
d28bb90d 299 # This is totally horrific - the $where ends up in both the inner and outer query
300 # Unfortunately not much can be done until SQLA2 introspection arrives, and even
301 # then if where conditions apply to the *right* side of the prefetch, you may have
302 # to both filter the inner select (e.g. to apply a limit) and then have to re-filter
303 # the outer select to exclude joins you didin't want in the first place
304 #
305 # OTOH it can be seen as a plus: <ash> (notes that this query would make a DBA cry ;)
306 return (\@outer_from, $outer_select, $where, $outer_attrs);
307}
308
1a736efb 309#
310# I KNOW THIS SUCKS! GET SQLA2 OUT THE DOOR SO THIS CAN DIE!
311#
ad630f4b 312# Due to a lack of SQLA2 we fall back to crude scans of all the
313# select/where/order/group attributes, in order to determine what
314# aliases are neded to fulfill the query. This information is used
315# throughout the code to prune unnecessary JOINs from the queries
316# in an attempt to reduce the execution time.
317# Although the method is pretty horrific, the worst thing that can
1a736efb 318# happen is for it to fail due to some scalar SQL, which in turn will
319# result in a vocal exception.
539ffe87 320sub _resolve_aliastypes_from_select_args {
052e8431 321 my ( $self, $from, $select, $where, $attrs ) = @_;
546f1cd9 322
ad630f4b 323 $self->throw_exception ('Unable to analyze custom {from}')
324 if ref $from ne 'ARRAY';
546f1cd9 325
ad630f4b 326 # what we will return
964a3c71 327 my $aliases_by_type;
546f1cd9 328
ad630f4b 329 # see what aliases are there to work with
330 my $alias_list;
539ffe87 331 for (@$from) {
332 my $j = $_;
ad630f4b 333 $j = $j->[0] if ref $j eq 'ARRAY';
539ffe87 334 my $al = $j->{-alias}
335 or next;
336
337 $alias_list->{$al} = $j;
97e130fa 338 $aliases_by_type->{multiplying}{$al} ||= { -parents => $j->{-join_path}||[] } if (
a4812caa 339 # not array == {from} head == can't be multiplying
340 ( ref($_) eq 'ARRAY' and ! $j->{-is_single} )
341 or
342 # a parent of ours is already a multiplier
343 ( grep { $aliases_by_type->{multiplying}{$_} } @{ $j->{-join_path}||[] } )
344 );
546f1cd9 345 }
546f1cd9 346
1a736efb 347 # get a column to source/alias map (including unqualified ones)
348 my $colinfo = $self->_resolve_column_info ($from);
349
ad630f4b 350 # set up a botched SQLA
351 my $sql_maker = $self->sql_maker;
07f31d19 352
4c2b30d6 353 # these are throw away results, do not pollute the bind stack
4c2b30d6 354 local $sql_maker->{select_bind};
0542ec57 355 local $sql_maker->{where_bind};
356 local $sql_maker->{group_bind};
357 local $sql_maker->{having_bind};
97e130fa 358 local $sql_maker->{from_bind};
3f5b99fe 359
360 # we can't scan properly without any quoting (\b doesn't cut it
361 # everywhere), so unless there is proper quoting set - use our
362 # own weird impossible character.
363 # Also in the case of no quoting, we need to explicitly disable
364 # name_sep, otherwise sorry nasty legacy syntax like
365 # { 'count(foo.id)' => { '>' => 3 } } will stop working >:(
366 local $sql_maker->{quote_char} = $sql_maker->{quote_char};
367 local $sql_maker->{name_sep} = $sql_maker->{name_sep};
368
369 unless (defined $sql_maker->{quote_char} and length $sql_maker->{quote_char}) {
e493ecb2 370 $sql_maker->{quote_char} = ["\x00", "\xFF"];
371 # if we don't unset it we screw up retarded but unfortunately working
372 # 'MAX(foo.bar)' => { '>', 3 }
3f5b99fe 373 $sql_maker->{name_sep} = '';
374 }
375
376 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
07f31d19 377
1a736efb 378 # generate sql chunks
379 my $to_scan = {
380 restricting => [
381 $sql_maker->_recurse_where ($where),
a7e643b1 382 $sql_maker->_parse_rs_attrs ({
1a736efb 383 map { $_ => $attrs->{$_} } (qw/group_by having/)
384 }),
385 ],
97e130fa 386 joining => [
387 $sql_maker->_recurse_from (
388 ref $from->[0] eq 'ARRAY' ? $from->[0][0] : $from->[0],
389 @{$from}[1 .. $#$from],
390 ),
391 ],
1a736efb 392 selecting => [
1a736efb 393 $sql_maker->_recurse_fields ($select),
bac358c9 394 ( map { $_->[0] } $self->_extract_order_criteria ($attrs->{order_by}, $sql_maker) ),
1a736efb 395 ],
396 };
07f31d19 397
1a736efb 398 # throw away empty chunks
399 $_ = [ map { $_ || () } @$_ ] for values %$to_scan;
07f31d19 400
1a736efb 401 # first loop through all fully qualified columns and get the corresponding
402 # alias (should work even if they are in scalarrefs)
ad630f4b 403 for my $alias (keys %$alias_list) {
1a736efb 404 my $al_re = qr/
97e130fa 405 $lquote $alias $rquote $sep (?: $lquote ([^$rquote]+) $rquote )?
1a736efb 406 |
97e130fa 407 \b $alias \. ([^\s\)\($rquote]+)?
1a736efb 408 /x;
409
1a736efb 410 for my $type (keys %$to_scan) {
411 for my $piece (@{$to_scan->{$type}}) {
97e130fa 412 if (my @matches = $piece =~ /$al_re/g) {
413 $aliases_by_type->{$type}{$alias} ||= { -parents => $alias_list->{$alias}{-join_path}||[] };
414 $aliases_by_type->{$type}{$alias}{-seen_columns}{"$alias.$_"} = 1
415 for grep { defined $_ } @matches;
416 }
1a736efb 417 }
ad630f4b 418 }
1a736efb 419 }
420
421 # now loop through unqualified column names, and try to locate them within
422 # the chunks
423 for my $col (keys %$colinfo) {
3f5b99fe 424 next if $col =~ / \. /x; # if column is qualified it was caught by the above
1a736efb 425
97e130fa 426 my $col_re = qr/ $lquote ($col) $rquote /x;
07f31d19 427
1a736efb 428 for my $type (keys %$to_scan) {
429 for my $piece (@{$to_scan->{$type}}) {
97e130fa 430 if (my @matches = $piece =~ /$col_re/g) {
a4812caa 431 my $alias = $colinfo->{$col}{-source_alias};
97e130fa 432 $aliases_by_type->{$type}{$alias} ||= { -parents => $alias_list->{$alias}{-join_path}||[] };
433 $aliases_by_type->{$type}{$alias}{-seen_columns}{"$alias.$_"} = 1
434 for grep { defined $_ } @matches;
a4812caa 435 }
1a736efb 436 }
07f31d19 437 }
438 }
439
440 # Add any non-left joins to the restriction list (such joins are indeed restrictions)
ad630f4b 441 for my $j (values %$alias_list) {
07f31d19 442 my $alias = $j->{-alias} or next;
97e130fa 443 $aliases_by_type->{restricting}{$alias} ||= { -parents => $j->{-join_path}||[] } if (
07f31d19 444 (not $j->{-join_type})
445 or
446 ($j->{-join_type} !~ /^left (?: \s+ outer)? $/xi)
447 );
448 }
449
964a3c71 450 return $aliases_by_type;
07f31d19 451}
452
bac358c9 453# This is the engine behind { distinct => 1 }
0a3441ee 454sub _group_over_selection {
455 my ($self, $from, $select, $order_by) = @_;
456
457 my $rs_column_list = $self->_resolve_column_info ($from);
458
459 my (@group_by, %group_index);
460
36fd7f07 461 # the logic is: if it is a { func => val } we assume an aggregate,
462 # otherwise if \'...' or \[...] we assume the user knows what is
463 # going on thus group over it
0a3441ee 464 for (@$select) {
465 if (! ref($_) or ref ($_) ne 'HASH' ) {
466 push @group_by, $_;
467 $group_index{$_}++;
468 if ($rs_column_list->{$_} and $_ !~ /\./ ) {
469 # add a fully qualified version as well
470 $group_index{"$rs_column_list->{$_}{-source_alias}.$_"}++;
471 }
07f31d19 472 }
473 }
ad630f4b 474
0a3441ee 475 # add any order_by parts that are not already present in the group_by
476 # we need to be careful not to add any named functions/aggregates
bac358c9 477 # i.e. order_by => [ ... { count => 'foo' } ... ]
14e26c5f 478 my @leftovers;
bac358c9 479 for ($self->_extract_order_criteria($order_by)) {
0a3441ee 480 # only consider real columns (for functions the user got to do an explicit group_by)
14e26c5f 481 if (@$_ != 1) {
482 push @leftovers, $_;
483 next;
484 }
bac358c9 485 my $chunk = $_->[0];
14e26c5f 486 my $colinfo = $rs_column_list->{$chunk} or do {
487 push @leftovers, $_;
488 next;
489 };
0a3441ee 490
491 $chunk = "$colinfo->{-source_alias}.$chunk" if $chunk !~ /\./;
492 push @group_by, $chunk unless $group_index{$chunk}++;
493 }
494
14e26c5f 495 return wantarray
496 ? (\@group_by, (@leftovers ? \@leftovers : undef) )
497 : \@group_by
498 ;
07f31d19 499}
500
d28bb90d 501sub _resolve_ident_sources {
502 my ($self, $ident) = @_;
503
504 my $alias2source = {};
505 my $rs_alias;
506
507 # the reason this is so contrived is that $ident may be a {from}
508 # structure, specifying multiple tables to join
6298a324 509 if ( blessed $ident && $ident->isa("DBIx::Class::ResultSource") ) {
d28bb90d 510 # this is compat mode for insert/update/delete which do not deal with aliases
511 $alias2source->{me} = $ident;
512 $rs_alias = 'me';
513 }
514 elsif (ref $ident eq 'ARRAY') {
515
516 for (@$ident) {
517 my $tabinfo;
518 if (ref $_ eq 'HASH') {
519 $tabinfo = $_;
520 $rs_alias = $tabinfo->{-alias};
521 }
522 if (ref $_ eq 'ARRAY' and ref $_->[0] eq 'HASH') {
523 $tabinfo = $_->[0];
524 }
525
4376a157 526 $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-rsrc}
527 if ($tabinfo->{-rsrc});
d28bb90d 528 }
529 }
530
531 return ($alias2source, $rs_alias);
532}
533
534# Takes $ident, \@column_names
535#
536# returns { $column_name => \%column_info, ... }
537# also note: this adds -result_source => $rsrc to the column info
538#
09e14fdc 539# If no columns_names are supplied returns info about *all* columns
540# for all sources
d28bb90d 541sub _resolve_column_info {
542 my ($self, $ident, $colnames) = @_;
543 my ($alias2src, $root_alias) = $self->_resolve_ident_sources($ident);
544
52416317 545 my (%seen_cols, @auto_colnames);
d28bb90d 546
547 # compile a global list of column names, to be able to properly
548 # disambiguate unqualified column names (if at all possible)
549 for my $alias (keys %$alias2src) {
550 my $rsrc = $alias2src->{$alias};
551 for my $colname ($rsrc->columns) {
552 push @{$seen_cols{$colname}}, $alias;
3f5b99fe 553 push @auto_colnames, "$alias.$colname" unless $colnames;
d28bb90d 554 }
555 }
556
09e14fdc 557 $colnames ||= [
558 @auto_colnames,
559 grep { @{$seen_cols{$_}} == 1 } (keys %seen_cols),
560 ];
561
52416317 562 my (%return, $colinfos);
d28bb90d 563 foreach my $col (@$colnames) {
52416317 564 my ($source_alias, $colname) = $col =~ m/^ (?: ([^\.]+) \. )? (.+) $/x;
d28bb90d 565
52416317 566 # if the column was seen exactly once - we know which rsrc it came from
567 $source_alias ||= $seen_cols{$colname}[0]
568 if ($seen_cols{$colname} and @{$seen_cols{$colname}} == 1);
d28bb90d 569
52416317 570 next unless $source_alias;
571
572 my $rsrc = $alias2src->{$source_alias}
573 or next;
574
575 $return{$col} = {
6395604e 576 %{
577 ( $colinfos->{$source_alias} ||= $rsrc->columns_info )->{$colname}
578 ||
579 $self->throw_exception(
580 "No such column '$colname' on source " . $rsrc->source_name
581 );
582 },
d28bb90d 583 -result_source => $rsrc,
52416317 584 -source_alias => $source_alias,
81bf295c 585 -fq_colname => $col eq $colname ? "$source_alias.$col" : $col,
586 -colname => $colname,
d28bb90d 587 };
81bf295c 588
589 $return{"$source_alias.$colname"} = $return{$col} if $col eq $colname;
d28bb90d 590 }
591
592 return \%return;
593}
594
289ac713 595# The DBIC relationship chaining implementation is pretty simple - every
596# new related_relationship is pushed onto the {from} stack, and the {select}
597# window simply slides further in. This means that when we count somewhere
598# in the middle, we got to make sure that everything in the join chain is an
599# actual inner join, otherwise the count will come back with unpredictable
600# results (a resultset may be generated with _some_ rows regardless of if
601# the relation which the $rs currently selects has rows or not). E.g.
602# $artist_rs->cds->count - normally generates:
603# SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
604# which actually returns the number of artists * (number of cds || 1)
605#
606# So what we do here is crawl {from}, determine if the current alias is at
607# the top of the stack, and if not - make sure the chain is inner-joined down
608# to the root.
609#
31a8aaaf 610sub _inner_join_to_node {
289ac713 611 my ($self, $from, $alias) = @_;
612
613 # subqueries and other oddness are naturally not supported
614 return $from if (
615 ref $from ne 'ARRAY'
616 ||
617 @$from <= 1
618 ||
619 ref $from->[0] ne 'HASH'
620 ||
621 ! $from->[0]{-alias}
622 ||
7eb76996 623 $from->[0]{-alias} eq $alias # this last bit means $alias is the head of $from - nothing to do
289ac713 624 );
625
626 # find the current $alias in the $from structure
627 my $switch_branch;
628 JOINSCAN:
629 for my $j (@{$from}[1 .. $#$from]) {
630 if ($j->[0]{-alias} eq $alias) {
631 $switch_branch = $j->[0]{-join_path};
632 last JOINSCAN;
633 }
634 }
635
7eb76996 636 # something else went quite wrong
289ac713 637 return $from unless $switch_branch;
638
639 # So it looks like we will have to switch some stuff around.
640 # local() is useless here as we will be leaving the scope
641 # anyway, and deep cloning is just too fucking expensive
8273e845 642 # So replace the first hashref in the node arrayref manually
289ac713 643 my @new_from = ($from->[0]);
faeb2407 644 my $sw_idx = { map { (values %$_), 1 } @$switch_branch }; #there's one k/v per join-path
289ac713 645
646 for my $j (@{$from}[1 .. $#$from]) {
647 my $jalias = $j->[0]{-alias};
648
649 if ($sw_idx->{$jalias}) {
650 my %attrs = %{$j->[0]};
651 delete $attrs{-join_type};
652 push @new_from, [
653 \%attrs,
654 @{$j}[ 1 .. $#$j ],
655 ];
656 }
657 else {
658 push @new_from, $j;
659 }
660 }
661
662 return \@new_from;
663}
664
bac358c9 665sub _extract_order_criteria {
1a736efb 666 my ($self, $order_by, $sql_maker) = @_;
c0748280 667
1a736efb 668 my $parser = sub {
669 my ($sql_maker, $order_by) = @_;
c0748280 670
1a736efb 671 return scalar $sql_maker->_order_by_chunks ($order_by)
672 unless wantarray;
c0748280 673
1a736efb 674 my @chunks;
bac358c9 675 for ($sql_maker->_order_by_chunks ($order_by) ) {
676 my $chunk = ref $_ ? $_ : [ $_ ];
677 $chunk->[0] =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
1a736efb 678 push @chunks, $chunk;
bac6c4fb 679 }
1a736efb 680
681 return @chunks;
682 };
683
684 if ($sql_maker) {
685 return $parser->($sql_maker, $order_by);
bac6c4fb 686 }
687 else {
1a736efb 688 $sql_maker = $self->sql_maker;
689 local $sql_maker->{quote_char};
690 return $parser->($sql_maker, $order_by);
bac6c4fb 691 }
bac6c4fb 692}
693
7cec4356 694sub _order_by_is_stable {
5f11e54f 695 my ($self, $ident, $order_by, $where) = @_;
c0748280 696
5f11e54f 697 my $colinfo = $self->_resolve_column_info($ident, [
698 (map { $_->[0] } $self->_extract_order_criteria($order_by)),
699 $where ? @{$self->_extract_fixed_condition_columns($where)} :(),
700 ]);
c0748280 701
7cec4356 702 return undef unless keys %$colinfo;
703
704 my $cols_per_src;
705 $cols_per_src->{$_->{-source_alias}}{$_->{-colname}} = $_ for values %$colinfo;
706
707 for (values %$cols_per_src) {
708 my $src = (values %$_)[0]->{-result_source};
709 return 1 if $src->_identifying_column_set($_);
c0748280 710 }
711
7cec4356 712 return undef;
713}
714
5f11e54f 715# returns an arrayref of column names which *definitely* have som
716# sort of non-nullable equality requested in the given condition
717# specification. This is used to figure out if a resultset is
718# constrained to a column which is part of a unique constraint,
719# which in turn allows us to better predict how ordering will behave
720# etc.
721#
722# this is a rudimentary, incomplete, and error-prone extractor
723# however this is OK - it is conservative, and if we can not find
724# something that is in fact there - the stack will recover gracefully
725# Also - DQ and the mst it rode in on will save us all RSN!!!
726sub _extract_fixed_condition_columns {
727 my ($self, $where, $nested) = @_;
728
729 return unless ref $where eq 'HASH';
730
731 my @cols;
732 for my $lhs (keys %$where) {
733 if ($lhs =~ /^\-and$/i) {
734 push @cols, ref $where->{$lhs} eq 'ARRAY'
735 ? ( map { $self->_extract_fixed_condition_columns($_, 1) } @{$where->{$lhs}} )
736 : $self->_extract_fixed_condition_columns($where->{$lhs}, 1)
737 ;
738 }
739 elsif ($lhs !~ /^\-/) {
740 my $val = $where->{$lhs};
741
742 push @cols, $lhs if (defined $val and (
743 ! ref $val
744 or
745 (ref $val eq 'HASH' and keys %$val == 1 and defined $val->{'='})
746 ));
747 }
748 }
749 return $nested ? @cols : \@cols;
c0748280 750}
bac6c4fb 751
d28bb90d 7521;