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