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