Deprecate -nest in favor of -paren
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract.pm
index 457f305..a569708 100644 (file)
@@ -15,7 +15,7 @@ use Scalar::Util qw/blessed/;
 # GLOBALS
 #======================================================================
 
-our $VERSION  = '1.51';
+our $VERSION  = '1.53';
 
 # This would confuse some packagers
 #$VERSION      = eval $VERSION; # numify for warning-free dev releases
@@ -63,7 +63,7 @@ sub new {
   delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
 
   # default logic for interpreting arrayrefs
-  $opt{logic} = uc $opt{logic} || 'OR';
+  $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
 
   # how to return bind vars
   # LDNOTE: changed nwiger code : why this 'delete' ??
@@ -422,7 +422,6 @@ sub _where_HASHREF {
   my ($self, $where) = @_;
   my (@sql_clauses, @all_bind);
 
-  # LDNOTE : don't really know why we need to sort keys
   for my $k (sort keys %$where) { 
     my $v = $where->{$k};
 
@@ -444,49 +443,54 @@ sub _where_HASHREF {
 sub _where_op_in_hash {
   my ($self, $op_str, $v) = @_; 
 
-  $op_str =~ /^ (AND|OR|NEST) ( \_? \d* ) $/xi
+  $op_str =~ /^ (AND|OR|PAREN|NEST) ( \_? \d* ) $/xi
     or puke "unknown operator: -$op_str";
 
   my $op = uc($1); # uppercase, remove trailing digits
   if ($2) {
-    belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
+    belch 'Use of op_N modifiers is deprecated and will be removed in SQLA v2.0. '
           . "You probably wanted ...-and => [ $op_str => COND1, $op_str => COND2 ... ]";
   }
 
+  if ($op eq 'NEST') {
+    belch 'The -nest modifier is deprecated in favor of -paren and will be removed in SQLA v2.0';
+    $op = 'PAREN';
+  }
+
   $self->_debug("OP(-$op) within hashref, recursing...");
 
   $self->_SWITCH_refkind($v, {
 
     ARRAYREF => sub {
-      return $self->_where_ARRAYREF($v, $op eq 'NEST' ? '' : $op);
+      return $self->_where_ARRAYREF($v, $op eq 'PAREN' ? '' : $op);
     },
 
     HASHREF => sub {
       if ($op eq 'OR') {
-        return $self->_where_ARRAYREF([%$v], 'OR');
+        return $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], 'OR');
       } 
-      else {                  # NEST | AND
+      else {                  # PAREN | AND
         return $self->_where_HASHREF($v);
       }
     },
 
     SCALARREF  => sub {         # literal SQL
-      $op eq 'NEST' 
-        or puke "-$op => \\\$scalar not supported, use -nest => ...";
+      $op eq 'PAREN' 
+        or puke "-$op => \\\$scalar not supported, use -paren => ...";
       return ($$v); 
     },
 
     ARRAYREFREF => sub {        # literal SQL
-      $op eq 'NEST' 
-        or puke "-$op => \\[..] not supported, use -nest => ...";
+      $op eq 'PAREN' 
+        or puke "-$op => \\[..] not supported, use -paren => ...";
       return @{${$v}};
     },
 
     SCALAR => sub { # permissively interpreted as SQL
-      $op eq 'NEST' 
-        or puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
-      belch "literal SQL should be -nest => \\'scalar' "
-          . "instead of -nest => 'scalar' ";
+      $op eq 'PAREN' 
+        or puke "-$op => 'scalar' not supported, use -paren => \\'scalar'";
+      belch "literal SQL should be -paren => \\'scalar' "
+          . "instead of -paren => 'scalar' ";
       return ($v); 
     },
 
@@ -505,9 +509,10 @@ sub _where_hashpair_ARRAYREF {
     $self->_debug("ARRAY($k) means distribute over elements");
 
     # put apart first element if it is an operator (-and, -or)
-    my $op = ($v[0] =~ /^ - (?: AND|OR ) $/ix
-      ? shift @v
-      : ''
+    my $op = (
+       (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
+         ? shift @v
+         : ''
     );
     my @distributed = map { {$k =>  $_} } @v;
 
@@ -528,9 +533,10 @@ sub _where_hashpair_ARRAYREF {
 }
 
 sub _where_hashpair_HASHREF {
-  my ($self, $k, $v) = @_;
+  my ($self, $k, $v, $logic) = @_;
+  $logic ||= 'and';
 
-  my (@all_sql, @all_bind);
+  my ($all_sql, @all_bind);
 
   for my $op (sort keys %$v) {
     my $val = $v->{$op};
@@ -571,6 +577,10 @@ sub _where_hashpair_HASHREF {
           @bind = @sub_bind;
         },
 
+        HASHREF => sub {
+          ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $op);
+        },
+
         UNDEF => sub {          # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
           my $is = ($op =~ $self->{equality_op})   ? 'is'     :
                    ($op =~ $self->{inequality_op}) ? 'is not' :
@@ -587,11 +597,10 @@ sub _where_hashpair_HASHREF {
       });
     }
 
-    push @all_sql, $sql;
+    ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
     push @all_bind, @bind;
   }
-
-  return $self->_join_sql_clauses('and', \@all_sql, \@all_bind);
+  return ($all_sql, @all_bind);
 }
 
 
@@ -602,17 +611,25 @@ sub _where_field_op_ARRAYREF {
   if(@$vals) {
     $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
 
+    # see if the first element is an -and/-or op
+    my $logic;
+    if ($vals->[0] =~ /^ - ( AND|OR ) $/ix) {
+      $logic = uc $1;
+      shift @$vals;
+    }
+
+    # distribute $op over each remaining member of @$vals, append logic if exists
+    return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
+
     # LDNOTE : had planned to change the distribution logic when 
     # $op =~ $self->{inequality_op}, because of Morgan laws : 
     # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
     # WHERE field != 22 OR  field != 33 : the user probably means 
     # WHERE field != 22 AND field != 33.
-    # To do this, replace the line below by :
+    # To do this, replace the above to roughly :
     # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
     # return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
 
-    # distribute $op over each member of @$vals
-    return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals]);
   } 
   else {
     # try to DWIM on equality operators 
@@ -825,7 +842,8 @@ sub _order_by_hash {
   my ($order) = ($key =~ /^-(desc|asc)/i)
     or puke "invalid key in _order_by hash : $key";
 
-  return $self->_quote($val) ." ". $self->_sqlcase($order);
+  $val = ref $val eq 'ARRAY' ? $val : [$val];
+  return join ', ', map { $self->_quote($_) . ' ' . $self->_sqlcase($order) } @$val;
 }
 
 
@@ -1838,7 +1856,7 @@ This data structure would create the following:
     @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
 
 
-There is also a special C<-nest>
+There is also a special C<-paren>
 operator which adds an additional set of parens, to create a subquery.
 For example, to get something like this:
 
@@ -1849,7 +1867,7 @@ You would do:
 
     my %where = (
          user => 'nwiger',
-        -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
+        -paren => [ workhrs => {'>', 20}, geo => 'ASIA' ],
     );
 
 
@@ -1860,7 +1878,7 @@ inside :
     my @where = (
          -and => [
             user => 'nwiger',
-            -nest => [
+            -paren => [
                 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
                 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
             ],
@@ -2013,7 +2031,7 @@ hash, like an EXISTS subquery :
      = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
   my %where = (
     foo   => 1234,
-    -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
+    -paren => \["EXISTS ($sub_stmt)" => @sub_bind],
   );
 
 which yields
@@ -2036,7 +2054,7 @@ like for example fulltext expressions, geospatial expressions,
 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
 
   my %where = (
-    -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
+    -paren => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
   );
 
 Finally, here is an example where a subquery is used
@@ -2047,7 +2065,7 @@ for expressing unary negation:
   $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
   my %where = (
         lname  => {like => '%son%'},
-        -nest  => \["NOT ($sub_stmt)" => @sub_bind],
+        -paren  => \["NOT ($sub_stmt)" => @sub_bind],
     );
 
 This yields
@@ -2081,19 +2099,29 @@ Some functions take an order by clause. This can either be a scalar (just a
 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
 or an array of either of the two previous forms. Examples:
 
-             Given             |    Will Generate
+               Given            |         Will Generate
     ----------------------------------------------------------
-    \'colA DESC'               | ORDER BY colA DESC
-    'colA'                     | ORDER BY colA
-    [qw/colA colB/]            | ORDER BY colA, colB
-    {-asc  => 'colA'}          | ORDER BY colA ASC
-    {-desc => 'colB'}          | ORDER BY colB DESC
-    [                          |
-      {-asc  => 'colA'},       | ORDER BY colA ASC, colB DESC
-      {-desc => 'colB'}        |
-    ]                          |
-    [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
-    ==========================================================
+                                |
+    \'colA DESC'                | ORDER BY colA DESC
+                                |
+    'colA'                      | ORDER BY colA
+                                |
+    [qw/colA colB/]             | ORDER BY colA, colB
+                                |
+    {-asc  => 'colA'}           | ORDER BY colA ASC
+                                |
+    {-desc => 'colB'}           | ORDER BY colB DESC
+                                |
+    ['colA', {-asc => 'colB'}]  | ORDER BY colA, colB ASC
+                                |
+    { -asc => [qw/colA colB] }  | ORDER BY colA ASC, colB ASC
+                                |
+    [                           |
+      { -asc => 'colA' },       | ORDER BY colA ASC, colB DESC,
+      { -desc => [qw/colB/],    |          colC ASC, colD ASC
+      { -asc => [qw/colC colD/],|
+    ]                           |
+    ===========================================================
 
 
 
@@ -2295,8 +2323,9 @@ so I have no idea who they are! But the people I do know are:
     Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
     Dan Kubb (support for "quote_char" and "name_sep")
     Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
-    Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
+    Laurent Dami (internal refactoring, multiple -paren, extensible list of special operators, literal SQL)
     Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
+    Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
 
 Thanks!
 
@@ -2315,6 +2344,8 @@ While not an official support venue, C<DBIx::Class> makes heavy use of
 C<SQL::Abstract>, and as such list members there are very familiar with
 how to create queries.
 
+=head1 LICENSE
+
 This module is free software; you may copy this under the terms of
 the GNU General Public License, or the Artistic License, copies of
 which should have accompanied your Perl kit.