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