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