Updates to MX::Declare required changes
[dbsrgits/SQL-Abstract-2.0-ish.git] / lib / SQL / Abstract / AST / v1.pm
index 3914388..b43d479 100644 (file)
@@ -8,22 +8,22 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
   use Moose::Util::TypeConstraints;
   use MooseX::Types::Moose qw/ArrayRef Str Int Ref HashRef/;
   use MooseX::AttributeHelpers;
-  use SQL::Abstract::Types qw/AST ArrayAST HashAST/;
+  use SQL::Abstract::Types qw/AST/;
   use Devel::PartialDump qw/dump/;
 
-  clean;
-
   # set things that are valid in where clauses
   override _build_expr_dispatch_table {
     return { 
       %{super()},
       in => $self->can('_in'),
       not_in => $self->can('_in'),
+      between => $self->can('_between'),
+      not_between => $self->can('_between'),
       and => $self->can('_recurse_where'),
       or => $self->can('_recurse_where'),
       map { +"$_" => $self->can("_$_") } qw/
         value
-        name
+        identifier
         true
         false
         expr
@@ -31,7 +31,7 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     };
   }
 
-  method _select(HashAST $ast) {
+  method _select(AST $ast) {
     # Default to requiring columns and from.
     # DB specific ones (i.e. mysql/Pg) can not require the FROM part with a bit
     # of refactoring
@@ -45,7 +45,7 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     confess "'columns' should be an array ref, not " . dump($ast->{columns})
       unless is_ArrayRef($ast->{columns});
 
-    my $cols = join ($self->list_separator, map { $self->dispatch($_) } @{ $ast->{columns}});
+    my $cols = $self->_list({-type => 'list', args => $ast->{columns} });
 
     my @output = (
       SELECT => $cols
@@ -54,47 +54,109 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     push @output, FROM => $self->dispatch($ast->{tablespec})
       if exists $ast->{tablespec};
 
-    for (qw//) {
+    if (exists $ast->{where}) {
+      my $sub_ast = $ast->{where};
+
+      confess "$_ option is not an AST: " . dump($sub_ast)
+        unless is_AST($sub_ast);
+
+      push @output, "WHERE", $self->_expr($sub_ast);
+    }
+
+    for (qw/group_by having order_by/) {
       if (exists $ast->{$_}) {
         my $sub_ast = $ast->{$_};
-        $sub_ast->{-type} = "$_" if is_HashRef($sub_ast);
-        confess "$_ option is not an AST"
-          unless is_AST($sub_ast);
 
-        push @output, $self->dispatch($sub_ast);
+        confess "$_ option is not an AST or an ArrayRef: " . dump($sub_ast)
+          unless is_AST($sub_ast) || is_ArrayRef($sub_ast);;
+
+        my $meth = "__$_";
+        push @output, $self->$meth($sub_ast);
       }
     }
 
     return join(' ', @output);
   }
 
-  method _where(ArrayAST $ast) {
-    my (undef, @clauses) = @$ast;
-  
-    return 'WHERE ' . $self->_recurse_where(\@clauses);
+  method _update(AST $ast) {
+
+    for (qw/columns values tablespec/) {
+      confess "'$_' is required in update AST with " . dump ($ast)
+        unless exists $ast->{$_};
+    }
+
+    my $table = $ast->{tablespec};
+    confess 'update: tablespec must be an ident or an alias in ' . dump($ast)
+      unless $table->{-type} =~ /^identifier|alias$/;
+
+    my @output = (
+        'UPDATE',
+        $self->dispatch($table),
+        'SET'
+    );
+
+    confess 'update: Number of values does not match columns: ' . dump($ast)
+      if @{$ast->{columns}} != @{$ast->{values}};
+    
+    my $list = {
+      -type => 'list',
+      args => [ map {
+        { -type => 'expr',
+          op => '==', # This should really be '=' but hmmmmmmmm
+          args => [
+            $ast->{columns}[$_],
+            $ast->{values}[$_]
+          ]
+        }
+      } 0..$#{$ast->{columns}} ]
+    };
+
+    push @output, $self->dispatch($list);
+      
+    return join(' ', @output);
+    
   }
 
-  method _order_by(AST $ast) {
-    my @clauses = @{$ast->{order_by}};
+  method _join(HashRef $ast) {
+
+    # TODO: Validate join type
+    my $type = $ast->{join_type} || "";
   
-    my @output;
-   
-    for (@clauses) {
-      if (is_ArrayRef($_) && $_->[0] =~ /^-(asc|desc)$/) {
-        my $o = $1;
-        push @output, $self->dispatch($_->[1]) . " " . uc($o);
-        next;
-      }
-      push @output, $self->dispatch($_);
-    }
+    my @output = $self->dispatch($ast->{lhs});
+
+    push @output, uc $type if $type;
+    push @output, "JOIN", $self->dispatch($ast->{rhs});
+
+    push @output, 
+        exists $ast->{on}
+      ? ('ON', '(' . $self->_expr( $ast->{on} ) . ')' )
+      : ('USING', '(' .$self->dispatch($ast->{using} 
+                        || croak "No 'on' or 'uinsg' clause passed to join cluase: " .
+                                 dump($ast) 
+                        ) .
+                  ')' );
 
-    return "ORDER BY " . join(", ", @output);
+    return join(" ", @output);
+      
   }
 
-  method _name(HashAST $ast) {
-    my @names = @{$ast->{args}};
+  method _ordering(AST $ast) {
+    my $output = $self->_expr($ast->{expr});
+
+    $output .= " " . uc $1
+      if $ast->{direction} && 
+         ( $ast->{direction} =~ /^(asc|desc)$/i 
+           || confess "Unknown ordering direction " . dump($ast)
+         );
 
-    my $sep = $self->name_separator;
+    return $output;
+  }
+
+  method _identifier(AST $ast) {
+    my @names = @{$ast->{elements}};
+
+    my $sep = $self->ident_separator;
     my $quote = $self->is_quoting 
               ? $self->quote_chars
               : [ '' ];
@@ -107,30 +169,28 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     my $post;
     $post = pop @names if $names[-1] eq '*';
 
-    my $ret = 
-      $quote->[0] . 
-      join( $join, @names ) . 
-      $quote->[-1];
+    my $ret;
+    $ret = $quote->[0] . 
+           join( $join, @names ) . 
+           $quote->[-1]
+      if @names;
 
-    $ret .= $sep . $post if defined $post;
-    return $ret;
-  }
+    $ret = $ret 
+         ? $ret . $sep . $post
+         : $post
+      if defined $post;
 
-  method _join(HashRef $ast) {
-  
-    my $output = 'JOIN ' . $self->dispatch($ast->{tablespec});
-
-    $output .= exists $ast->{on}
-             ? ' ON (' . $self->_expr( $ast->{on} )
-             : ' USING (' .$self->dispatch($ast->{using} || croak "No 'on' or 'join' clause passed to -join");
 
-    $output .= ")";
-    return $output;
-      
+    return $ret;
   }
 
+
   method _list(AST $ast) {
-    my @items = @{$ast->{args}};
+    return "" unless $ast->{args};
+
+    my @items = is_ArrayRef($ast->{args})
+              ? @{$ast->{args}}
+              : $ast->{args};
 
     return join(
       $self->list_separator,
@@ -145,14 +205,28 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
 
   }
 
-  method _value(HashAST $ast) {
+  method _value(AST $ast) {
 
     $self->add_bind($ast->{value});
     return "?";
   }
 
+  # Not dispatchable to.
+  method __having($args) {
+    return "HAVING " . $self->_list({-type => 'list', args => $args});
+  }
+
+  method __group_by($args) {
+    return "GROUP BY " . $self->_list({-type => 'list', args => $args});
+  }
+
+  method __order_by($args) {
+    return "ORDER BY " . $self->_list({-type => 'list', args => $args});
+  }
+
+
   # Perhaps badly named. handles 'and' and 'or' clauses
-  method _recurse_where(HashAST $ast) {
+  method _recurse_where(AST $ast) {
 
     my $op = $ast->{op};
 
@@ -163,12 +237,14 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
 
     my @output;
     foreach ( @{$ast->{args}} ) {
-      croak "invalid component in where clause: $_" unless is_HashAST($_);
+      croak "invalid component in where clause: $_" unless is_AST($_);
 
       if ($_->{-type} eq 'expr' && $_->{op} =~ /^(and|or)$/) {
         my $sub_prio = $SQL::Abstract::PRIO{$1}; 
 
-        if ($sub_prio <= $prio) {
+        if ($sub_prio == $prio) {
+          # When the element below has same priority, i.e. 'or' as a child of
+          # 'or', dont produce extra brackets
           push @output, $self->_recurse_where($_);
         } else {
           push @output, '(' . $self->_recurse_where($_) . ')';
@@ -181,7 +257,7 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     return join(" $OP ", @output);
   }
 
-  method _expr(HashAST $ast) {
+  method _expr(AST $ast) {
     my $op = $ast->{-type};
 
     $op = $ast->{op} if $op eq 'expr';
@@ -194,21 +270,41 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
     croak "'$op' is not a valid AST type in an expression with " . dump($ast)
       if $ast->{-type} ne 'expr';
 
-    croak "'$op' is not a valid operator in an expression with " . dump($ast);
+    # This is an attempt to do some form of validation on function names. This
+    # might end up being a bad thing.
+    croak "'$op' is not a valid operator in an expression with " . dump($ast)
+      if $op =~ /\W/;
+
+    return $self->_generic_function_op($ast);
    
   }
 
-  method _binop(HashAST $ast) {
+  method _binop(AST $ast) {
     my ($lhs, $rhs) = @{$ast->{args}};
     my $op = $ast->{op};
 
+    # IS NOT? NULL
+    if ($rhs->{-type} eq 'value' && !defined $rhs->{value} &&
+        ($op eq '==' || $op eq '!='))
+    {
+      return $self->_expr($lhs) .
+             ($op eq '==' ? " IS " : " IS NOT ") .
+             "NULL";
+    }
+
     join (' ', $self->_expr($lhs), 
                $self->binop_mapping($op) || croak("Unknown binary operator $op"),
                $self->_expr($rhs)
     );
   }
 
-  method _in(HashAST $ast) {
+  method _generic_function_op(AST $ast) {
+    my $op = $ast->{op};
+
+    return "$op(" . $self->_list($ast) . ")";
+  }
+
+  method _in(AST $ast) {
   
     my ($field,@values) = @{$ast->{args}};
 
@@ -223,7 +319,21 @@ class SQL::Abstract::AST::v1 extends SQL::Abstract {
            ")";
   }
 
-  method _generic_func(ArrayRef $ast) {
+  method _between(AST $ast) {
+  
+    my ($field,@values) = @{$ast->{args}};
+
+    my $not = ($ast->{op} =~ /^not_/) ? " NOT" : "";
+    croak "between requires 3 arguments: " . dump($ast)
+      unless @values == 2;
+
+    # The brackets are to work round an issue with SQL::A::Test
+    return "(" .
+           $self->_expr($field) .
+           $not . 
+           " BETWEEN " .
+           join(" AND ", map { $self->dispatch($_) } @values ) .
+           ")";
   }
 
   # 'constants' that are portable across DBs