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