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