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