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