Deduplicate code in RSC, use the RSRC unique constraint traversal instead
[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
80 my $inner_attrs = { %$attrs };
36fd7f07 81 delete $inner_attrs->{$_} for qw/for collapse _prefetch_selector_range _collapse_order_by select as/;
d28bb90d 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
d28bb90d 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 = [];
36fd7f07 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) {
d28bb90d 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;
bb9bffea 109
110 push @{$inner_attrs->{as}}, $attrs->{as}[$i];
d28bb90d 111 }
112
ea95892e 113 # construct the inner $from and lock it in a subquery
48580715 114 # we need to prune first, because this will determine if we need a group_by below
53c29913 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)
ea95892e 117
6395604e 118 my $inner_subq = do {
ea95892e 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
887a0aef 127 my $inner_aliastypes =
128 $self->_resolve_aliastypes_from_select_args( $inner_from, $inner_select, $where, $inner_attrs );
129
a4812caa 130 # we need to simulate collapse in the subq if a multiplying join is pulled
131 # by being a non-selecting restrictor
0a3441ee 132 if (
133 ! $inner_attrs->{group_by}
134 and
887a0aef 135 first {
136 $inner_aliastypes->{restricting}{$_}
137 and
138 ! $inner_aliastypes->{selecting}{$_}
139 } ( keys %{$inner_aliastypes->{multiplying}||{}} )
0a3441ee 140 ) {
14e26c5f 141 my $unprocessed_order_chunks;
142 ($inner_attrs->{group_by}, $unprocessed_order_chunks) = $self->_group_over_selection (
0a3441ee 143 $inner_from, $inner_select, $inner_attrs->{order_by}
144 );
14e26c5f 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;
0a3441ee 151 }
ea95892e 152
153 # we already optimized $inner_from above
154 local $self->{_use_join_optimizer} = 0;
155
156 # generate the subquery
6395604e 157 $self->_select_args_to_query (
ea95892e 158 $inner_from,
159 $inner_select,
160 $where,
161 $inner_attrs,
162 );
d28bb90d 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
052e8431 175 $from = [ @$from ];
052e8431 176
d28bb90d 177 # so first generate the outer_from, up to the substitution point
178 my @outer_from;
179 while (my $j = shift @$from) {
53c29913 180 $j = [ $j ] unless ref $j eq 'ARRAY'; # promote the head-from to an AoH
181
d28bb90d 182 if ($j->[0]{-alias} eq $attrs->{alias}) { # time to swap
6395604e 183
d28bb90d 184 push @outer_from, [
6395604e 185 {
186 -alias => $attrs->{alias},
187 -rsrc => $j->[0]{-rsrc},
188 $attrs->{alias} => $inner_subq,
189 },
d28bb90d 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
ea95892e 199 # scan the *remaining* from spec against different attributes, and see which joins are needed
052e8431 200 # in what role
201 my $outer_aliastypes =
539ffe87 202 $self->_resolve_aliastypes_from_select_args( $from, $outer_select, $where, $outer_attrs );
052e8431 203
a4812caa 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
d28bb90d 209 # see what's left - throw away if not selecting/restricting
a4812caa 210 # also throw in a group_by if a non-selecting multiplier,
211 # to guard against cross-join explosions
36fd7f07 212 my $need_outer_group_by;
d28bb90d 213 while (my $j = shift @$from) {
214 my $alias = $j->[0]{-alias};
215
a4812caa 216 if (
217 $outer_select_chain->{$alias}
218 ) {
219 push @outer_from, $j
d28bb90d 220 }
a4812caa 221 elsif ($outer_restrict_chain->{$alias}) {
d28bb90d 222 push @outer_from, $j;
a4812caa 223 $need_outer_group_by ||= $outer_aliastypes->{multiplying}{$alias} ? 1 : 0;
d28bb90d 224 }
225 }
226
227 # demote the outer_from head
228 $outer_from[0] = $outer_from[0][0];
229
36fd7f07 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
d28bb90d 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
1a736efb 255#
256# I KNOW THIS SUCKS! GET SQLA2 OUT THE DOOR SO THIS CAN DIE!
257#
ad630f4b 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
1a736efb 264# happen is for it to fail due to some scalar SQL, which in turn will
265# result in a vocal exception.
539ffe87 266sub _resolve_aliastypes_from_select_args {
052e8431 267 my ( $self, $from, $select, $where, $attrs ) = @_;
546f1cd9 268
ad630f4b 269 $self->throw_exception ('Unable to analyze custom {from}')
270 if ref $from ne 'ARRAY';
546f1cd9 271
ad630f4b 272 # what we will return
964a3c71 273 my $aliases_by_type;
546f1cd9 274
ad630f4b 275 # see what aliases are there to work with
276 my $alias_list;
539ffe87 277 for (@$from) {
278 my $j = $_;
ad630f4b 279 $j = $j->[0] if ref $j eq 'ARRAY';
539ffe87 280 my $al = $j->{-alias}
281 or next;
282
283 $alias_list->{$al} = $j;
a4812caa 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 );
546f1cd9 291 }
546f1cd9 292
1a736efb 293 # get a column to source/alias map (including unqualified ones)
294 my $colinfo = $self->_resolve_column_info ($from);
295
ad630f4b 296 # set up a botched SQLA
297 my $sql_maker = $self->sql_maker;
07f31d19 298
4c2b30d6 299 # these are throw away results, do not pollute the bind stack
4c2b30d6 300 local $sql_maker->{select_bind};
0542ec57 301 local $sql_maker->{where_bind};
302 local $sql_maker->{group_bind};
303 local $sql_maker->{having_bind};
3f5b99fe 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}) {
e493ecb2 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 }
3f5b99fe 318 $sql_maker->{name_sep} = '';
319 }
320
321 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
07f31d19 322
1a736efb 323 # generate sql chunks
324 my $to_scan = {
325 restricting => [
326 $sql_maker->_recurse_where ($where),
a7e643b1 327 $sql_maker->_parse_rs_attrs ({
1a736efb 328 map { $_ => $attrs->{$_} } (qw/group_by having/)
329 }),
330 ],
331 selecting => [
1a736efb 332 $sql_maker->_recurse_fields ($select),
bac358c9 333 ( map { $_->[0] } $self->_extract_order_criteria ($attrs->{order_by}, $sql_maker) ),
1a736efb 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)
ad630f4b 342 for my $alias (keys %$alias_list) {
1a736efb 343 my $al_re = qr/
3f5b99fe 344 $lquote $alias $rquote $sep
1a736efb 345 |
3f5b99fe 346 \b $alias \.
1a736efb 347 /x;
348
1a736efb 349 for my $type (keys %$to_scan) {
350 for my $piece (@{$to_scan->{$type}}) {
a4812caa 351 $aliases_by_type->{$type}{$alias} ||= $alias_list->{$alias}{-join_path}||[]
352 if ($piece =~ $al_re);
1a736efb 353 }
ad630f4b 354 }
1a736efb 355 }
356
357 # now loop through unqualified column names, and try to locate them within
358 # the chunks
359 for my $col (keys %$colinfo) {
3f5b99fe 360 next if $col =~ / \. /x; # if column is qualified it was caught by the above
1a736efb 361
3f5b99fe 362 my $col_re = qr/ $lquote $col $rquote /x;
1a736efb 363
364 for my $type (keys %$to_scan) {
365 for my $piece (@{$to_scan->{$type}}) {
a4812caa 366 if ($piece =~ $col_re) {
367 my $alias = $colinfo->{$col}{-source_alias};
368 $aliases_by_type->{$type}{$alias} ||= $alias_list->{$alias}{-join_path}||[];
369 }
1a736efb 370 }
07f31d19 371 }
372 }
373
374 # Add any non-left joins to the restriction list (such joins are indeed restrictions)
ad630f4b 375 for my $j (values %$alias_list) {
07f31d19 376 my $alias = $j->{-alias} or next;
a4812caa 377 $aliases_by_type->{restricting}{$alias} ||= $j->{-join_path}||[] if (
07f31d19 378 (not $j->{-join_type})
379 or
380 ($j->{-join_type} !~ /^left (?: \s+ outer)? $/xi)
381 );
382 }
383
964a3c71 384 return $aliases_by_type;
07f31d19 385}
386
bac358c9 387# This is the engine behind { distinct => 1 }
0a3441ee 388sub _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
36fd7f07 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
0a3441ee 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
bac358c9 411 # i.e. order_by => [ ... { count => 'foo' } ... ]
14e26c5f 412 my @leftovers;
bac358c9 413 for ($self->_extract_order_criteria($order_by)) {
0a3441ee 414 # only consider real columns (for functions the user got to do an explicit group_by)
14e26c5f 415 if (@$_ != 1) {
416 push @leftovers, $_;
417 next;
418 }
bac358c9 419 my $chunk = $_->[0];
14e26c5f 420 my $colinfo = $rs_column_list->{$chunk} or do {
421 push @leftovers, $_;
422 next;
423 };
0a3441ee 424
425 $chunk = "$colinfo->{-source_alias}.$chunk" if $chunk !~ /\./;
426 push @group_by, $chunk unless $group_index{$chunk}++;
427 }
428
14e26c5f 429 return wantarray
430 ? (\@group_by, (@leftovers ? \@leftovers : undef) )
431 : \@group_by
432 ;
0a3441ee 433}
434
d28bb90d 435sub _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
6298a324 443 if ( blessed $ident && $ident->isa("DBIx::Class::ResultSource") ) {
d28bb90d 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
4376a157 460 $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-rsrc}
461 if ($tabinfo->{-rsrc});
d28bb90d 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#
09e14fdc 473# If no columns_names are supplied returns info about *all* columns
474# for all sources
d28bb90d 475sub _resolve_column_info {
476 my ($self, $ident, $colnames) = @_;
477 my ($alias2src, $root_alias) = $self->_resolve_ident_sources($ident);
478
52416317 479 my (%seen_cols, @auto_colnames);
d28bb90d 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;
3f5b99fe 487 push @auto_colnames, "$alias.$colname" unless $colnames;
d28bb90d 488 }
489 }
490
09e14fdc 491 $colnames ||= [
492 @auto_colnames,
493 grep { @{$seen_cols{$_}} == 1 } (keys %seen_cols),
494 ];
495
52416317 496 my (%return, $colinfos);
d28bb90d 497 foreach my $col (@$colnames) {
52416317 498 my ($source_alias, $colname) = $col =~ m/^ (?: ([^\.]+) \. )? (.+) $/x;
d28bb90d 499
52416317 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);
d28bb90d 503
52416317 504 next unless $source_alias;
505
506 my $rsrc = $alias2src->{$source_alias}
507 or next;
508
509 $return{$col} = {
6395604e 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 },
d28bb90d 517 -result_source => $rsrc,
52416317 518 -source_alias => $source_alias,
81bf295c 519 -fq_colname => $col eq $colname ? "$source_alias.$col" : $col,
520 -colname => $colname,
d28bb90d 521 };
81bf295c 522
523 $return{"$source_alias.$colname"} = $return{$col} if $col eq $colname;
d28bb90d 524 }
525
526 return \%return;
527}
528
289ac713 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#
31a8aaaf 544sub _inner_join_to_node {
289ac713 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 ||
7eb76996 557 $from->[0]{-alias} eq $alias # this last bit means $alias is the head of $from - nothing to do
289ac713 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
7eb76996 570 # something else went quite wrong
289ac713 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
8273e845 576 # So replace the first hashref in the node arrayref manually
289ac713 577 my @new_from = ($from->[0]);
faeb2407 578 my $sw_idx = { map { (values %$_), 1 } @$switch_branch }; #there's one k/v per join-path
289ac713 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
ea5c7509 599# yet another atrocity: attempt to extract all columns from a
600# where condition by hooking _quote
601sub _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
bac358c9 654sub _extract_order_criteria {
1a736efb 655 my ($self, $order_by, $sql_maker) = @_;
c0748280 656
1a736efb 657 my $parser = sub {
658 my ($sql_maker, $order_by) = @_;
c0748280 659
1a736efb 660 return scalar $sql_maker->_order_by_chunks ($order_by)
661 unless wantarray;
c0748280 662
1a736efb 663 my @chunks;
bac358c9 664 for ($sql_maker->_order_by_chunks ($order_by) ) {
665 my $chunk = ref $_ ? $_ : [ $_ ];
666 $chunk->[0] =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
1a736efb 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 }
c0748280 681}
bac6c4fb 682
d28bb90d 6831;