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