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