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 oboslete 90% of this
13 use base 'DBIx::Class::Storage';
16 use Carp::Clan qw/^DBIx::Class/;
19 # This code will remove non-selecting/non-restricting joins from
20 # {from} specs, aiding the RDBMS query optimizer.
22 sub _prune_unused_joins {
26 if (ref $from ne 'ARRAY' || ref $from->[0] ne 'HASH' || ref $from->[1] ne 'ARRAY') {
27 return $from; # only standard {from} specs are supported
30 my $aliastypes = $self->_resolve_aliastypes_from_select_args($from, @_);
32 my @newfrom = $from->[0]; # FROM head is always present
34 my %need_joins = (map { %{$_||{}} } (values %$aliastypes) );
35 for my $j (@{$from}[1..$#$from]) {
36 push @newfrom, $j if (
37 ! $j->[0]{-alias} # legacy crap
39 $need_joins{$j->[0]{-alias}}
48 # This is the code producing joined subqueries like:
49 # SELECT me.*, other.* FROM ( SELECT me.* FROM ... ) JOIN other ON ...
51 sub _adjust_select_args_for_complex_prefetch {
52 my ($self, $from, $select, $where, $attrs) = @_;
54 $self->throw_exception ('Nothing to prefetch... how did we get here?!')
55 if not @{$attrs->{_prefetch_select}};
57 $self->throw_exception ('Complex prefetches are not supported on resultsets with a custom from attribute')
58 if (ref $from ne 'ARRAY' || ref $from->[0] ne 'HASH' || ref $from->[1] ne 'ARRAY');
61 # generate inner/outer attribute lists, remove stuff that doesn't apply
62 my $outer_attrs = { %$attrs };
63 delete $outer_attrs->{$_} for qw/where bind rows offset group_by having/;
65 my $inner_attrs = { %$attrs };
66 delete $inner_attrs->{$_} for qw/for collapse _prefetch_select _collapse_order_by select as/;
69 # bring over all non-collapse-induced order_by into the inner query (if any)
70 # the outer one will have to keep them all
71 delete $inner_attrs->{order_by};
72 if (my $ord_cnt = @{$outer_attrs->{order_by}} - @{$outer_attrs->{_collapse_order_by}} ) {
73 $inner_attrs->{order_by} = [
74 @{$outer_attrs->{order_by}}[ 0 .. $ord_cnt - 1]
78 # generate the inner/outer select lists
79 # for inside we consider only stuff *not* brought in by the prefetch
80 # on the outside we substitute any function for its alias
81 my $outer_select = [ @$select ];
82 my $inner_select = [];
83 for my $i (0 .. ( @$outer_select - @{$outer_attrs->{_prefetch_select}} - 1) ) {
84 my $sel = $outer_select->[$i];
86 if (ref $sel eq 'HASH' ) {
87 $sel->{-as} ||= $attrs->{as}[$i];
88 $outer_select->[$i] = join ('.', $attrs->{alias}, ($sel->{-as} || "inner_column_$i") );
91 push @$inner_select, $sel;
94 # construct the inner $from for the subquery
95 my $inner_from = $self->_prune_unused_joins ($from, $inner_select, $where, $inner_attrs);
97 # if a multi-type join was needed in the subquery - add a group_by to simulate the
98 # collapse in the subq
99 $inner_attrs->{group_by} ||= $inner_select
101 { ! $_->[0]{-is_single} }
102 (@{$inner_from}[1 .. $#$inner_from])
105 # generate the subquery
106 my $subq = $self->_select_args_to_query (
113 my $subq_joinspec = {
114 -alias => $attrs->{alias},
115 -source_handle => $inner_from->[0]{-source_handle},
116 $attrs->{alias} => $subq,
119 # Generate the outer from - this is relatively easy (really just replace
120 # the join slot with the subquery), with a major caveat - we can not
121 # join anything that is non-selecting (not part of the prefetch), but at
122 # the same time is a multi-type relationship, as it will explode the result.
124 # There are two possibilities here
125 # - either the join is non-restricting, in which case we simply throw it away
126 # - it is part of the restrictions, in which case we need to collapse the outer
127 # result by tackling yet another group_by to the outside of the query
129 # normalize a copy of $from, so it will be easier to work with further
130 # down (i.e. promote the initial hashref to an AoH)
132 $from->[0] = [ $from->[0] ];
134 # so first generate the outer_from, up to the substitution point
136 while (my $j = shift @$from) {
137 if ($j->[0]{-alias} eq $attrs->{alias}) { # time to swap
142 last; # we'll take care of what's left in $from below
145 push @outer_from, $j;
149 # scan the from spec against different attributes, and see which joins are needed
151 my $outer_aliastypes =
152 $self->_resolve_aliastypes_from_select_args( $from, $outer_select, $where, $outer_attrs );
154 # see what's left - throw away if not selecting/restricting
155 # also throw in a group_by if restricting to guard against
156 # cross-join explosions
158 while (my $j = shift @$from) {
159 my $alias = $j->[0]{-alias};
161 if ($outer_aliastypes->{select}{$alias}) {
162 push @outer_from, $j;
164 elsif ($outer_aliastypes->{restrict}{$alias}) {
165 push @outer_from, $j;
166 $outer_attrs->{group_by} ||= $outer_select unless $j->[0]{-is_single};
170 # demote the outer_from head
171 $outer_from[0] = $outer_from[0][0];
173 # This is totally horrific - the $where ends up in both the inner and outer query
174 # Unfortunately not much can be done until SQLA2 introspection arrives, and even
175 # then if where conditions apply to the *right* side of the prefetch, you may have
176 # to both filter the inner select (e.g. to apply a limit) and then have to re-filter
177 # the outer select to exclude joins you didin't want in the first place
179 # OTOH it can be seen as a plus: <ash> (notes that this query would make a DBA cry ;)
180 return (\@outer_from, $outer_select, $where, $outer_attrs);
183 # Due to a lack of SQLA2 we fall back to crude scans of all the
184 # select/where/order/group attributes, in order to determine what
185 # aliases are neded to fulfill the query. This information is used
186 # throughout the code to prune unnecessary JOINs from the queries
187 # in an attempt to reduce the execution time.
188 # Although the method is pretty horrific, the worst thing that can
189 # happen is for it to fail due to an unqualified column, which in
190 # turn will result in a vocal exception. Qualifying the column will
191 # invariably solve the problem.
192 sub _resolve_aliastypes_from_select_args {
193 my ( $self, $from, $select, $where, $attrs ) = @_;
195 $self->throw_exception ('Unable to analyze custom {from}')
196 if ref $from ne 'ARRAY';
198 # what we will return
201 # see what aliases are there to work with
205 $j = $j->[0] if ref $j eq 'ARRAY';
206 my $al = $j->{-alias}
209 $alias_list->{$al} = $j;
210 $aliases_by_type->{multiplying}{$al} = 1
211 unless $j->{-is_single};
214 # set up a botched SQLA
215 my $sql_maker = $self->sql_maker;
216 my $sep = quotemeta ($self->_sql_maker_opts->{name_sep} || '.');
217 local $sql_maker->{quote_char}; # so that we can regex away
220 my $select_sql = $sql_maker->_recurse_fields ($select);
221 my $where_sql = $sql_maker->where ($where);
222 my $group_by_sql = $sql_maker->_order_by({
223 map { $_ => $attrs->{$_} } qw/group_by having/
225 my @order_by_chunks = (map
226 { ref $_ ? $_->[0] : $_ }
227 $sql_maker->_order_by_chunks ($attrs->{order_by})
230 # match every alias to the sql chunks above
231 for my $alias (keys %$alias_list) {
232 my $al_re = qr/\b $alias $sep/x;
234 for my $piece ($where_sql, $group_by_sql) {
235 $aliases_by_type->{restrict}{$alias} = 1 if ($piece =~ $al_re);
238 for my $piece ($select_sql, @order_by_chunks ) {
239 $aliases_by_type->{select}{$alias} = 1 if ($piece =~ $al_re);
243 # Add any non-left joins to the restriction list (such joins are indeed restrictions)
244 for my $j (values %$alias_list) {
245 my $alias = $j->{-alias} or next;
246 $aliases_by_type->{restrict}{$alias} = 1 if (
247 (not $j->{-join_type})
249 ($j->{-join_type} !~ /^left (?: \s+ outer)? $/xi)
253 # mark all join parents as mentioned
254 # (e.g. join => { cds => 'tracks' } - tracks will need to bring cds too )
255 for my $type (keys %$aliases_by_type) {
256 for my $alias (keys %{$aliases_by_type->{$type}}) {
257 $aliases_by_type->{$type}{$_} = 1
258 for (@{ $alias_list->{$alias}{-join_path} || [] });
262 return $aliases_by_type;
265 sub _resolve_ident_sources {
266 my ($self, $ident) = @_;
268 my $alias2source = {};
271 # the reason this is so contrived is that $ident may be a {from}
272 # structure, specifying multiple tables to join
273 if ( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
274 # this is compat mode for insert/update/delete which do not deal with aliases
275 $alias2source->{me} = $ident;
278 elsif (ref $ident eq 'ARRAY') {
282 if (ref $_ eq 'HASH') {
284 $rs_alias = $tabinfo->{-alias};
286 if (ref $_ eq 'ARRAY' and ref $_->[0] eq 'HASH') {
290 $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-source_handle}->resolve
291 if ($tabinfo->{-source_handle});
295 return ($alias2source, $rs_alias);
298 # Takes $ident, \@column_names
300 # returns { $column_name => \%column_info, ... }
301 # also note: this adds -result_source => $rsrc to the column info
303 # If no columns_names are supplied returns info about *all* columns
305 sub _resolve_column_info {
306 my ($self, $ident, $colnames) = @_;
307 my ($alias2src, $root_alias) = $self->_resolve_ident_sources($ident);
309 my $sep = $self->_sql_maker_opts->{name_sep} || '.';
310 my $qsep = quotemeta $sep;
312 my (%return, %seen_cols, @auto_colnames);
314 # compile a global list of column names, to be able to properly
315 # disambiguate unqualified column names (if at all possible)
316 for my $alias (keys %$alias2src) {
317 my $rsrc = $alias2src->{$alias};
318 for my $colname ($rsrc->columns) {
319 push @{$seen_cols{$colname}}, $alias;
320 push @auto_colnames, "$alias$sep$colname" unless $colnames;
326 grep { @{$seen_cols{$_}} == 1 } (keys %seen_cols),
330 foreach my $col (@$colnames) {
331 my ($alias, $colname) = $col =~ m/^ (?: ([^$qsep]+) $qsep)? (.+) $/x;
334 # see if the column was seen exactly once (so we know which rsrc it came from)
335 if ($seen_cols{$colname} and @{$seen_cols{$colname}} == 1) {
336 $alias = $seen_cols{$colname}[0];
343 my $rsrc = $alias2src->{$alias};
344 $return{$col} = $rsrc && {
345 %{$rsrc->column_info($colname)},
346 -result_source => $rsrc,
347 -source_alias => $alias,
354 # The DBIC relationship chaining implementation is pretty simple - every
355 # new related_relationship is pushed onto the {from} stack, and the {select}
356 # window simply slides further in. This means that when we count somewhere
357 # in the middle, we got to make sure that everything in the join chain is an
358 # actual inner join, otherwise the count will come back with unpredictable
359 # results (a resultset may be generated with _some_ rows regardless of if
360 # the relation which the $rs currently selects has rows or not). E.g.
361 # $artist_rs->cds->count - normally generates:
362 # SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
363 # which actually returns the number of artists * (number of cds || 1)
365 # So what we do here is crawl {from}, determine if the current alias is at
366 # the top of the stack, and if not - make sure the chain is inner-joined down
369 sub _straight_join_to_node {
370 my ($self, $from, $alias) = @_;
372 # subqueries and other oddness are naturally not supported
378 ref $from->[0] ne 'HASH'
382 $from->[0]{-alias} eq $alias # this last bit means $alias is the head of $from - nothing to do
385 # find the current $alias in the $from structure
388 for my $j (@{$from}[1 .. $#$from]) {
389 if ($j->[0]{-alias} eq $alias) {
390 $switch_branch = $j->[0]{-join_path};
395 # something else went quite wrong
396 return $from unless $switch_branch;
398 # So it looks like we will have to switch some stuff around.
399 # local() is useless here as we will be leaving the scope
400 # anyway, and deep cloning is just too fucking expensive
401 # So replace the first hashref in the node arrayref manually
402 my @new_from = ($from->[0]);
403 my $sw_idx = { map { $_ => 1 } @$switch_branch };
405 for my $j (@{$from}[1 .. $#$from]) {
406 my $jalias = $j->[0]{-alias};
408 if ($sw_idx->{$jalias}) {
409 my %attrs = %{$j->[0]};
410 delete $attrs{-join_type};
424 # Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
425 # a condition containing 'me' or other table prefixes will not work
426 # at all. What this code tries to do (badly) is introspect the condition
427 # and remove all column qualifiers. If it bails out early (returns undef)
428 # the calling code should try another approach (e.g. a subquery)
429 sub _strip_cond_qualifiers {
430 my ($self, $where) = @_;
434 # No-op. No condition, we're updating/deleting everything
435 return $cond unless $where;
437 if (ref $where eq 'ARRAY') {
441 foreach my $key (keys %{$_}) {
443 $hash{$1} = $_->{$key};
449 elsif (ref $where eq 'HASH') {
450 if ( (keys %$where) == 1 && ( (keys %{$where})[0] eq '-and' )) {
452 my @cond = @{$where->{-and}};
453 for (my $i = 0; $i < @cond; $i++) {
454 my $entry = $cond[$i];
456 if (ref $entry eq 'HASH') {
457 $hash = $self->_strip_cond_qualifiers($entry);
460 $entry =~ /([^.]+)$/;
461 $hash->{$1} = $cond[++$i];
463 push @{$cond->{-and}}, $hash;
467 foreach my $key (keys %$where) {
469 $cond->{$1} = $where->{$key};