slightly nicer newline handling for stuff in parens
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
index 10b0455..5c17951 100644 (file)
@@ -4,6 +4,7 @@ use strict;
 use warnings;
 use Carp;
 
+use List::Util;
 
 use base 'Class::Accessor::Grouped';
 
@@ -27,6 +28,7 @@ my @expression_terminator_sql_keywords = (
   'UPDATE',
   'INSERT \s+ INTO',
   'DELETE \s+ FROM',
+  'FROM',
   'SET',
   '(?:
     (?:
@@ -87,15 +89,16 @@ my %indents = (
    update        => 0,
    'insert into' => 0,
    'delete from' => 0,
-   where         => 1,
+   from          => 1,
+   where         => 0,
    join          => 1,
    'left join'   => 1,
    on            => 2,
-   'group by'    => 1,
-   'order by'    => 1,
+   'group by'    => 0,
+   'order by'    => 0,
    set           => 1,
    into          => 1,
-   values        => 2,
+   values        => 1,
 );
 
 my %profiles = (
@@ -149,6 +152,7 @@ eval {
       'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
 
       set           => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
+      from          => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
 
       where         => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
       values        => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
@@ -287,11 +291,11 @@ sub whitespace {
 
 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
 
-sub _is_select {
-   my $tree = shift;
+sub _is_key {
+   my ($self, $tree) = @_;
    $tree = $tree->[0] while ref $tree;
 
-   defined $tree && lc $tree eq 'select';
+   defined $tree && defined $self->indentmap->{lc $tree};
 }
 
 sub unparse {
@@ -316,7 +320,7 @@ sub unparse {
     return '(' .
       join(' ',
         map $self->unparse($_, $depth + 2), @{$cdr}) .
-    (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
+    ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
   }
   elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
     return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
@@ -343,3 +347,14 @@ sub format { my $self = shift; $self->unparse($self->parse(@_)) }
  #   FROM foo
  #   WHERE foo.a > 2
 
+=head1 METHODS
+
+=head2 new
+
+ my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
+
+=head2 format
+
+ $sqlat->format('SELECT * FROM bar')
+
+Returns a formatting string based on wthe string passed in