Treat RNO as a unary op, and properly normalize it
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
1 package SQL::Abstract::Tree;
2
3 use strict;
4 use warnings;
5 no warnings 'qw';
6 use Carp;
7
8 use Hash::Merge qw//;
9
10 use base 'Class::Accessor::Grouped';
11
12 __PACKAGE__->mk_group_accessors( simple => qw(
13    newline indent_string indent_amount colormap indentmap fill_in_placeholders
14    placeholder_surround
15 ));
16
17 my $merger = Hash::Merge->new;
18
19 $merger->specify_behavior({
20    SCALAR => {
21       SCALAR => sub { $_[1] },
22       ARRAY  => sub { [ $_[0], @{$_[1]} ] },
23       HASH   => sub { $_[1] },
24    },
25    ARRAY => {
26       SCALAR => sub { $_[1] },
27       ARRAY  => sub { $_[1] },
28       HASH   => sub { $_[1] },
29    },
30    HASH => {
31       SCALAR => sub { $_[1] },
32       ARRAY  => sub { [ values %{$_[0]}, @{$_[1]} ] },
33       HASH   => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
34    },
35 }, 'SQLA::Tree Behavior' );
36
37 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
38 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
39
40 my $quote_left = qr/[\`\'\"\[]/;
41 my $quote_right = qr/[\`\'\"\]]/;
42
43 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
44
45 # These SQL keywords always signal end of the current expression (except inside
46 # of a parenthesized subexpression).
47 # Format: A list of strings that will be compiled to extended syntax ie.
48 # /.../x) regexes, without capturing parentheses. They will be automatically
49 # anchored to op boundaries (excluding quotes) to match the whole token.
50 my @expression_start_keywords = (
51   'SELECT',
52   'UPDATE',
53   'SET',
54   'INSERT \s+ INTO',
55   'DELETE \s+ FROM',
56   'FROM',
57   '(?:
58     (?:
59         (?: (?: LEFT | RIGHT | FULL ) \s+ )?
60         (?: (?: CROSS | INNER | OUTER ) \s+ )?
61     )?
62     JOIN
63   )',
64   'ON',
65   'WHERE',
66   '(?: DEFAULT \s+ )? VALUES',
67   'GROUP \s+ BY',
68   'HAVING',
69   'ORDER \s+ BY',
70   'SKIP',
71   'FETCH',
72   'FIRST',
73   'LIMIT',
74   'OFFSET',
75   'FOR',
76   'UNION',
77   'INTERSECT',
78   'EXCEPT',
79   'BEGIN \s+ WORK',
80   'COMMIT',
81   'ROLLBACK \s+ TO \s+ SAVEPOINT',
82   'ROLLBACK',
83   'SAVEPOINT',
84   'RELEASE \s+ SAVEPOINT',
85   'RETURNING',
86 );
87
88 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
89 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
90
91 # These are binary operator keywords always a single LHS and RHS
92 # * AND/OR are handled separately as they are N-ary
93 # * so is NOT as being unary
94 # * BETWEEN without parentheses around the ANDed arguments (which
95 #   makes it a non-binary op) is detected and accommodated in
96 #   _recurse_parse()
97 # * AS is not really an operator but is handled here as it's also LHS/RHS
98
99 # this will be included in the $binary_op_re, the distinction is interesting during
100 # testing as one is tighter than the other, plus alphanum cmp ops have different
101 # look ahead/behind (e.g. "x"="y" )
102 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
103 my $alphanum_cmp_op_re = join ("\n\t|\n", map
104   { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )"  . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
105   @alphanum_cmp_op_keywords
106 );
107 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
108
109 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
110 $binary_op_re = join "\n\t|\n",
111   "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
112   $alphanum_cmp_op_re,
113   $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
114 ;
115 $binary_op_re = qr/$binary_op_re/x;
116
117 my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix;
118
119 my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re;
120 $unary_op_re = join "\n\t|\n",
121   "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
122 ;
123 $unary_op_re = qr/$unary_op_re/x;
124
125 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
126 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
127
128 my $tokenizer_re = join("\n\t|\n",
129   $expr_start_re,
130   $binary_op_re,
131   $unary_op_re,
132   $asc_desc_re,
133   $and_or_re,
134   $op_look_behind . ' \* ' . $op_look_ahead,
135   (map { quotemeta $_ } qw/, ( )/),
136   $placeholder_re,
137 );
138
139 # this one *is* capturing for the split below
140 # splits on whitespace if all else fails
141 # has to happen before the composing qr's are anchored (below)
142 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
143
144 # Parser states for _recurse_parse()
145 use constant PARSE_TOP_LEVEL => 0;
146 use constant PARSE_IN_EXPR => 1;
147 use constant PARSE_IN_PARENS => 2;
148 use constant PARSE_IN_FUNC => 3;
149 use constant PARSE_RHS => 4;
150 use constant PARSE_LIST_ELT => 5;
151
152 my $expr_term_re = qr/$expr_start_re | \)/x;
153 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
154 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
155
156 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
157 for (
158   $quote_left,
159   $quote_right,
160   $placeholder_re,
161   $expr_start_re,
162   $alphanum_cmp_op_re,
163   $binary_op_re,
164   $unary_op_re,
165   $asc_desc_re,
166   $and_or_re,
167   $expr_term_re,
168   $rhs_term_re,
169   $all_std_keywords_re,
170 ) {
171   $_ = qr/ \A $_ \z /x;
172 }
173
174 # what can be bunched together under one MISC in an AST
175 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
176
177 my %indents = (
178    select        => 0,
179    update        => 0,
180    'insert into' => 0,
181    'delete from' => 0,
182    from          => 1,
183    where         => 0,
184    join          => 1,
185    'left join'   => 1,
186    on            => 2,
187    having        => 0,
188    'group by'    => 0,
189    'order by'    => 0,
190    set           => 1,
191    into          => 1,
192    values        => 1,
193    limit         => 1,
194    offset        => 1,
195    skip          => 1,
196    first         => 1,
197 );
198
199 my %profiles = (
200    console => {
201       fill_in_placeholders => 1,
202       placeholder_surround => ['?/', ''],
203       indent_string => ' ',
204       indent_amount => 2,
205       newline       => "\n",
206       colormap      => {},
207       indentmap     => \%indents,
208
209       eval { require Term::ANSIColor }
210         ? do {
211           my $c = \&Term::ANSIColor::color;
212
213           my $red     = [$c->('red')    , $c->('reset')];
214           my $cyan    = [$c->('cyan')   , $c->('reset')];
215           my $green   = [$c->('green')  , $c->('reset')];
216           my $yellow  = [$c->('yellow') , $c->('reset')];
217           my $blue    = [$c->('blue')   , $c->('reset')];
218           my $magenta = [$c->('magenta'), $c->('reset')];
219           my $b_o_w   = [$c->('black on_white'), $c->('reset')];
220           (
221             placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
222             colormap => {
223               'begin work'            => $b_o_w,
224               commit                  => $b_o_w,
225               rollback                => $b_o_w,
226               savepoint               => $b_o_w,
227               'rollback to savepoint' => $b_o_w,
228               'release savepoint'     => $b_o_w,
229
230               select                  => $red,
231               'insert into'           => $red,
232               update                  => $red,
233               'delete from'           => $red,
234
235               set                     => $cyan,
236               from                    => $cyan,
237
238               where                   => $green,
239               values                  => $yellow,
240
241               join                    => $magenta,
242               'left join'             => $magenta,
243               on                      => $blue,
244
245               'group by'              => $yellow,
246               having                  => $yellow,
247               'order by'              => $yellow,
248
249               skip                    => $green,
250               first                   => $green,
251               limit                   => $green,
252               offset                  => $green,
253             }
254           );
255         } : (),
256    },
257    console_monochrome => {
258       fill_in_placeholders => 1,
259       placeholder_surround => ['?/', ''],
260       indent_string => ' ',
261       indent_amount => 2,
262       newline       => "\n",
263       colormap      => {},
264       indentmap     => \%indents,
265    },
266    html => {
267       fill_in_placeholders => 1,
268       placeholder_surround => ['<span class="placeholder">', '</span>'],
269       indent_string => '&nbsp;',
270       indent_amount => 2,
271       newline       => "<br />\n",
272       colormap      => {
273          select        => ['<span class="select">'  , '</span>'],
274          'insert into' => ['<span class="insert-into">'  , '</span>'],
275          update        => ['<span class="select">'  , '</span>'],
276          'delete from' => ['<span class="delete-from">'  , '</span>'],
277
278          set           => ['<span class="set">', '</span>'],
279          from          => ['<span class="from">'    , '</span>'],
280
281          where         => ['<span class="where">'   , '</span>'],
282          values        => ['<span class="values">', '</span>'],
283
284          join          => ['<span class="join">'    , '</span>'],
285          'left join'   => ['<span class="left-join">','</span>'],
286          on            => ['<span class="on">'      , '</span>'],
287
288          'group by'    => ['<span class="group-by">', '</span>'],
289          having        => ['<span class="having">',   '</span>'],
290          'order by'    => ['<span class="order-by">', '</span>'],
291
292          skip          => ['<span class="skip">',   '</span>'],
293          first         => ['<span class="first">',  '</span>'],
294          limit         => ['<span class="limit">',  '</span>'],
295          offset        => ['<span class="offset">', '</span>'],
296
297          'begin work'  => ['<span class="begin-work">', '</span>'],
298          commit        => ['<span class="commit">', '</span>'],
299          rollback      => ['<span class="rollback">', '</span>'],
300          savepoint     => ['<span class="savepoint">', '</span>'],
301          'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
302          'release savepoint'     => ['<span class="release-savepoint">', '</span>'],
303       },
304       indentmap     => \%indents,
305    },
306    none => {
307       colormap      => {},
308       indentmap     => {},
309    },
310 );
311
312 sub new {
313    my $class = shift;
314    my $args  = shift || {};
315
316    my $profile = delete $args->{profile} || 'none';
317
318    die "No such profile '$profile'!" unless exists $profiles{$profile};
319
320    my $data = $merger->merge( $profiles{$profile}, $args );
321
322    bless $data, $class
323 }
324
325 sub parse {
326   my ($self, $s) = @_;
327
328   # tokenize string, and remove all optional whitespace
329   my $tokens = [];
330   foreach my $token (split $tokenizer_re, $s) {
331     push @$tokens, $token if (
332       defined $token
333         and
334       length $token
335         and
336       $token =~ /\S/
337     );
338   }
339
340   return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
341 }
342
343 sub _recurse_parse {
344   my ($self, $tokens, $state) = @_;
345
346   my @left;
347   while (1) { # left-associative parsing
348
349     if ( ! @$tokens
350           or
351         ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
352           or
353         ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
354           or
355         ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
356           or
357         ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
358     ) {
359       return @left;
360     }
361
362     my $token = shift @$tokens;
363
364     # nested expression in ()
365     if ($token eq '(' ) {
366       my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
367       $token = shift @$tokens   or croak "missing closing ')' around block " . $self->unparse(\@right);
368       $token eq ')'             or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
369
370       push @left, [ '-PAREN' => \@right ];
371     }
372
373     # AND/OR
374     elsif ($token =~ $and_or_re) {
375       my $op = uc $token;
376
377       my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
378
379       # Merge chunks if "logic" matches
380       @left = [ $op => [ @left, (@right and $op eq $right[0][0])
381         ? @{ $right[0][1] }
382         : @right
383       ] ];
384     }
385
386     # LIST (,)
387     elsif ($token eq ',') {
388
389       my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
390
391       # deal with malformed lists ( foo, bar, , baz )
392       @right = [] unless @right;
393
394       @right = [ -MISC => [ @right ] ] if @right > 1;
395
396       if (!@left) {
397         @left = [ -LIST => [ [], @right ] ];
398       }
399       elsif ($left[0][0] eq '-LIST') {
400         push @{$left[0][1]}, (@{$right[0]} and  $right[0][0] eq '-LIST')
401           ? @{$right[0][1]}
402           : @right
403         ;
404       }
405       else {
406         @left = [ -LIST => [ @left, @right ] ];
407       }
408     }
409
410     # binary operator keywords
411     elsif ($token =~ $binary_op_re) {
412       my $op = uc $token;
413
414       my @right = $self->_recurse_parse($tokens, PARSE_RHS);
415
416       # A between with a simple LITERAL for a 1st RHS argument needs a
417       # rerun of the search to (hopefully) find the proper AND construct
418       if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
419         unshift @$tokens, $right[1][0];
420         @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
421       }
422
423       push @left, [$op => [ (@left ? pop @left : ''), @right ]];
424     }
425
426     # unary op keywords
427     elsif ( $token =~ $unary_op_re ) {
428       my $op = uc $token;
429
430       # normalize RNO explicitly
431       $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/;
432
433       my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
434
435       push @left, [ $op => \@right ];
436     }
437
438     # expression terminator keywords
439     elsif ( $token =~ $expr_start_re ) {
440       my $op = uc $token;
441       my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
442
443       push @left, [ $op => \@right ];
444     }
445
446     # a '?'
447     elsif ( $token =~ $placeholder_re) {
448       push @left, [ -PLACEHOLDER => [ $token ] ];
449     }
450
451     # check if the current token is an unknown op-start
452     elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
453       push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
454     }
455
456     # we're now in "unknown token" land - start eating tokens until
457     # we see something familiar, OR in the case of RHS (binop) stop
458     # after the first token
459     # Also stop processing when we could end up with an unknown func
460     else {
461       my @lits = [ -LITERAL => [$token] ];
462
463       unshift @lits, pop @left if @left == 1;
464
465       unless ( $state == PARSE_RHS ) {
466         while (
467           @$tokens
468             and
469           $tokens->[0] !~ $all_std_keywords_re
470             and
471           ! ( @$tokens > 1 and $tokens->[1] eq '(' )
472         ) {
473           push @lits, [ -LITERAL => [ shift @$tokens ] ];
474         }
475       }
476
477       @lits = [ -MISC => [ @lits ] ] if @lits > 1;
478
479       push @left, @lits;
480     }
481
482     # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
483     # -MISC container
484     if (@left > 1) {
485       my $i = 0;
486       while ($#left > $i) {
487         if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
488           splice @left, $i, 2, [ -MISC => [
489             map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
490           ]];
491         }
492         else {
493           $i++;
494         }
495       }
496     }
497
498     return @left if $state == PARSE_RHS;
499
500     # deal with post-fix operators
501     if (@$tokens) {
502       # asc/desc
503       if ($tokens->[0] =~ $asc_desc_re) {
504         @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
505       }
506     }
507   }
508 }
509
510 sub format_keyword {
511   my ($self, $keyword) = @_;
512
513   if (my $around = $self->colormap->{lc $keyword}) {
514      $keyword = "$around->[0]$keyword$around->[1]";
515   }
516
517   return $keyword
518 }
519
520 my %starters = (
521    select        => 1,
522    update        => 1,
523    'insert into' => 1,
524    'delete from' => 1,
525 );
526
527 sub pad_keyword {
528    my ($self, $keyword, $depth) = @_;
529
530    my $before = '';
531    if (defined $self->indentmap->{lc $keyword}) {
532       $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
533    }
534    $before = '' if $depth == 0 and defined $starters{lc $keyword};
535    return [$before, ''];
536 }
537
538 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
539
540 sub _is_key {
541    my ($self, $tree) = @_;
542    $tree = $tree->[0] while ref $tree;
543
544    defined $tree && defined $self->indentmap->{lc $tree};
545 }
546
547 sub fill_in_placeholder {
548    my ($self, $bindargs) = @_;
549
550    if ($self->fill_in_placeholders) {
551       my $val = shift @{$bindargs} || '';
552       my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
553       my ($left, $right) = @{$self->placeholder_surround};
554       $val =~ s/\\/\\\\/g;
555       $val =~ s/'/\\'/g;
556       $val = qq('$val') if $quoted;
557       return qq($left$val$right)
558    }
559    return '?'
560 }
561
562 # FIXME - terrible name for a user facing API
563 sub unparse {
564   my ($self, $tree, $bindargs) = @_;
565   $self->_unparse($tree, [@{$bindargs||[]}], 0);
566 }
567
568 sub _unparse {
569   my ($self, $tree, $bindargs, $depth) = @_;
570
571   if (not $tree or not @$tree) {
572     return '';
573   }
574
575   # FIXME - needs a config switch to disable
576   $self->_parenthesis_unroll($tree);
577
578   my ($op, $args) = @{$tree}[0,1];
579
580   if (! defined $op or (! ref $op and ! defined $args) ) {
581     require Data::Dumper;
582     Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
583       Data::Dumper::Dumper($tree)
584     ) );
585   }
586
587   if (ref $op) {
588     return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
589   }
590   elsif ($op eq '-LITERAL') { # literal has different sig
591     return $args->[0];
592   }
593   elsif ($op eq '-PLACEHOLDER') {
594     return $self->fill_in_placeholder($bindargs);
595   }
596   elsif ($op eq '-PAREN') {
597     return sprintf ('( %s )',
598       join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
599         .
600       ($self->_is_key($args)
601         ? ( $self->newline||'' ) . $self->indent($depth + 1)
602         : ''
603       )
604     );
605   }
606   elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
607     return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
608   }
609   elsif ($op eq '-LIST' ) {
610     return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
611   }
612   elsif ($op eq '-MISC' ) {
613     return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
614   }
615   elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
616     my $dir = $1;
617     return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
618   }
619   else {
620     my ($l, $r) = @{$self->pad_keyword($op, $depth)};
621
622     my $rhs = $self->_unparse($args, $bindargs, $depth);
623
624     return sprintf "$l%s$r", join(
625       ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
626         ? ''    # mysql--
627         : ' '
628       ,
629       $self->format_keyword($op),
630       (length $rhs ? $rhs : () ),
631     );
632   }
633 }
634
635 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
636 my @unrollable_ops = (
637   'ON',
638   'WHERE',
639   'GROUP \s+ BY',
640   'HAVING',
641   'ORDER \s+ BY',
642   'I?LIKE',
643 );
644 my $unrollable_ops_re = join ' | ', @unrollable_ops;
645 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
646
647 sub _parenthesis_unroll {
648   my $self = shift;
649   my $ast = shift;
650
651   return unless (ref $ast and ref $ast->[1]);
652
653   my $changes;
654   do {
655     my @children;
656     $changes = 0;
657
658     for my $child (@{$ast->[1]}) {
659
660       # the current node in this loop is *always* a PAREN
661       if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
662         push @children, $child;
663         next;
664       }
665
666       # unroll nested parenthesis
667       while ( $ast->[0] ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
668         $child = $child->[1][0];
669         $changes++;
670       }
671
672       # if the parent operator explicitly allows it nuke the parenthesis
673       if ( $ast->[0] =~ $unrollable_ops_re ) {
674         push @children, @{$child->[1]};
675         $changes++;
676       }
677
678       # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
679       elsif (
680         @{$child->[1]} == 1
681             and
682         ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
683             and
684         $child->[1][0][0] eq $ast->[0]
685       ) {
686         push @children, @{$child->[1][0][1]};
687         $changes++;
688       }
689
690       # only *ONE* LITERAL or placeholder element
691       # as an AND/OR/NOT argument
692       elsif (
693         @{$child->[1]} == 1 && (
694           $child->[1][0][0] eq '-LITERAL'
695             or
696           $child->[1][0][0] eq '-PLACEHOLDER'
697         ) && (
698           $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
699         )
700       ) {
701         push @children, @{$child->[1]};
702         $changes++;
703       }
704
705       # an AND/OR expression with only one binop in the parenthesis
706       # with exactly two grandchildren
707       # the only time when we can *not* unroll this is when both
708       # the parent and the child are mathops (in which case we'll
709       # break precedence) or when the child is BETWEEN (special
710       # case)
711       elsif (
712         @{$child->[1]} == 1
713           and
714         ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
715           and
716         $child->[1][0][0] =~ $binary_op_re
717           and
718         $child->[1][0][0] ne 'BETWEEN'
719           and
720         @{$child->[1][0][1]} == 2
721           and
722         ! (
723           $child->[1][0][0] =~ $alphanum_cmp_op_re
724             and
725           $ast->[0] =~ $alphanum_cmp_op_re
726         )
727       ) {
728         push @children, @{$child->[1]};
729         $changes++;
730       }
731
732       # a function binds tighter than a mathop - see if our ancestor is a
733       # mathop, and our content is:
734       # a single non-mathop child with a single PAREN grandchild which
735       # would indicate mathop ( nonmathop ( ... ) )
736       # or a single non-mathop with a single LITERAL ( nonmathop foo )
737       # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
738       elsif (
739         @{$child->[1]} == 1
740           and
741         @{$child->[1][0][1]} == 1
742           and
743         $ast->[0] =~ $alphanum_cmp_op_re
744           and
745         $child->[1][0][0] !~ $alphanum_cmp_op_re
746           and
747         (
748           $child->[1][0][1][0][0] eq '-PAREN'
749             or
750           $child->[1][0][1][0][0] eq '-LITERAL'
751             or
752           $child->[1][0][1][0][0] eq '-PLACEHOLDER'
753         )
754       ) {
755         push @children, @{$child->[1]};
756         $changes++;
757       }
758
759       # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
760       # except for the case of ( NOT ( ... ) ) which has already been handled earlier
761       elsif (
762         @{$child->[1]} == 1
763           and
764         @{$child->[1][0][1]} == 1
765           and
766         $child->[1][0][0] ne 'NOT'
767           and
768         ref $child->[1][0][1][0] eq 'ARRAY'
769           and
770         $child->[1][0][1][0][0] eq '-PAREN'
771       ) {
772         push @children, @{$child->[1]};
773         $changes++;
774       }
775
776
777       # otherwise no more mucking for this pass
778       else {
779         push @children, $child;
780       }
781     }
782
783     $ast->[1] = \@children;
784
785   } while ($changes);
786 }
787
788 sub _strip_asc_from_order_by {
789   my ($self, $ast) = @_;
790
791   return $ast if (
792     ref $ast ne 'ARRAY'
793       or
794     $ast->[0] ne 'ORDER BY'
795   );
796
797
798   my $to_replace;
799
800   if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
801     $to_replace = [ $ast->[1][0] ];
802   }
803   elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
804     $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
805   }
806
807   @$_ = @{$_->[1][0]} for @$to_replace;
808
809   $ast;
810 }
811
812 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
813
814 1;
815
816 =pod
817
818 =head1 NAME
819
820 SQL::Abstract::Tree - Represent SQL as an AST
821
822 =head1 SYNOPSIS
823
824  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
825
826  print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
827
828  # SELECT *
829  #   FROM foo
830  #   WHERE foo.a > 2
831
832 =head1 METHODS
833
834 =head2 new
835
836  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
837
838  $args = {
839    profile => 'console',      # predefined profile to use (default: 'none')
840    fill_in_placeholders => 1, # true for placeholder population
841    placeholder_surround =>    # The strings that will be wrapped around
842               [GREEN, RESET], # populated placeholders if the above is set
843    indent_string => ' ',      # the string used when indenting
844    indent_amount => 2,        # how many of above string to use for a single
845                               # indent level
846    newline       => "\n",     # string for newline
847    colormap      => {
848      select => [RED, RESET], # a pair of strings defining what to surround
849                              # the keyword with for colorization
850      # ...
851    },
852    indentmap     => {
853      select        => 0,     # A zero means that the keyword will start on
854                              # a new line
855      from          => 1,     # Any other positive integer means that after
856      on            => 2,     # said newline it will get that many indents
857      # ...
858    },
859  }
860
861 Returns a new SQL::Abstract::Tree object.  All arguments are optional.
862
863 =head3 profiles
864
865 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
866 and C<html>.  Typically a user will probably just use C<console> or
867 C<console_monochrome>, but if something about a profile bothers you, merely
868 use the profile and override the parts that you don't like.
869
870 =head2 format
871
872  $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
873
874 Takes C<$sql> and C<\@bindargs>.
875
876 Returns a formatting string based on the string passed in
877
878 =head2 parse
879
880  $sqlat->parse('SELECT * FROM bar WHERE x = ?')
881
882 Returns a "tree" representing passed in SQL.  Please do not depend on the
883 structure of the returned tree.  It may be stable at some point, but not yet.
884
885 =head2 unparse
886
887  $sqlat->unparse($tree_structure, \@bindargs)
888
889 Transform "tree" into SQL, applying various transforms on the way.
890
891 =head2 format_keyword
892
893  $sqlat->format_keyword('SELECT')
894
895 Currently this just takes a keyword and puts the C<colormap> stuff around it.
896 Later on it may do more and allow for coderef based transforms.
897
898 =head2 pad_keyword
899
900  my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
901
902 Returns whitespace to be inserted around a keyword.
903
904 =head2 fill_in_placeholder
905
906  my $value = $sqlat->fill_in_placeholder(\@bindargs)
907
908 Removes last arg from passed arrayref and returns it, surrounded with
909 the values in placeholder_surround, and then surrounded with single quotes.
910
911 =head2 indent
912
913 Returns as many indent strings as indent amounts times the first argument.
914
915 =head1 ACCESSORS
916
917 =head2 colormap
918
919 See L</new>
920
921 =head2 fill_in_placeholders
922
923 See L</new>
924
925 =head2 indent_amount
926
927 See L</new>
928
929 =head2 indent_string
930
931 See L</new>
932
933 =head2 indentmap
934
935 See L</new>
936
937 =head2 newline
938
939 See L</new>
940
941 =head2 placeholder_surround
942
943 See L</new>
944