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