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