The Top limit emulation bundled with SQLA::Limit assumes that the limited resultset...
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLAHacks.pm
index d2f96bf..f9a5675 100644 (file)
@@ -1,8 +1,11 @@
 package # Hide from PAUSE
-  DBIx::Class::SQLAHacks; # Would merge upstream, but nate doesn't reply :(
+  DBIx::Class::SQLAHacks;
 
 use base qw/SQL::Abstract::Limit/;
+use strict;
+use warnings;
 use Carp::Clan qw/^DBIx::Class/;
+use Scalar::Util();
 
 sub new {
   my $self = shift->SUPER::new(@_);
@@ -17,7 +20,6 @@ sub new {
 }
 
 
-
 # Some databases (sqlite) do not handle multiple parenthesis
 # around in/between arguments. A tentative x IN ( ( 1, 2 ,3) )
 # is interpreted as x IN 1 or something similar.
@@ -66,16 +68,12 @@ sub _where_field_BETWEEN {
   return $self->SUPER::_where_field_BETWEEN ($lhs, $op, $rhs);
 }
 
-
-
-# DB2 is the only remaining DB using this. Even though we are not sure if
-# RowNumberOver is still needed here (should be part of SQLA) leave the 
-# code in place
+# Slow but ANSI standard Limit/Offset support. DB2 uses this
 sub _RowNumberOver {
   my ($self, $sql, $order, $rows, $offset ) = @_;
 
   $offset += 1;
-  my $last = $rows + $offset;
+  my $last = $rows + $offset - 1;
   my ( $order_by ) = $self->_order_by( $order );
 
   $sql = <<"SQL";
@@ -93,22 +91,45 @@ SQL
   return $sql;
 }
 
+# Crappy Top based Limit/Offset support. MSSQL uses this currently,
+# but may have to switch to RowNumberOver one day
+sub _Top {
+  my ( $self, $sql, $order, $rows, $offset ) = @_;
+
+  croak '$order supplied to SQLAHacks limit emulators must be a hash'
+    if (ref $order ne 'HASH');
+
+  my $last = $rows + $offset;
+
+  my $req_order = $self->_order_by ($order->{order_by});
+  my $limit_order = $req_order ? $order->{order_by} : $order->{_virtual_order_by};
+
+  my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
+
+  $sql =~ s/^\s*(SELECT|select)//;
+
+  $sql = <<"SQL";
+  SELECT * FROM
+  (
+    SELECT TOP $rows * FROM
+    (
+        SELECT TOP $last $sql $order_by_inner
+    ) AS foo
+    $order_by_outer
+  ) AS bar
+  $req_order
+
+SQL
+    return $sql;
+}
+
+
 
 # While we're at it, this should make LIMIT queries more efficient,
 #  without digging into things too deeply
-use Scalar::Util 'blessed';
 sub _find_syntax {
   my ($self, $syntax) = @_;
-  
-  # DB2 is the only remaining DB using this. Even though we are not sure if
-  # RowNumberOver is still needed here (should be part of SQLA) leave the 
-  # code in place
-  my $dbhname = blessed($syntax) ? $syntax->{Driver}{Name} : $syntax;
-  if(ref($self) && $dbhname && $dbhname eq 'DB2') {
-    return 'RowNumberOver';
-  }
-  
-  $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
+  return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
 }
 
 sub select {
@@ -125,7 +146,7 @@ sub select {
   local $self->{rownum_hack_count} = 1
     if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
   @rest = (-1) unless defined $rest[0];
-  die "LIMIT 0 Does Not Compute" if $rest[0] == 0;
+  croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
     # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
   my ($sql, @where_bind) = $self->SUPER::select(
     $table, $self->_recurse_fields($fields), $where, $order, @rest
@@ -190,20 +211,20 @@ sub _recurse_fields {
       if ($func eq 'distinct') {
         my $_fields = $fields->{$func};
         if (ref $_fields eq 'ARRAY' && @{$_fields} > 1) {
-          die "Unsupported syntax, please use " . 
-              "{ group_by => [ qw/" . (join ' ', @$_fields) . "/ ] }" .
-              " or " .
-              "{ select => [ qw/" . (join ' ', @$_fields) . "/ ], distinct => 1 }";
+          croak (
+            'The select => { distinct => ... } syntax is not supported for multiple columns.'
+           .' Instead please use { group_by => [ qw/' . (join ' ', @$_fields) . '/ ] }'
+           .' or { select => [ qw/' . (join ' ', @$_fields) . '/ ], distinct => 1 }'
+          );
         }
         else {
           $_fields = @{$_fields}[0] if ref $_fields eq 'ARRAY';
-          carp "This syntax will be deprecated in 09, please use " . 
-               "{ group_by => '${_fields}' }" . 
-               " or " .
-               "{ select => '${_fields}', distinct => 1 }";
+          carp (
+            'The select => { distinct => ... } syntax will be deprecated in DBIC version 0.09,'
+           ." please use { group_by => '${_fields}' } or { select => '${_fields}', distinct => 1 }"
+          );
         }
       }
-      
       return $self->_sqlcase($func)
         .'( '.$self->_recurse_fields($fields->{$func}).' )';
     }
@@ -213,7 +234,7 @@ sub _recurse_fields {
     return $self->_fold_sqlbind( $fields );
   }
   else {
-    Carp::croak($ref . qq{ unexpected in _recurse_fields()})
+    croak($ref . qq{ unexpected in _recurse_fields()})
   }
 }
 
@@ -222,32 +243,38 @@ sub _order_by {
   my $ret = '';
   my @extra;
   if (ref $_[0] eq 'HASH') {
+
     if (defined $_[0]->{group_by}) {
       $ret = $self->_sqlcase(' group by ')
         .$self->_recurse_fields($_[0]->{group_by}, { no_rownum_hack => 1 });
     }
+
     if (defined $_[0]->{having}) {
       my $frag;
       ($frag, @extra) = $self->_recurse_where($_[0]->{having});
       push(@{$self->{having_bind}}, @extra);
       $ret .= $self->_sqlcase(' having ').$frag;
     }
+
     if (defined $_[0]->{order_by}) {
       $ret .= $self->_order_by($_[0]->{order_by});
     }
+
     if (grep { $_ =~ /^-(desc|asc)/i } keys %{$_[0]}) {
       return $self->SUPER::_order_by($_[0]);
     }
+
   } elsif (ref $_[0] eq 'SCALAR') {
     $ret = $self->_sqlcase(' order by ').${ $_[0] };
   } elsif (ref $_[0] eq 'ARRAY' && @{$_[0]}) {
-    my @order = @{+shift};
-    $ret = $self->_sqlcase(' order by ')
-          .join(', ', map {
-                        my $r = $self->_order_by($_, @_);
-                        $r =~ s/^ ?ORDER BY //i;
-                        $r;
-                      } @order);
+    my @order = map {
+      my $r = $self->_order_by($_, @_);
+      $r =~ s/^ ?ORDER BY //i;
+      $r || ();
+    } @{+shift};
+
+    $ret = $self->_sqlcase(' order by ') . join(', ', @order) if @order;
+
   } else {
     $ret = $self->SUPER::_order_by(@_);
   }
@@ -256,8 +283,52 @@ sub _order_by {
 
 sub _order_directions {
   my ($self, $order) = @_;
-  $order = $order->{order_by} if ref $order eq 'HASH';
-  return $self->SUPER::_order_directions($order);
+  return $self->SUPER::_order_directions( $self->_resolve_order($order) );
+}
+
+sub _resolve_order {
+  my ($self, $order) = @_;
+
+  if (ref $order eq 'HASH') {
+    $order = [$self->_resolve_order_hash($order)];
+  }
+  elsif (ref $order eq 'ARRAY') {
+    $order = [map {
+      if (ref ($_) eq 'SCALAR') {
+        $$_
+      }
+      elsif (ref ($_) eq 'HASH') {
+        $self->_resolve_order_hash($_)
+      }
+      else {
+        $_
+      }
+    }  @$order];
+  }
+
+  return $order;
+}
+
+sub _resolve_order_hash {
+  my ($self, $order) = @_;
+  my @new_order;
+  foreach my $key (keys %{ $order }) {
+    if ($key =~ /^-(desc|asc)/i ) {
+      my $direction = $1;
+      my $type = ref $order->{ $key };
+      if ($type eq 'ARRAY') {
+        push @new_order, map( "$_ $direction", @{ $order->{ $key } } );
+      } elsif (!$type) {
+        push @new_order, "$order->{$key} $direction";
+      } else {
+        croak "hash order_by can only contain Scalar or Array, not $type";
+      }
+    } else {
+      croak "$key is not a valid direction, use -asc or -desc";
+    }
+  }
+
+  return @new_order;
 }
 
 sub _table {
@@ -305,8 +376,11 @@ sub _recurse_from {
 
 sub _fold_sqlbind {
   my ($self, $sqlbind) = @_;
-  my $sql = shift @$$sqlbind;
-  push @{$self->{from_bind}}, @$$sqlbind;
+
+  my @sqlbind = @$$sqlbind; # copy
+  my $sql = shift @sqlbind;
+  push @{$self->{from_bind}}, @sqlbind;
+
   return $sql;
 }
 
@@ -333,8 +407,7 @@ sub _join_condition {
     for (keys %$cond) {
       my $v = $cond->{$_};
       if (ref $v) {
-        # XXX no throw_exception() in this package and croak() fails with strange results
-        Carp::croak(ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
+        croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
             if ref($v) ne 'SCALAR';
         $j{$_} = $v;
       }
@@ -392,7 +465,9 @@ __END__
 
 =head1 NAME
 
-DBIx::Class::SQLAHacks - Things desired to be merged into SQL::Abstract
+DBIx::Class::SQLAHacks - This module is a subclass of SQL::Abstract::Limit
+and includes a number of DBIC-specific workarounds, not yet suitable for
+inclusion into SQLA proper.
 
 =head1 METHODS