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