1 package #hide from PAUSE
2 DBIx::Class::Storage::DBIHacks;
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
13 use base 'DBIx::Class::Storage';
16 use List::Util 'first';
17 use Scalar::Util 'blessed';
18 use Sub::Name 'subname';
22 # This code will remove non-selecting/non-restricting joins from
23 # {from} specs, aiding the RDBMS query optimizer
25 sub _prune_unused_joins {
27 my ($from, $select, $where, $attrs) = @_;
29 return $from unless $self->_use_join_optimizer;
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
35 my $aliastypes = $self->_resolve_aliastypes_from_select_args(@_);
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};
41 my @newfrom = $from->[0]; # FROM head is always present
44 for (values %$aliastypes) {
45 # add all requested aliases
46 $need_joins{$_} = 1 for keys %$_;
48 # add all their parents (as per joinpath which is an AoH { table => alias })
49 $need_joins{$_} = 1 for map { values %$_ } map { @$_ } values %$_;
51 for my $j (@{$from}[1..$#$from]) {
52 push @newfrom, $j if (
53 (! $j->[0]{-alias}) # legacy crap
55 $need_joins{$j->[0]{-alias}}
63 # This is the code producing joined subqueries like:
64 # SELECT me.*, other.* FROM ( SELECT me.* FROM ... ) JOIN other ON ...
66 sub _adjust_select_args_for_complex_prefetch {
67 my ($self, $from, $select, $where, $attrs) = @_;
69 $self->throw_exception ('Nothing to prefetch... how did we get here?!')
70 if not @{$attrs->{_prefetch_selector_range}};
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');
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/;
80 my $inner_attrs = { %$attrs };
81 delete $inner_attrs->{$_} for qw/for collapse _prefetch_selector_range _collapse_order_by select as/;
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]
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 = [];
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];
103 if (ref $sel eq 'HASH' ) {
104 $sel->{-as} ||= $attrs->{as}[$i];
105 $outer_select->[$i] = join ('.', $attrs->{alias}, ($sel->{-as} || "inner_column_$i") );
108 push @$inner_select, $sel;
110 push @{$inner_attrs->{as}}, $attrs->{as}[$i];
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)
118 my $inner_subq = do {
120 # must use it here regardless of user requests
121 local $self->{_use_join_optimizer} = 1;
123 my $inner_from = $self->_prune_unused_joins ($from, $inner_select, $where, {
124 group_by => ['dummy'], %$inner_attrs,
127 my $inner_aliastypes =
128 $self->_resolve_aliastypes_from_select_args( $inner_from, $inner_select, $where, $inner_attrs );
130 # we need to simulate collapse in the subq if a multiplying join is pulled
131 # by being a non-selecting restrictor
133 ! $inner_attrs->{group_by}
136 $inner_aliastypes->{restricting}{$_}
138 ! $inner_aliastypes->{selecting}{$_}
139 } ( keys %{$inner_aliastypes->{multiplying}||{}} )
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}
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 '
150 ) if $unprocessed_order_chunks;
153 # we already optimized $inner_from above
154 local $self->{_use_join_optimizer} = 0;
156 # generate the subquery
157 $self->_select_args_to_query (
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.
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
177 # so first generate the outer_from, up to the substitution point
179 while (my $j = shift @$from) {
180 $j = [ $j ] unless ref $j eq 'ARRAY'; # promote the head-from to an AoH
182 if ($j->[0]{-alias} eq $attrs->{alias}) { # time to swap
186 -alias => $attrs->{alias},
187 -rsrc => $j->[0]{-rsrc},
188 $attrs->{alias} => $inner_subq,
192 last; # we'll take care of what's left in $from below
195 push @outer_from, $j;
199 # scan the *remaining* from spec against different attributes, and see which joins are needed
201 my $outer_aliastypes =
202 $self->_resolve_aliastypes_from_select_args( $from, $outer_select, $where, $outer_attrs );
205 my ($outer_select_chain, $outer_restrict_chain) = map { +{
206 map { $_ => 1 } map { values %$_} map { @$_ } values %{ $outer_aliastypes->{$_} || {} }
207 } } qw/selecting restricting/;
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};
217 $outer_select_chain->{$alias}
221 elsif ($outer_restrict_chain->{$alias}) {
222 push @outer_from, $j;
223 $need_outer_group_by ||= $outer_aliastypes->{multiplying}{$alias} ? 1 : 0;
227 # demote the outer_from head
228 $outer_from[0] = $outer_from[0][0];
230 if ($need_outer_group_by and ! $outer_attrs->{group_by}) {
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}
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 '
241 ) if $unprocessed_order_chunks;
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
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);
256 # I KNOW THIS SUCKS! GET SQLA2 OUT THE DOOR SO THIS CAN DIE!
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 ) = @_;
269 $self->throw_exception ('Unable to analyze custom {from}')
270 if ref $from ne 'ARRAY';
272 # what we will return
275 # see what aliases are there to work with
279 $j = $j->[0] if ref $j eq 'ARRAY';
280 my $al = $j->{-alias}
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} )
288 # a parent of ours is already a multiplier
289 ( grep { $aliases_by_type->{multiplying}{$_} } @{ $j->{-join_path}||[] } )
293 # get a column to source/alias map (including unqualified ones)
294 my $colinfo = $self->_resolve_column_info ($from);
296 # set up a botched SQLA
297 my $sql_maker = $self->sql_maker;
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};
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};
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} = '';
321 my ($lquote, $rquote, $sep) = map { quotemeta $_ } ($sql_maker->_quote_chars, $sql_maker->name_sep);
323 # generate sql chunks
326 $sql_maker->_recurse_where ($where),
327 $sql_maker->_parse_rs_attrs ({
328 map { $_ => $attrs->{$_} } (qw/group_by having/)
332 $sql_maker->_recurse_fields ($select),
333 ( map { $_->[0] } $self->_extract_order_criteria ($attrs->{order_by}, $sql_maker) ),
337 # throw away empty chunks
338 $_ = [ map { $_ || () } @$_ ] for values %$to_scan;
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) {
344 $lquote $alias $rquote $sep
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);
357 # now loop through unqualified column names, and try to locate them within
359 for my $col (keys %$colinfo) {
360 next if $col =~ / \. /x; # if column is qualified it was caught by the above
362 my $col_re = qr/ $lquote $col $rquote /x;
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}||[];
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})
380 ($j->{-join_type} !~ /^left (?: \s+ outer)? $/xi)
384 return $aliases_by_type;
387 # This is the engine behind { distinct => 1 }
388 sub _group_over_selection {
389 my ($self, $from, $select, $order_by) = @_;
391 my $rs_column_list = $self->_resolve_column_info ($from);
393 my (@group_by, %group_index);
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
399 if (! ref($_) or ref ($_) ne 'HASH' ) {
402 if ($rs_column_list->{$_} and $_ !~ /\./ ) {
403 # add a fully qualified version as well
404 $group_index{"$rs_column_list->{$_}{-source_alias}.$_"}++;
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' } ... ]
413 for ($self->_extract_order_criteria($order_by)) {
414 # only consider real columns (for functions the user got to do an explicit group_by)
420 my $colinfo = $rs_column_list->{$chunk} or do {
425 $chunk = "$colinfo->{-source_alias}.$chunk" if $chunk !~ /\./;
426 push @group_by, $chunk unless $group_index{$chunk}++;
430 ? (\@group_by, (@leftovers ? \@leftovers : undef) )
435 sub _resolve_ident_sources {
436 my ($self, $ident) = @_;
438 my $alias2source = {};
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;
448 elsif (ref $ident eq 'ARRAY') {
452 if (ref $_ eq 'HASH') {
454 $rs_alias = $tabinfo->{-alias};
456 if (ref $_ eq 'ARRAY' and ref $_->[0] eq 'HASH') {
460 $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-rsrc}
461 if ($tabinfo->{-rsrc});
465 return ($alias2source, $rs_alias);
468 # Takes $ident, \@column_names
470 # returns { $column_name => \%column_info, ... }
471 # also note: this adds -result_source => $rsrc to the column info
473 # If no columns_names are supplied returns info about *all* columns
475 sub _resolve_column_info {
476 my ($self, $ident, $colnames) = @_;
477 my ($alias2src, $root_alias) = $self->_resolve_ident_sources($ident);
479 my (%seen_cols, @auto_colnames);
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;
493 grep { @{$seen_cols{$_}} == 1 } (keys %seen_cols),
496 my (%return, $colinfos);
497 foreach my $col (@$colnames) {
498 my ($source_alias, $colname) = $col =~ m/^ (?: ([^\.]+) \. )? (.+) $/x;
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);
504 next unless $source_alias;
506 my $rsrc = $alias2src->{$source_alias}
511 ( $colinfos->{$source_alias} ||= $rsrc->columns_info )->{$colname}
513 $self->throw_exception(
514 "No such column '$colname' on source " . $rsrc->source_name
517 -result_source => $rsrc,
518 -source_alias => $source_alias,
525 # The DBIC relationship chaining implementation is pretty simple - every
526 # new related_relationship is pushed onto the {from} stack, and the {select}
527 # window simply slides further in. This means that when we count somewhere
528 # in the middle, we got to make sure that everything in the join chain is an
529 # actual inner join, otherwise the count will come back with unpredictable
530 # results (a resultset may be generated with _some_ rows regardless of if
531 # the relation which the $rs currently selects has rows or not). E.g.
532 # $artist_rs->cds->count - normally generates:
533 # SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
534 # which actually returns the number of artists * (number of cds || 1)
536 # So what we do here is crawl {from}, determine if the current alias is at
537 # the top of the stack, and if not - make sure the chain is inner-joined down
540 sub _inner_join_to_node {
541 my ($self, $from, $alias) = @_;
543 # subqueries and other oddness are naturally not supported
549 ref $from->[0] ne 'HASH'
553 $from->[0]{-alias} eq $alias # this last bit means $alias is the head of $from - nothing to do
556 # find the current $alias in the $from structure
559 for my $j (@{$from}[1 .. $#$from]) {
560 if ($j->[0]{-alias} eq $alias) {
561 $switch_branch = $j->[0]{-join_path};
566 # something else went quite wrong
567 return $from unless $switch_branch;
569 # So it looks like we will have to switch some stuff around.
570 # local() is useless here as we will be leaving the scope
571 # anyway, and deep cloning is just too fucking expensive
572 # So replace the first hashref in the node arrayref manually
573 my @new_from = ($from->[0]);
574 my $sw_idx = { map { (values %$_), 1 } @$switch_branch }; #there's one k/v per join-path
576 for my $j (@{$from}[1 .. $#$from]) {
577 my $jalias = $j->[0]{-alias};
579 if ($sw_idx->{$jalias}) {
580 my %attrs = %{$j->[0]};
581 delete $attrs{-join_type};
595 # yet another atrocity: attempt to extract all columns from a
596 # where condition by hooking _quote
597 sub _extract_condition_columns {
598 my ($self, $cond, $sql_maker) = @_;
600 return [] unless $cond;
602 $sql_maker ||= $self->{_sql_ident_capturer} ||= do {
603 # FIXME - replace with a Moo trait
604 my $orig_sm_class = ref $self->sql_maker;
605 my $smic_class = "${orig_sm_class}::_IdentCapture_";
607 unless ($smic_class->isa('SQL::Abstract')) {
610 *{"${smic_class}::_quote"} = subname "${smic_class}::_quote" => sub {
611 my ($self, $ident) = @_;
612 if (ref $ident eq 'SCALAR') {
614 my $storage_quotes = $self->sql_quote_char || '"';
617 (ref $storage_quotes eq 'ARRAY' ? @$storage_quotes : ($storage_quotes) x 2 )
625 $self->{_captured_idents}{$1||$2}++;
629 $self->{_captured_idents}{$ident}++;
634 *{"${smic_class}::_get_captured_idents"} = subname "${smic_class}::_get_captures" => sub {
635 (delete shift->{_captured_idents}) || {};
638 $self->inject_base ($smic_class, $orig_sm_class);
645 $sql_maker->_recurse_where($cond);
647 return [ sort keys %{$sql_maker->_get_captured_idents} ];
650 sub _extract_order_criteria {
651 my ($self, $order_by, $sql_maker) = @_;
654 my ($sql_maker, $order_by) = @_;
656 return scalar $sql_maker->_order_by_chunks ($order_by)
660 for ($sql_maker->_order_by_chunks ($order_by) ) {
661 my $chunk = ref $_ ? $_ : [ $_ ];
662 $chunk->[0] =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
663 push @chunks, $chunk;
670 return $parser->($sql_maker, $order_by);
673 $sql_maker = $self->sql_maker;
674 local $sql_maker->{quote_char};
675 return $parser->($sql_maker, $order_by);