Better refactor
[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
7eb76996 7# display. The arrival of SQLA2 should immediately oboslete 90% of this
d28bb90d 8#
9
10use strict;
11use warnings;
12
13use base 'DBIx::Class::Storage';
14use mro 'c3';
15
16use Carp::Clan qw/^DBIx::Class/;
17
18#
19# This is the code producing joined subqueries like:
20# SELECT me.*, other.* FROM ( SELECT me.* FROM ... ) JOIN other ON ...
21#
22sub _adjust_select_args_for_complex_prefetch {
23 my ($self, $from, $select, $where, $attrs) = @_;
24
25 $self->throw_exception ('Nothing to prefetch... how did we get here?!')
26 if not @{$attrs->{_prefetch_select}};
27
28 $self->throw_exception ('Complex prefetches are not supported on resultsets with a custom from attribute')
29 if (ref $from ne 'ARRAY' || ref $from->[0] ne 'HASH' || ref $from->[1] ne 'ARRAY');
30
31
32 # generate inner/outer attribute lists, remove stuff that doesn't apply
33 my $outer_attrs = { %$attrs };
34 delete $outer_attrs->{$_} for qw/where bind rows offset group_by having/;
35
36 my $inner_attrs = { %$attrs };
37 delete $inner_attrs->{$_} for qw/for collapse _prefetch_select _collapse_order_by select as/;
38
39
40 # bring over all non-collapse-induced order_by into the inner query (if any)
41 # the outer one will have to keep them all
42 delete $inner_attrs->{order_by};
43 if (my $ord_cnt = @{$outer_attrs->{order_by}} - @{$outer_attrs->{_collapse_order_by}} ) {
44 $inner_attrs->{order_by} = [
45 @{$outer_attrs->{order_by}}[ 0 .. $ord_cnt - 1]
46 ];
47 }
48
49
50 # generate the inner/outer select lists
51 # for inside we consider only stuff *not* brought in by the prefetch
52 # on the outside we substitute any function for its alias
53 my $outer_select = [ @$select ];
54 my $inner_select = [];
55 for my $i (0 .. ( @$outer_select - @{$outer_attrs->{_prefetch_select}} - 1) ) {
56 my $sel = $outer_select->[$i];
57
58 if (ref $sel eq 'HASH' ) {
59 $sel->{-as} ||= $attrs->{as}[$i];
60 $outer_select->[$i] = join ('.', $attrs->{alias}, ($sel->{-as} || "inner_column_$i") );
61 }
62
63 push @$inner_select, $sel;
64 }
65
ad630f4b 66
67 # scan the from spec against different attributes, and see which joins are needed
68 # in what role
69 my $inner_aliaslist =
70 $self->_resolve_aliases_from_select_args( $from, $where, $inner_select, $inner_attrs );
71 my $outer_aliaslist =
72 $self->_resolve_aliases_from_select_args( $from, $where, $outer_select, $outer_attrs );
73
74
75
d28bb90d 76 # normalize a copy of $from, so it will be easier to work with further
77 # down (i.e. promote the initial hashref to an AoH)
78 $from = [ @$from ];
79 $from->[0] = [ $from->[0] ];
d28bb90d 80
d28bb90d 81
d28bb90d 82 # construct the inner $from for the subquery
ad630f4b 83 my %inner_joins = (map { %{$inner_aliaslist->{$_} || {}} } (qw/restrict select/) );
d28bb90d 84 my @inner_from;
85 for my $j (@$from) {
86 push @inner_from, $j if $inner_joins{$j->[0]{-alias}};
87 }
88
ad630f4b 89
d28bb90d 90 # if a multi-type join was needed in the subquery ("multi" is indicated by
91 # presence in {collapse}) - add a group_by to simulate the collapse in the subq
92 unless ($inner_attrs->{group_by}) {
93 for my $alias (keys %inner_joins) {
94
95 # the dot comes from some weirdness in collapse
96 # remove after the rewrite
97 if ($attrs->{collapse}{".$alias"}) {
98 $inner_attrs->{group_by} ||= $inner_select;
99 last;
100 }
101 }
102 }
103
104 # demote the inner_from head
105 $inner_from[0] = $inner_from[0][0];
106
107 # generate the subquery
108 my $subq = $self->_select_args_to_query (
109 \@inner_from,
110 $inner_select,
111 $where,
112 $inner_attrs,
113 );
114
115 my $subq_joinspec = {
116 -alias => $attrs->{alias},
117 -source_handle => $inner_from[0]{-source_handle},
118 $attrs->{alias} => $subq,
119 };
120
121 # Generate the outer from - this is relatively easy (really just replace
122 # the join slot with the subquery), with a major caveat - we can not
123 # join anything that is non-selecting (not part of the prefetch), but at
124 # the same time is a multi-type relationship, as it will explode the result.
125 #
126 # There are two possibilities here
127 # - either the join is non-restricting, in which case we simply throw it away
128 # - it is part of the restrictions, in which case we need to collapse the outer
129 # result by tackling yet another group_by to the outside of the query
130
131 # so first generate the outer_from, up to the substitution point
132 my @outer_from;
133 while (my $j = shift @$from) {
134 if ($j->[0]{-alias} eq $attrs->{alias}) { # time to swap
135 push @outer_from, [
136 $subq_joinspec,
137 @{$j}[1 .. $#$j],
138 ];
139 last; # we'll take care of what's left in $from below
140 }
141 else {
142 push @outer_from, $j;
143 }
144 }
145
146 # see what's left - throw away if not selecting/restricting
147 # also throw in a group_by if restricting to guard against
148 # cross-join explosions
149 #
150 while (my $j = shift @$from) {
151 my $alias = $j->[0]{-alias};
152
ad630f4b 153 if ($outer_aliaslist->{select}{$alias}) {
d28bb90d 154 push @outer_from, $j;
155 }
ad630f4b 156 elsif ($outer_aliaslist->{restrict}{$alias}) {
d28bb90d 157 push @outer_from, $j;
158
159 # FIXME - this should be obviated by SQLA2, as I'll be able to
160 # have restrict_inner and restrict_outer... or something to that
161 # effect... I think...
162
163 # FIXME2 - I can't find a clean way to determine if a particular join
164 # is a multi - instead I am just treating everything as a potential
165 # explosive join (ribasushi)
166 #
167 # if (my $handle = $j->[0]{-source_handle}) {
168 # my $rsrc = $handle->resolve;
169 # ... need to bail out of the following if this is not a multi,
170 # as it will be much easier on the db ...
171
172 $outer_attrs->{group_by} ||= $outer_select;
173 # }
174 }
175 }
176
177 # demote the outer_from head
178 $outer_from[0] = $outer_from[0][0];
179
180 # This is totally horrific - the $where ends up in both the inner and outer query
181 # Unfortunately not much can be done until SQLA2 introspection arrives, and even
182 # then if where conditions apply to the *right* side of the prefetch, you may have
183 # to both filter the inner select (e.g. to apply a limit) and then have to re-filter
184 # the outer select to exclude joins you didin't want in the first place
185 #
186 # OTOH it can be seen as a plus: <ash> (notes that this query would make a DBA cry ;)
187 return (\@outer_from, $outer_select, $where, $outer_attrs);
188}
189
ad630f4b 190# Due to a lack of SQLA2 we fall back to crude scans of all the
191# select/where/order/group attributes, in order to determine what
192# aliases are neded to fulfill the query. This information is used
193# throughout the code to prune unnecessary JOINs from the queries
194# in an attempt to reduce the execution time.
195# Although the method is pretty horrific, the worst thing that can
196# happen is for it to fail due to an unqualified column, which in
197# turn will result in a vocal exception. Qualifying the column will
198# invariably solve the problem.
546f1cd9 199sub _resolve_aliases_from_select_args {
200 my ( $self, $from, $where, $select, $attrs ) = @_;
201
ad630f4b 202 $self->throw_exception ('Unable to analyze custom {from}')
203 if ref $from ne 'ARRAY';
546f1cd9 204
ad630f4b 205 # what we will return
206 my $alias_map;
546f1cd9 207
ad630f4b 208 # see what aliases are there to work with
209 my $alias_list;
210 my @from = @$from; # if I don't copy weird shit happens
211 for my $j (@from) {
212 $j = $j->[0] if ref $j eq 'ARRAY';
213 $alias_list->{$j->{-alias}} = $j;
546f1cd9 214 }
546f1cd9 215
ad630f4b 216 # set up a botched SQLA
217 my $sql_maker = $self->sql_maker;
218 my $sep = quotemeta ($self->_sql_maker_opts->{name_sep} || '.');
219 local $sql_maker->{quote_char}; # so that we can regex away
07f31d19 220
221
ad630f4b 222 my $select_sql = $sql_maker->_recurse_fields ($select);
223 my $where_sql = $sql_maker->where ($where);
224 my $group_by_sql = $sql_maker->_order_by({
225 map { $_ => $attrs->{$_} } qw/group_by having/
226 });
227 my @order_by_chunks = (map
228 { ref $_ ? $_->[0] : $_ }
229 $sql_maker->_order_by_chunks ($attrs->{order_by})
230 );
07f31d19 231
ad630f4b 232 # match every alias to the sql chunks above
233 for my $alias (keys %$alias_list) {
234 my $al_re = qr/\b $alias $sep/x;
07f31d19 235
ad630f4b 236 for my $piece ($where_sql, $group_by_sql) {
237 $alias_map->{restrict}{$alias} = 1 if ($piece =~ $al_re);
238 }
07f31d19 239
ad630f4b 240 for my $piece ($select_sql, @order_by_chunks ) {
241 $alias_map->{select}{$alias} = 1 if ($piece =~ $al_re);
07f31d19 242 }
243 }
244
245 # Add any non-left joins to the restriction list (such joins are indeed restrictions)
ad630f4b 246 for my $j (values %$alias_list) {
07f31d19 247 my $alias = $j->{-alias} or next;
ad630f4b 248 $alias_map->{restrict}{$alias} = 1 if (
07f31d19 249 (not $j->{-join_type})
250 or
251 ($j->{-join_type} !~ /^left (?: \s+ outer)? $/xi)
252 );
253 }
254
255 # mark all join parents as mentioned
256 # (e.g. join => { cds => 'tracks' } - tracks will need to bring cds too )
ad630f4b 257 for my $collection (qw/restrict select/) {
258 for my $alias (keys %{$alias_map->{$collection}||{}}) {
259 $alias_map->{$collection}{$_} = 1
260 for (@{ $alias_list->{$alias}{-join_path} || [] });
07f31d19 261 }
262 }
ad630f4b 263
264 return $alias_map;
07f31d19 265}
266
d28bb90d 267sub _resolve_ident_sources {
268 my ($self, $ident) = @_;
269
270 my $alias2source = {};
271 my $rs_alias;
272
273 # the reason this is so contrived is that $ident may be a {from}
274 # structure, specifying multiple tables to join
275 if ( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
276 # this is compat mode for insert/update/delete which do not deal with aliases
277 $alias2source->{me} = $ident;
278 $rs_alias = 'me';
279 }
280 elsif (ref $ident eq 'ARRAY') {
281
282 for (@$ident) {
283 my $tabinfo;
284 if (ref $_ eq 'HASH') {
285 $tabinfo = $_;
286 $rs_alias = $tabinfo->{-alias};
287 }
288 if (ref $_ eq 'ARRAY' and ref $_->[0] eq 'HASH') {
289 $tabinfo = $_->[0];
290 }
291
292 $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-source_handle}->resolve
293 if ($tabinfo->{-source_handle});
294 }
295 }
296
297 return ($alias2source, $rs_alias);
298}
299
300# Takes $ident, \@column_names
301#
302# returns { $column_name => \%column_info, ... }
303# also note: this adds -result_source => $rsrc to the column info
304#
09e14fdc 305# If no columns_names are supplied returns info about *all* columns
306# for all sources
d28bb90d 307sub _resolve_column_info {
308 my ($self, $ident, $colnames) = @_;
309 my ($alias2src, $root_alias) = $self->_resolve_ident_sources($ident);
310
311 my $sep = $self->_sql_maker_opts->{name_sep} || '.';
09e14fdc 312 my $qsep = quotemeta $sep;
d28bb90d 313
09e14fdc 314 my (%return, %seen_cols, @auto_colnames);
d28bb90d 315
316 # compile a global list of column names, to be able to properly
317 # disambiguate unqualified column names (if at all possible)
318 for my $alias (keys %$alias2src) {
319 my $rsrc = $alias2src->{$alias};
320 for my $colname ($rsrc->columns) {
321 push @{$seen_cols{$colname}}, $alias;
09e14fdc 322 push @auto_colnames, "$alias$sep$colname" unless $colnames;
d28bb90d 323 }
324 }
325
09e14fdc 326 $colnames ||= [
327 @auto_colnames,
328 grep { @{$seen_cols{$_}} == 1 } (keys %seen_cols),
329 ];
330
d28bb90d 331 COLUMN:
332 foreach my $col (@$colnames) {
09e14fdc 333 my ($alias, $colname) = $col =~ m/^ (?: ([^$qsep]+) $qsep)? (.+) $/x;
d28bb90d 334
335 unless ($alias) {
336 # see if the column was seen exactly once (so we know which rsrc it came from)
337 if ($seen_cols{$colname} and @{$seen_cols{$colname}} == 1) {
338 $alias = $seen_cols{$colname}[0];
339 }
340 else {
341 next COLUMN;
342 }
343 }
344
345 my $rsrc = $alias2src->{$alias};
346 $return{$col} = $rsrc && {
347 %{$rsrc->column_info($colname)},
348 -result_source => $rsrc,
349 -source_alias => $alias,
350 };
351 }
352
353 return \%return;
354}
355
289ac713 356# The DBIC relationship chaining implementation is pretty simple - every
357# new related_relationship is pushed onto the {from} stack, and the {select}
358# window simply slides further in. This means that when we count somewhere
359# in the middle, we got to make sure that everything in the join chain is an
360# actual inner join, otherwise the count will come back with unpredictable
361# results (a resultset may be generated with _some_ rows regardless of if
362# the relation which the $rs currently selects has rows or not). E.g.
363# $artist_rs->cds->count - normally generates:
364# SELECT COUNT( * ) FROM artist me LEFT JOIN cd cds ON cds.artist = me.artistid
365# which actually returns the number of artists * (number of cds || 1)
366#
367# So what we do here is crawl {from}, determine if the current alias is at
368# the top of the stack, and if not - make sure the chain is inner-joined down
369# to the root.
370#
371sub _straight_join_to_node {
372 my ($self, $from, $alias) = @_;
373
374 # subqueries and other oddness are naturally not supported
375 return $from if (
376 ref $from ne 'ARRAY'
377 ||
378 @$from <= 1
379 ||
380 ref $from->[0] ne 'HASH'
381 ||
382 ! $from->[0]{-alias}
383 ||
7eb76996 384 $from->[0]{-alias} eq $alias # this last bit means $alias is the head of $from - nothing to do
289ac713 385 );
386
387 # find the current $alias in the $from structure
388 my $switch_branch;
389 JOINSCAN:
390 for my $j (@{$from}[1 .. $#$from]) {
391 if ($j->[0]{-alias} eq $alias) {
392 $switch_branch = $j->[0]{-join_path};
393 last JOINSCAN;
394 }
395 }
396
7eb76996 397 # something else went quite wrong
289ac713 398 return $from unless $switch_branch;
399
400 # So it looks like we will have to switch some stuff around.
401 # local() is useless here as we will be leaving the scope
402 # anyway, and deep cloning is just too fucking expensive
7eb76996 403 # So replace the first hashref in the node arrayref manually
289ac713 404 my @new_from = ($from->[0]);
405 my $sw_idx = { map { $_ => 1 } @$switch_branch };
406
407 for my $j (@{$from}[1 .. $#$from]) {
408 my $jalias = $j->[0]{-alias};
409
410 if ($sw_idx->{$jalias}) {
411 my %attrs = %{$j->[0]};
412 delete $attrs{-join_type};
413 push @new_from, [
414 \%attrs,
415 @{$j}[ 1 .. $#$j ],
416 ];
417 }
418 else {
419 push @new_from, $j;
420 }
421 }
422
423 return \@new_from;
424}
425
bac6c4fb 426# Most databases do not allow aliasing of tables in UPDATE/DELETE. Thus
427# a condition containing 'me' or other table prefixes will not work
428# at all. What this code tries to do (badly) is introspect the condition
429# and remove all column qualifiers. If it bails out early (returns undef)
430# the calling code should try another approach (e.g. a subquery)
431sub _strip_cond_qualifiers {
432 my ($self, $where) = @_;
433
434 my $cond = {};
435
436 # No-op. No condition, we're updating/deleting everything
437 return $cond unless $where;
438
439 if (ref $where eq 'ARRAY') {
440 $cond = [
441 map {
442 my %hash;
443 foreach my $key (keys %{$_}) {
444 $key =~ /([^.]+)$/;
445 $hash{$1} = $_->{$key};
446 }
447 \%hash;
448 } @$where
449 ];
450 }
451 elsif (ref $where eq 'HASH') {
452 if ( (keys %$where) == 1 && ( (keys %{$where})[0] eq '-and' )) {
453 $cond->{-and} = [];
454 my @cond = @{$where->{-and}};
455 for (my $i = 0; $i < @cond; $i++) {
456 my $entry = $cond[$i];
457 my $hash;
458 if (ref $entry eq 'HASH') {
459 $hash = $self->_strip_cond_qualifiers($entry);
460 }
461 else {
462 $entry =~ /([^.]+)$/;
463 $hash->{$1} = $cond[++$i];
464 }
465 push @{$cond->{-and}}, $hash;
466 }
467 }
468 else {
469 foreach my $key (keys %$where) {
470 $key =~ /([^.]+)$/;
471 $cond->{$1} = $where->{$key};
472 }
473 }
474 }
475 else {
476 return undef;
477 }
478
479 return $cond;
480}
481
482
d28bb90d 4831;