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