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