Commit | Line | Data |
6f4ddea1 |
1 | package # Hide from PAUSE |
855c6fd0 |
2 | DBIx::Class::SQLAHacks; |
6f4ddea1 |
3 | |
998373c2 |
4 | # This module is a subclass of SQL::Abstract::Limit and includes a number |
5 | # of DBIC-specific workarounds, not yet suitable for inclusion into the |
6 | # SQLA core |
7 | |
6f4ddea1 |
8 | use base qw/SQL::Abstract::Limit/; |
e3764383 |
9 | use strict; |
10 | use warnings; |
6298a324 |
11 | use List::Util 'first'; |
12 | use Sub::Name 'subname'; |
13 | use namespace::clean; |
ac322978 |
14 | use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/; |
b2b22cd6 |
15 | |
16 | BEGIN { |
17 | # reinstall the carp()/croak() functions imported into SQL::Abstract |
18 | # as Carp and Carp::Clan do not like each other much |
19 | no warnings qw/redefine/; |
20 | no strict qw/refs/; |
21 | for my $f (qw/carp croak/) { |
329d7385 |
22 | |
b2b22cd6 |
23 | my $orig = \&{"SQL::Abstract::$f"}; |
6298a324 |
24 | *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" => |
8637bb24 |
25 | sub { |
26 | if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) { |
27 | __PACKAGE__->can($f)->(@_); |
28 | } |
29 | else { |
30 | goto $orig; |
31 | } |
32 | }; |
b2b22cd6 |
33 | } |
34 | } |
6f4ddea1 |
35 | |
e9657379 |
36 | # the "oh noes offset/top without limit" constant |
37 | sub __max_int { 0xFFFFFFFF }; |
38 | |
998373c2 |
39 | |
40 | # Tries to determine limit dialect. |
41 | # |
6f4ddea1 |
42 | sub new { |
43 | my $self = shift->SUPER::new(@_); |
44 | |
45 | # This prevents the caching of $dbh in S::A::L, I believe |
46 | # If limit_dialect is a ref (like a $dbh), go ahead and replace |
47 | # it with what it resolves to: |
48 | $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect}) |
49 | if ref $self->{limit_dialect}; |
50 | |
51 | $self; |
52 | } |
53 | |
a54bd479 |
54 | # !!! THIS IS ALSO HORRIFIC !!! /me ashamed |
55 | # |
75f025cf |
56 | # Generates inner/outer select lists for various limit dialects |
81446c4f |
57 | # which result in one or more subqueries (e.g. RNO, Top, RowNum) |
58 | # Any non-root-table columns need to have their table qualifier |
a54bd479 |
59 | # turned into a column alias (otherwise names in subqueries clash |
81446c4f |
60 | # and/or lose their source table) |
a54bd479 |
61 | # |
75f025cf |
62 | # Returns inner/outer strings of SQL QUOTED selectors with aliases |
a54bd479 |
63 | # (to be used in whatever select statement), and an alias index hashref |
64 | # of QUOTED SEL => QUOTED ALIAS pairs (to maybe be used for string-subst |
75f025cf |
65 | # higher up). |
66 | # If an order_by is supplied, the inner select needs to bring out columns |
67 | # used in implicit (non-selected) orders, and the order condition itself |
68 | # needs to be realiased to the proper names in the outer query. Thus we |
69 | # also return a hashref (order doesn't matter) of QUOTED EXTRA-SEL => |
70 | # QUOTED ALIAS pairs, which is a list of extra selectors that do *not* |
71 | # exist in the original select list |
a54bd479 |
72 | |
73 | sub _subqueried_limit_attrs { |
75f025cf |
74 | my ($self, $rs_attrs) = @_; |
81446c4f |
75 | |
a54bd479 |
76 | croak 'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)' |
77 | unless ref ($rs_attrs) eq 'HASH'; |
78 | |
79 | my ($re_sep, $re_alias) = map { quotemeta $_ } ( |
80 | $self->name_sep || '.', |
81 | $rs_attrs->{alias}, |
82 | ); |
81446c4f |
83 | |
a54bd479 |
84 | # correlate select and as, build selection index |
85 | my (@sel, $in_sel_index); |
81446c4f |
86 | for my $i (0 .. $#{$rs_attrs->{select}}) { |
a54bd479 |
87 | |
81446c4f |
88 | my $s = $rs_attrs->{select}[$i]; |
a54bd479 |
89 | my $sql_sel = $self->_recurse_fields ($s); |
90 | my $sql_alias = (ref $s) eq 'HASH' ? $s->{-as} : undef; |
91 | |
92 | |
81446c4f |
93 | push @sel, { |
a54bd479 |
94 | sql => $sql_sel, |
81446c4f |
95 | unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) }, |
96 | as => |
a54bd479 |
97 | $sql_alias |
81446c4f |
98 | || |
99 | $rs_attrs->{as}[$i] |
100 | || |
101 | croak "Select argument $i ($s) without corresponding 'as'" |
102 | , |
103 | }; |
a54bd479 |
104 | |
105 | $in_sel_index->{$sql_sel}++; |
106 | $in_sel_index->{$self->_quote ($sql_alias)}++ if $sql_alias; |
107 | |
75f025cf |
108 | # record unqualified versions too, so we do not have |
109 | # to reselect the same column twice (in qualified and |
110 | # unqualified form) |
111 | if (! ref $s && $sql_sel =~ / $re_sep (.+) $/x) { |
112 | $in_sel_index->{$1}++; |
113 | } |
81446c4f |
114 | } |
115 | |
81446c4f |
116 | |
117 | # re-alias and remove any name separators from aliases, |
118 | # unless we are dealing with the current source alias |
a54bd479 |
119 | # (which will transcend the subqueries as it is necessary |
81446c4f |
120 | # for possible further chaining) |
a54bd479 |
121 | my (@in_sel, @out_sel, %renamed); |
81446c4f |
122 | for my $node (@sel) { |
6298a324 |
123 | if (first { $_ =~ / (?<! $re_alias ) $re_sep /x } ($node->{as}, $node->{unquoted_sql}) ) { |
a54bd479 |
124 | $node->{as} =~ s/ $re_sep /__/xg; |
125 | my $quoted_as = $self->_quote($node->{as}); |
126 | push @in_sel, sprintf '%s AS %s', $node->{sql}, $quoted_as; |
127 | push @out_sel, $quoted_as; |
128 | $renamed{$node->{sql}} = $quoted_as; |
81446c4f |
129 | } |
130 | else { |
a54bd479 |
131 | push @in_sel, $node->{sql}; |
132 | push @out_sel, $self->_quote ($node->{as}); |
81446c4f |
133 | } |
134 | } |
135 | |
75f025cf |
136 | # see if the order gives us anything |
a54bd479 |
137 | my %extra_order_sel; |
75f025cf |
138 | for my $chunk ($self->_order_by_chunks ($rs_attrs->{order_by})) { |
139 | # order with bind |
140 | $chunk = $chunk->[0] if (ref $chunk) eq 'ARRAY'; |
141 | $chunk =~ s/\s+ (?: ASC|DESC ) \s* $//ix; |
a54bd479 |
142 | |
75f025cf |
143 | next if $in_sel_index->{$chunk}; |
a54bd479 |
144 | |
75f025cf |
145 | $extra_order_sel{$chunk} ||= $self->_quote ( |
146 | 'ORDER__BY__' . scalar keys %extra_order_sel |
147 | ); |
a54bd479 |
148 | } |
75f025cf |
149 | |
a54bd479 |
150 | return ( |
151 | (map { join (', ', @$_ ) } ( |
152 | \@in_sel, |
153 | \@out_sel) |
154 | ), |
155 | \%renamed, |
156 | keys %extra_order_sel ? \%extra_order_sel : (), |
157 | ); |
81446c4f |
158 | } |
159 | |
a54bd479 |
160 | # ANSI standard Limit/Offset implementation. DB2 and MSSQL >= 2005 use this |
6f4ddea1 |
161 | sub _RowNumberOver { |
a6b68a60 |
162 | my ($self, $sql, $rs_attrs, $rows, $offset ) = @_; |
6f4ddea1 |
163 | |
81446c4f |
164 | # mangle the input sql as we will be replacing the selector |
165 | $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix |
cb478051 |
166 | or croak "Unrecognizable SELECT: $sql"; |
167 | |
a54bd479 |
168 | # get selectors, and scan the order_by (if any) |
75f025cf |
169 | my ($in_sel, $out_sel, $alias_map, $extra_order_sel) |
170 | = $self->_subqueried_limit_attrs ( $rs_attrs ); |
81446c4f |
171 | |
a6b68a60 |
172 | # make up an order if none exists |
a54bd479 |
173 | my $requested_order = (delete $rs_attrs->{order_by}) || $self->_rno_default_order; |
174 | my $rno_ord = $self->_order_by ($requested_order); |
175 | |
176 | # this is the order supplement magic |
177 | my $mid_sel = $out_sel; |
178 | if ($extra_order_sel) { |
20f44a33 |
179 | for my $extra_col (sort |
180 | { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} } |
181 | keys %$extra_order_sel |
182 | ) { |
a54bd479 |
183 | $in_sel .= sprintf (', %s AS %s', |
184 | $extra_col, |
185 | $extra_order_sel->{$extra_col}, |
186 | ); |
187 | |
188 | $mid_sel .= ', ' . $extra_order_sel->{$extra_col}; |
189 | } |
190 | } |
191 | |
192 | # and this is order re-alias magic |
193 | for ($extra_order_sel, $alias_map) { |
194 | for my $col (keys %$_) { |
195 | my $re_col = quotemeta ($col); |
196 | $rno_ord =~ s/$re_col/$_->{$col}/; |
197 | } |
198 | } |
6f4ddea1 |
199 | |
81446c4f |
200 | # whatever is left of the order_by (only where is processed at this point) |
a6b68a60 |
201 | my $group_having = $self->_parse_rs_attrs($rs_attrs); |
6f4ddea1 |
202 | |
a6b68a60 |
203 | my $qalias = $self->_quote ($rs_attrs->{alias}); |
81446c4f |
204 | my $idx_name = $self->_quote ('rno__row__index'); |
205 | |
cb478051 |
206 | $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, ); |
6f4ddea1 |
207 | |
a54bd479 |
208 | SELECT $out_sel FROM ( |
209 | SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM ( |
210 | SELECT $in_sel ${sql}${group_having} |
cb478051 |
211 | ) $qalias |
75f025cf |
212 | ) $qalias WHERE $idx_name BETWEEN %u AND %u |
6553ac38 |
213 | |
214 | EOS |
215 | |
216 | $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger |
6f4ddea1 |
217 | return $sql; |
218 | } |
219 | |
84ddb3da |
220 | # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) ) |
221 | sub _rno_default_order { |
222 | return undef; |
223 | } |
224 | |
193590c2 |
225 | # Informix specific limit, almost like LIMIT/OFFSET |
226 | sub _SkipFirst { |
a6b68a60 |
227 | my ($self, $sql, $rs_attrs, $rows, $offset) = @_; |
193590c2 |
228 | |
229 | $sql =~ s/^ \s* SELECT \s+ //ix |
230 | or croak "Unrecognizable SELECT: $sql"; |
231 | |
232 | return sprintf ('SELECT %s%s%s%s', |
233 | $offset |
75f025cf |
234 | ? sprintf ('SKIP %u ', $offset) |
193590c2 |
235 | : '' |
236 | , |
75f025cf |
237 | sprintf ('FIRST %u ', $rows), |
193590c2 |
238 | $sql, |
a6b68a60 |
239 | $self->_parse_rs_attrs ($rs_attrs), |
193590c2 |
240 | ); |
241 | } |
242 | |
145b2a3d |
243 | # Firebird specific limit, reverse of _SkipFirst for Informix |
244 | sub _FirstSkip { |
a6b68a60 |
245 | my ($self, $sql, $rs_attrs, $rows, $offset) = @_; |
145b2a3d |
246 | |
247 | $sql =~ s/^ \s* SELECT \s+ //ix |
248 | or croak "Unrecognizable SELECT: $sql"; |
249 | |
250 | return sprintf ('SELECT %s%s%s%s', |
75f025cf |
251 | sprintf ('FIRST %u ', $rows), |
145b2a3d |
252 | $offset |
75f025cf |
253 | ? sprintf ('SKIP %u ', $offset) |
145b2a3d |
254 | : '' |
255 | , |
256 | $sql, |
a6b68a60 |
257 | $self->_parse_rs_attrs ($rs_attrs), |
145b2a3d |
258 | ); |
259 | } |
260 | |
81446c4f |
261 | # WhOracle limits |
262 | sub _RowNum { |
263 | my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_; |
264 | |
265 | # mangle the input sql as we will be replacing the selector |
266 | $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix |
267 | or croak "Unrecognizable SELECT: $sql"; |
268 | |
a54bd479 |
269 | my ($insel, $outsel) = $self->_subqueried_limit_attrs ($rs_attrs); |
81446c4f |
270 | |
271 | my $qalias = $self->_quote ($rs_attrs->{alias}); |
272 | my $idx_name = $self->_quote ('rownum__index'); |
273 | my $order_group_having = $self->_parse_rs_attrs($rs_attrs); |
274 | |
275 | $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, ); |
276 | |
277 | SELECT $outsel FROM ( |
278 | SELECT $outsel, ROWNUM $idx_name FROM ( |
279 | SELECT $insel ${sql}${order_group_having} |
280 | ) $qalias |
75f025cf |
281 | ) $qalias WHERE $idx_name BETWEEN %u AND %u |
81446c4f |
282 | |
283 | EOS |
284 | |
285 | $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger |
286 | return $sql; |
287 | } |
288 | |
a54bd479 |
289 | # Crappy Top based Limit/Offset support. Legacy for MSSQL < 2005 |
15827712 |
290 | sub _Top { |
a6b68a60 |
291 | my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_; |
15827712 |
292 | |
81446c4f |
293 | # mangle the input sql as we will be replacing the selector |
294 | $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix |
b1e1d073 |
295 | or croak "Unrecognizable SELECT: $sql"; |
b1e1d073 |
296 | |
81446c4f |
297 | # get selectors |
a54bd479 |
298 | my ($in_sel, $out_sel, $alias_map, $extra_order_sel) |
75f025cf |
299 | = $self->_subqueried_limit_attrs ($rs_attrs); |
81446c4f |
300 | |
a54bd479 |
301 | my $requested_order = delete $rs_attrs->{order_by}; |
81446c4f |
302 | |
a54bd479 |
303 | my $order_by_requested = $self->_order_by ($requested_order); |
304 | |
305 | # make up an order unless supplied |
306 | my $inner_order = ($order_by_requested |
307 | ? $requested_order |
81446c4f |
308 | : [ map |
a54bd479 |
309 | { join ('', $rs_attrs->{alias}, $self->{name_sep}||'.', $_ ) } |
310 | ( $rs_attrs->{_rsroot_source_handle}->resolve->_pri_cols ) |
81446c4f |
311 | ] |
a54bd479 |
312 | ); |
81446c4f |
313 | |
a54bd479 |
314 | my ($order_by_inner, $order_by_reversed); |
81446c4f |
315 | |
a54bd479 |
316 | # localise as we already have all the bind values we need |
317 | { |
318 | local $self->{order_bind}; |
319 | $order_by_inner = $self->_order_by ($inner_order); |
ac93965c |
320 | |
a54bd479 |
321 | my @out_chunks; |
322 | for my $ch ($self->_order_by_chunks ($inner_order)) { |
323 | $ch = $ch->[0] if ref $ch eq 'ARRAY'; |
20f44a33 |
324 | |
a54bd479 |
325 | $ch =~ s/\s+ ( ASC|DESC ) \s* $//ix; |
326 | my $dir = uc ($1||'ASC'); |
b1e1d073 |
327 | |
a54bd479 |
328 | push @out_chunks, \join (' ', $ch, $dir eq 'ASC' ? 'DESC' : 'ASC' ); |
329 | } |
b1e1d073 |
330 | |
20f44a33 |
331 | $order_by_reversed = $self->_order_by (\@out_chunks); |
42e5b103 |
332 | } |
b1e1d073 |
333 | |
a54bd479 |
334 | # this is the order supplement magic |
335 | my $mid_sel = $out_sel; |
336 | if ($extra_order_sel) { |
20f44a33 |
337 | for my $extra_col (sort |
338 | { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} } |
339 | keys %$extra_order_sel |
340 | ) { |
a54bd479 |
341 | $in_sel .= sprintf (', %s AS %s', |
342 | $extra_col, |
343 | $extra_order_sel->{$extra_col}, |
42e5b103 |
344 | ); |
b1e1d073 |
345 | |
a54bd479 |
346 | $mid_sel .= ', ' . $extra_order_sel->{$extra_col}; |
42e5b103 |
347 | } |
25abda27 |
348 | |
349 | # since whatever order bindvals there are, they will be realiased |
350 | # and need to show up in front of the entire initial inner subquery |
351 | # Unshift *from_bind* to make this happen (horrible, horrible, but |
352 | # we don't have another mechanism yet) |
353 | unshift @{$self->{from_bind}}, @{$self->{order_bind}}; |
b1e1d073 |
354 | } |
355 | |
a54bd479 |
356 | # and this is order re-alias magic |
357 | for my $map ($extra_order_sel, $alias_map) { |
358 | for my $col (keys %$map) { |
359 | my $re_col = quotemeta ($col); |
360 | $_ =~ s/$re_col/$map->{$col}/ |
361 | for ($order_by_reversed, $order_by_requested); |
b1e1d073 |
362 | } |
363 | } |
15827712 |
364 | |
a54bd479 |
365 | # generate the rest of the sql |
366 | my $grpby_having = $self->_parse_rs_attrs ($rs_attrs); |
15827712 |
367 | |
a54bd479 |
368 | my $quoted_rs_alias = $self->_quote ($rs_attrs->{alias}); |
b1e1d073 |
369 | |
75f025cf |
370 | $sql = sprintf ('SELECT TOP %u %s %s %s %s', |
a54bd479 |
371 | $rows + ($offset||0), |
372 | $in_sel, |
373 | $sql, |
374 | $grpby_having, |
375 | $order_by_inner, |
376 | ); |
15827712 |
377 | |
75f025cf |
378 | $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s', |
a54bd479 |
379 | $rows, |
380 | $mid_sel, |
381 | $sql, |
382 | $quoted_rs_alias, |
383 | $order_by_reversed, |
384 | ) if $offset; |
15827712 |
385 | |
75f025cf |
386 | $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s', |
a54bd479 |
387 | $rows, |
a54bd479 |
388 | $out_sel, |
389 | $sql, |
390 | $quoted_rs_alias, |
20f44a33 |
391 | $order_by_requested, |
76fc0d71 |
392 | ) if ( ($offset && $order_by_requested) || ($mid_sel ne $out_sel) ); |
b1e1d073 |
393 | |
75f025cf |
394 | $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger |
395 | return $sql; |
396 | } |
397 | |
3f528319 |
398 | # This for Sybase ASE, to use SET ROWCOUNT when there is no offset, and |
399 | # GenericSubQ otherwise. |
400 | sub _RowCountOrGenericSubQ { |
401 | my $self = shift; |
402 | my ($sql, $rs_attrs, $rows, $offset) = @_; |
403 | |
404 | return $self->_GenericSubQ(@_) if $offset; |
405 | |
406 | return sprintf <<"EOF", $rows, $sql; |
407 | SET ROWCOUNT %d |
408 | %s |
409 | SET ROWCOUNT 0 |
410 | EOF |
411 | } |
412 | |
75f025cf |
413 | # This is the most evil limit "dialect" (more of a hack) for *really* |
414 | # stupid databases. It works by ordering the set by some unique column, |
415 | # and calculating amount of rows that have a less-er value (thus |
416 | # emulating a RowNum-like index). Of course this implies the set can |
417 | # only be ordered by a single unique columns. |
418 | sub _GenericSubQ { |
419 | my ($self, $sql, $rs_attrs, $rows, $offset) = @_; |
420 | |
421 | my $root_rsrc = $rs_attrs->{_rsroot_source_handle}->resolve; |
422 | my $root_tbl_name = $root_rsrc->name; |
423 | |
424 | # mangle the input sql as we will be replacing the selector |
425 | $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix |
426 | or croak "Unrecognizable SELECT: $sql"; |
427 | |
428 | my ($order_by, @rest) = do { |
429 | local $self->{quote_char}; |
430 | $self->_order_by_chunks ($rs_attrs->{order_by}) |
431 | }; |
432 | |
433 | unless ( |
434 | $order_by |
435 | && |
436 | ! @rest |
437 | && |
438 | ( ! ref $order_by |
439 | || |
440 | ( ref $order_by eq 'ARRAY' and @$order_by == 1 ) |
441 | ) |
442 | ) { |
443 | croak ( |
444 | 'Generic Subquery Limit does not work on resultsets without an order, or resultsets ' |
445 | . 'with complex order criteria (multicolumn and/or functions). Provide a single, ' |
446 | . 'unique-column order criteria.' |
447 | ); |
448 | } |
449 | |
450 | ($order_by) = @$order_by if ref $order_by; |
451 | |
452 | $order_by =~ s/\s+ ( ASC|DESC ) \s* $//ix; |
453 | my $direction = lc ($1 || 'asc'); |
454 | |
455 | my ($unq_sort_col) = $order_by =~ /(?:^|\.)([^\.]+)$/; |
456 | |
457 | my $inf = $root_rsrc->storage->_resolve_column_info ( |
458 | $rs_attrs->{from}, [$order_by, $unq_sort_col] |
459 | ); |
460 | |
461 | my $ord_colinfo = $inf->{$order_by} || croak "Unable to determine source of order-criteria '$order_by'"; |
462 | |
463 | if ($ord_colinfo->{-result_source}->name ne $root_tbl_name) { |
464 | croak "Generic Subquery Limit order criteria can be only based on the root-source '" |
465 | . $root_rsrc->source_name . "' (aliased as '$rs_attrs->{alias}')"; |
466 | } |
467 | |
468 | # make sure order column is qualified |
469 | $order_by = "$rs_attrs->{alias}.$order_by" |
470 | unless $order_by =~ /^$rs_attrs->{alias}\./; |
471 | |
472 | my $is_u; |
473 | my $ucs = { $root_rsrc->unique_constraints }; |
474 | for (values %$ucs ) { |
475 | if (@$_ == 1 && "$rs_attrs->{alias}.$_->[0]" eq $order_by) { |
476 | $is_u++; |
477 | last; |
478 | } |
479 | } |
480 | croak "Generic Subquery Limit order criteria column '$order_by' must be unique (no unique constraint found)" |
481 | unless $is_u; |
482 | |
483 | my ($in_sel, $out_sel, $alias_map, $extra_order_sel) |
484 | = $self->_subqueried_limit_attrs ($rs_attrs); |
485 | |
486 | my $cmp_op = $direction eq 'desc' ? '>' : '<'; |
487 | my $count_tbl_alias = 'rownum__emulation'; |
488 | |
b13d2248 |
489 | my $order_sql = $self->_order_by (delete $rs_attrs->{order_by}); |
490 | my $group_having_sql = $self->_parse_rs_attrs($rs_attrs); |
75f025cf |
491 | |
492 | # add the order supplement (if any) as this is what will be used for the outer WHERE |
493 | $in_sel .= ", $_" for keys %{$extra_order_sel||{}}; |
494 | |
495 | $sql = sprintf (<<EOS, |
496 | SELECT $out_sel |
497 | FROM ( |
b13d2248 |
498 | SELECT $in_sel ${sql}${group_having_sql} |
75f025cf |
499 | ) %s |
500 | WHERE ( SELECT COUNT(*) FROM %s %s WHERE %s $cmp_op %s ) %s |
b13d2248 |
501 | $order_sql |
75f025cf |
502 | EOS |
503 | ( map { $self->_quote ($_) } ( |
504 | $rs_attrs->{alias}, |
505 | $root_tbl_name, |
506 | $count_tbl_alias, |
507 | "$count_tbl_alias.$unq_sort_col", |
508 | $order_by, |
509 | )), |
510 | $offset |
511 | ? sprintf ('BETWEEN %u AND %u', $offset, $offset + $rows - 1) |
512 | : sprintf ('< %u', $rows ) |
513 | , |
514 | ); |
515 | |
516 | $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger |
b1e1d073 |
517 | return $sql; |
15827712 |
518 | } |
a54bd479 |
519 | |
6f4ddea1 |
520 | |
521 | # While we're at it, this should make LIMIT queries more efficient, |
522 | # without digging into things too deeply |
6f4ddea1 |
523 | sub _find_syntax { |
524 | my ($self, $syntax) = @_; |
ac788c46 |
525 | return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax); |
6f4ddea1 |
526 | } |
527 | |
998373c2 |
528 | # Quotes table names, handles "limit" dialects (e.g. where rownum between x and |
a6b68a60 |
529 | # y) |
6f4ddea1 |
530 | sub select { |
a6b68a60 |
531 | my ($self, $table, $fields, $where, $rs_attrs, @rest) = @_; |
1cbd3034 |
532 | |
c2b7c5dc |
533 | if (not ref($table) or ref($table) eq 'SCALAR') { |
6f4ddea1 |
534 | $table = $self->_quote($table); |
535 | } |
c2b7c5dc |
536 | |
6f4ddea1 |
537 | @rest = (-1) unless defined $rest[0]; |
e8fcf76f |
538 | croak "LIMIT 0 Does Not Compute" if $rest[0] == 0; |
6f4ddea1 |
539 | # and anyway, SQL::Abstract::Limit will cause a barf if we don't first |
a6b68a60 |
540 | |
49afd714 |
541 | my ($sql, @bind) = $self->SUPER::select( |
a6b68a60 |
542 | $table, $self->_recurse_fields($fields), $where, $rs_attrs, @rest |
6f4ddea1 |
543 | ); |
49afd714 |
544 | push @{$self->{where_bind}}, @bind; |
583a0c65 |
545 | |
546 | # this *must* be called, otherwise extra binds will remain in the sql-maker |
49afd714 |
547 | my @all_bind = $self->_assemble_binds; |
583a0c65 |
548 | |
49afd714 |
549 | return wantarray ? ($sql, @all_bind) : $sql; |
583a0c65 |
550 | } |
551 | |
552 | sub _assemble_binds { |
553 | my $self = shift; |
554 | return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/); |
6f4ddea1 |
555 | } |
556 | |
998373c2 |
557 | # Quotes table names, and handles default inserts |
6f4ddea1 |
558 | sub insert { |
559 | my $self = shift; |
560 | my $table = shift; |
c2b7c5dc |
561 | $table = $self->_quote($table); |
7a72e5a5 |
562 | |
563 | # SQLA will emit INSERT INTO $table ( ) VALUES ( ) |
564 | # which is sadly understood only by MySQL. Change default behavior here, |
565 | # until SQLA2 comes with proper dialect support |
566 | if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) { |
28d28903 |
567 | my $sql = "INSERT INTO ${table} DEFAULT VALUES"; |
568 | |
ef8d02eb |
569 | if (my $ret = ($_[1]||{})->{returning} ) { |
570 | $sql .= $self->_insert_returning ($ret); |
28d28903 |
571 | } |
572 | |
573 | return $sql; |
7a72e5a5 |
574 | } |
575 | |
6f4ddea1 |
576 | $self->SUPER::insert($table, @_); |
577 | } |
578 | |
998373c2 |
579 | # Just quotes table names. |
6f4ddea1 |
580 | sub update { |
581 | my $self = shift; |
582 | my $table = shift; |
c2b7c5dc |
583 | $table = $self->_quote($table); |
6f4ddea1 |
584 | $self->SUPER::update($table, @_); |
585 | } |
586 | |
998373c2 |
587 | # Just quotes table names. |
6f4ddea1 |
588 | sub delete { |
589 | my $self = shift; |
590 | my $table = shift; |
c2b7c5dc |
591 | $table = $self->_quote($table); |
6f4ddea1 |
592 | $self->SUPER::delete($table, @_); |
593 | } |
594 | |
595 | sub _emulate_limit { |
596 | my $self = shift; |
a6b68a60 |
597 | # my ( $syntax, $sql, $order, $rows, $offset ) = @_; |
598 | |
6f4ddea1 |
599 | if ($_[3] == -1) { |
a6b68a60 |
600 | return $_[1] . $self->_parse_rs_attrs($_[2]); |
6f4ddea1 |
601 | } else { |
602 | return $self->SUPER::_emulate_limit(@_); |
603 | } |
604 | } |
605 | |
606 | sub _recurse_fields { |
81446c4f |
607 | my ($self, $fields) = @_; |
6f4ddea1 |
608 | my $ref = ref $fields; |
609 | return $self->_quote($fields) unless $ref; |
610 | return $$fields if $ref eq 'SCALAR'; |
611 | |
612 | if ($ref eq 'ARRAY') { |
81446c4f |
613 | return join(', ', map { $self->_recurse_fields($_) } @$fields); |
83e09b5b |
614 | } |
615 | elsif ($ref eq 'HASH') { |
81446c4f |
616 | my %hash = %$fields; # shallow copy |
83e09b5b |
617 | |
50136dd9 |
618 | my $as = delete $hash{-as}; # if supplied |
619 | |
81446c4f |
620 | my ($func, $args, @toomany) = %hash; |
621 | |
622 | # there should be only one pair |
623 | if (@toomany) { |
624 | croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ); |
625 | } |
50136dd9 |
626 | |
627 | if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) { |
628 | croak ( |
629 | 'The select => { distinct => ... } syntax is not supported for multiple columns.' |
630 | .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }' |
631 | .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }' |
83e09b5b |
632 | ); |
6f4ddea1 |
633 | } |
83e09b5b |
634 | |
50136dd9 |
635 | my $select = sprintf ('%s( %s )%s', |
636 | $self->_sqlcase($func), |
637 | $self->_recurse_fields($args), |
638 | $as |
0491b597 |
639 | ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) ) |
50136dd9 |
640 | : '' |
641 | ); |
642 | |
83e09b5b |
643 | return $select; |
6f4ddea1 |
644 | } |
645 | # Is the second check absolutely necessary? |
646 | elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) { |
db56cf3d |
647 | return $self->_fold_sqlbind( $fields ); |
6f4ddea1 |
648 | } |
649 | else { |
e8fcf76f |
650 | croak($ref . qq{ unexpected in _recurse_fields()}) |
6f4ddea1 |
651 | } |
652 | } |
653 | |
a6b68a60 |
654 | my $for_syntax = { |
655 | update => 'FOR UPDATE', |
656 | shared => 'FOR SHARE', |
657 | }; |
658 | |
659 | # this used to be a part of _order_by but is broken out for clarity. |
660 | # What we have been doing forever is hijacking the $order arg of |
661 | # SQLA::select to pass in arbitrary pieces of data (first the group_by, |
662 | # then pretty much the entire resultset attr-hash, as more and more |
663 | # things in the SQLA space need to have mopre info about the $rs they |
664 | # create SQL for. The alternative would be to keep expanding the |
665 | # signature of _select with more and more positional parameters, which |
666 | # is just gross. All hail SQLA2! |
667 | sub _parse_rs_attrs { |
1cbd3034 |
668 | my ($self, $arg) = @_; |
15827712 |
669 | |
a6b68a60 |
670 | my $sql = ''; |
1cbd3034 |
671 | |
b03f30a3 |
672 | if (my $g = $self->_recurse_fields($arg->{group_by}) ) { |
a6b68a60 |
673 | $sql .= $self->_sqlcase(' group by ') . $g; |
674 | } |
1cbd3034 |
675 | |
a6b68a60 |
676 | if (defined $arg->{having}) { |
677 | my ($frag, @bind) = $self->_recurse_where($arg->{having}); |
678 | push(@{$self->{having_bind}}, @bind); |
679 | $sql .= $self->_sqlcase(' having ') . $frag; |
680 | } |
15827712 |
681 | |
a6b68a60 |
682 | if (defined $arg->{order_by}) { |
683 | $sql .= $self->_order_by ($arg->{order_by}); |
684 | } |
15827712 |
685 | |
a6b68a60 |
686 | if (my $for = $arg->{for}) { |
687 | $sql .= " $for_syntax->{$for}" if $for_syntax->{$for}; |
688 | } |
689 | |
690 | return $sql; |
691 | } |
692 | |
693 | sub _order_by { |
694 | my ($self, $arg) = @_; |
15827712 |
695 | |
a6b68a60 |
696 | # check that we are not called in legacy mode (order_by as 4th argument) |
697 | if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) { |
698 | return $self->_parse_rs_attrs ($arg); |
fde3719a |
699 | } |
1cbd3034 |
700 | else { |
701 | my ($sql, @bind) = $self->SUPER::_order_by ($arg); |
a6b68a60 |
702 | push @{$self->{order_bind}}, @bind; |
1cbd3034 |
703 | return $sql; |
fd4cb60a |
704 | } |
6f4ddea1 |
705 | } |
706 | |
1cbd3034 |
707 | sub _order_directions { |
fd4cb60a |
708 | my ($self, $order) = @_; |
15827712 |
709 | |
1cbd3034 |
710 | # strip bind values - none of the current _order_directions users support them |
711 | return $self->SUPER::_order_directions( [ map |
712 | { ref $_ ? $_->[0] : $_ } |
713 | $self->_order_by_chunks ($order) |
714 | ]); |
fd4cb60a |
715 | } |
716 | |
6f4ddea1 |
717 | sub _table { |
718 | my ($self, $from) = @_; |
719 | if (ref $from eq 'ARRAY') { |
720 | return $self->_recurse_from(@$from); |
721 | } elsif (ref $from eq 'HASH') { |
722 | return $self->_make_as($from); |
723 | } else { |
724 | return $from; # would love to quote here but _table ends up getting called |
725 | # twice during an ->select without a limit clause due to |
726 | # the way S::A::Limit->select works. should maybe consider |
727 | # bypassing this and doing S::A::select($self, ...) in |
728 | # our select method above. meantime, quoting shims have |
729 | # been added to select/insert/update/delete here |
730 | } |
731 | } |
732 | |
b8391c87 |
733 | sub _generate_join_clause { |
734 | my ($self, $join_type) = @_; |
735 | |
736 | return sprintf ('%s JOIN ', |
737 | $join_type ? ' ' . uc($join_type) : '' |
738 | ); |
739 | } |
740 | |
6f4ddea1 |
741 | sub _recurse_from { |
742 | my ($self, $from, @join) = @_; |
743 | my @sqlf; |
744 | push(@sqlf, $self->_make_as($from)); |
745 | foreach my $j (@join) { |
746 | my ($to, $on) = @$j; |
747 | |
aa82ce29 |
748 | |
6f4ddea1 |
749 | # check whether a join type exists |
6f4ddea1 |
750 | my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to; |
aa82ce29 |
751 | my $join_type; |
752 | if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) { |
753 | $join_type = $to_jt->{-join_type}; |
754 | $join_type =~ s/^\s+ | \s+$//xg; |
6f4ddea1 |
755 | } |
aa82ce29 |
756 | |
de5f71ef |
757 | $join_type = $self->{_default_jointype} if not defined $join_type; |
aa82ce29 |
758 | |
b8391c87 |
759 | push @sqlf, $self->_generate_join_clause( $join_type ); |
6f4ddea1 |
760 | |
761 | if (ref $to eq 'ARRAY') { |
762 | push(@sqlf, '(', $self->_recurse_from(@$to), ')'); |
763 | } else { |
764 | push(@sqlf, $self->_make_as($to)); |
765 | } |
766 | push(@sqlf, ' ON ', $self->_join_condition($on)); |
767 | } |
768 | return join('', @sqlf); |
769 | } |
770 | |
db56cf3d |
771 | sub _fold_sqlbind { |
772 | my ($self, $sqlbind) = @_; |
69989ea9 |
773 | |
774 | my @sqlbind = @$$sqlbind; # copy |
775 | my $sql = shift @sqlbind; |
776 | push @{$self->{from_bind}}, @sqlbind; |
777 | |
db56cf3d |
778 | return $sql; |
6f4ddea1 |
779 | } |
780 | |
781 | sub _make_as { |
782 | my ($self, $from) = @_; |
db56cf3d |
783 | return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ |
784 | : ref $_ eq 'REF' ? $self->_fold_sqlbind($_) |
785 | : $self->_quote($_)) |
6f4ddea1 |
786 | } reverse each %{$self->_skip_options($from)}); |
787 | } |
788 | |
789 | sub _skip_options { |
790 | my ($self, $hash) = @_; |
791 | my $clean_hash = {}; |
792 | $clean_hash->{$_} = $hash->{$_} |
793 | for grep {!/^-/} keys %$hash; |
794 | return $clean_hash; |
795 | } |
796 | |
797 | sub _join_condition { |
798 | my ($self, $cond) = @_; |
799 | if (ref $cond eq 'HASH') { |
800 | my %j; |
801 | for (keys %$cond) { |
802 | my $v = $cond->{$_}; |
803 | if (ref $v) { |
e8fcf76f |
804 | croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'}) |
6f4ddea1 |
805 | if ref($v) ne 'SCALAR'; |
806 | $j{$_} = $v; |
807 | } |
808 | else { |
809 | my $x = '= '.$self->_quote($v); $j{$_} = \$x; |
810 | } |
811 | }; |
812 | return scalar($self->_recurse_where(\%j)); |
813 | } elsif (ref $cond eq 'ARRAY') { |
814 | return join(' OR ', map { $self->_join_condition($_) } @$cond); |
815 | } else { |
816 | die "Can't handle this yet!"; |
817 | } |
818 | } |
819 | |
6f4ddea1 |
820 | sub limit_dialect { |
821 | my $self = shift; |
b2c7cf74 |
822 | if (@_) { |
823 | $self->{limit_dialect} = shift; |
824 | undef $self->{_cached_syntax}; |
825 | } |
6f4ddea1 |
826 | return $self->{limit_dialect}; |
827 | } |
828 | |
998373c2 |
829 | # Set to an array-ref to specify separate left and right quotes for table names. |
830 | # A single scalar is equivalen to [ $char, $char ] |
6f4ddea1 |
831 | sub quote_char { |
832 | my $self = shift; |
833 | $self->{quote_char} = shift if @_; |
834 | return $self->{quote_char}; |
835 | } |
836 | |
998373c2 |
837 | # Character separating quoted table names. |
6f4ddea1 |
838 | sub name_sep { |
839 | my $self = shift; |
840 | $self->{name_sep} = shift if @_; |
841 | return $self->{name_sep}; |
842 | } |
843 | |
844 | 1; |