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