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