1 package SQL::Abstract::Tree;
6 use Sub::Quote 'quote_sub';
11 newline indent_string indent_amount fill_in_placeholders
16 )] => ( is => 'rw', default => quote_sub('{}') );
20 )] => ( is => 'rw', default => quote_sub('[]') );
22 my $merger = Hash::Merge->new;
24 $merger->specify_behavior({
26 SCALAR => sub { $_[1] },
27 ARRAY => sub { [ $_[0], @{$_[1]} ] },
28 HASH => sub { $_[1] },
31 SCALAR => sub { $_[1] },
32 ARRAY => sub { $_[1] },
33 HASH => sub { $_[1] },
36 SCALAR => sub { $_[1] },
37 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
38 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
40 }, 'SQLA::Tree Behavior' );
42 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
43 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
45 my $quote_left = qr/[\`\'\"\[]/;
46 my $quote_right = qr/[\`\'\"\]]/;
48 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
50 # These SQL keywords always signal end of the current expression (except inside
51 # of a parenthesized subexpression).
52 # Format: A list of strings that will be compiled to extended syntax ie.
53 # /.../x) regexes, without capturing parentheses. They will be automatically
54 # anchored to op boundaries (excluding quotes) to match the whole token.
55 my @expression_start_keywords = (
64 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
65 (?: (?: CROSS | INNER | OUTER ) \s+ )?
71 '(?: DEFAULT \s+ )? VALUES',
86 'ROLLBACK \s+ TO \s+ SAVEPOINT',
89 'RELEASE \s+ SAVEPOINT',
91 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
94 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
95 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
97 # These are binary operator keywords always a single LHS and RHS
98 # * AND/OR are handled separately as they are N-ary
99 # * so is NOT as being unary
100 # * BETWEEN without parentheses around the ANDed arguments (which
101 # makes it a non-binary op) is detected and accommodated in
103 # * AS is not really an operator but is handled here as it's also LHS/RHS
105 # this will be included in the $binary_op_re, the distinction is interesting during
106 # testing as one is tighter than the other, plus alphanum cmp ops have different
107 # look ahead/behind (e.g. "x"="y" )
108 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
109 my $alphanum_cmp_op_re = join ("\n\t|\n", map
110 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
111 @alphanum_cmp_op_keywords
113 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
115 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
116 $binary_op_re = join "\n\t|\n",
117 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
119 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
121 $binary_op_re = qr/$binary_op_re/x;
123 my $unary_op_re = '(?: NOT \s+ EXISTS | NOT )';
124 $unary_op_re = join "\n\t|\n",
125 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
127 $unary_op_re = qr/$unary_op_re/x;
129 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
130 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
132 my $tokenizer_re = join("\n\t|\n",
138 $op_look_behind . ' \* ' . $op_look_ahead,
139 (map { quotemeta $_ } qw/, ( )/),
143 # this one *is* capturing for the split below
144 # splits on whitespace if all else fails
145 # has to happen before the composing qr's are anchored (below)
146 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
148 # Parser states for _recurse_parse()
149 use constant PARSE_TOP_LEVEL => 0;
150 use constant PARSE_IN_EXPR => 1;
151 use constant PARSE_IN_PARENS => 2;
152 use constant PARSE_IN_FUNC => 3;
153 use constant PARSE_RHS => 4;
154 use constant PARSE_LIST_ELT => 5;
156 my $expr_term_re = qr/$expr_start_re | \)/x;
157 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
158 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
160 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
173 $all_std_keywords_re,
175 $_ = qr/ \A $_ \z /x;
178 # what can be bunched together under one MISC in an AST
179 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
205 fill_in_placeholders => 1,
206 placeholder_surround => ['?/', ''],
207 indent_string => ' ',
211 indentmap => \%indents,
213 eval { require Term::ANSIColor }
215 my $c = \&Term::ANSIColor::color;
217 my $red = [$c->('red') , $c->('reset')];
218 my $cyan = [$c->('cyan') , $c->('reset')];
219 my $green = [$c->('green') , $c->('reset')];
220 my $yellow = [$c->('yellow') , $c->('reset')];
221 my $blue = [$c->('blue') , $c->('reset')];
222 my $magenta = [$c->('magenta'), $c->('reset')];
223 my $b_o_w = [$c->('black on_white'), $c->('reset')];
225 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
227 'begin work' => $b_o_w,
231 'rollback to savepoint' => $b_o_w,
232 'release savepoint' => $b_o_w,
235 'insert into' => $red,
237 'delete from' => $red,
246 'left join' => $magenta,
249 'group by' => $yellow,
251 'order by' => $yellow,
261 console_monochrome => {
262 fill_in_placeholders => 1,
263 placeholder_surround => ['?/', ''],
264 indent_string => ' ',
268 indentmap => \%indents,
271 fill_in_placeholders => 1,
272 placeholder_surround => ['<span class="placeholder">', '</span>'],
273 indent_string => ' ',
275 newline => "<br />\n",
277 select => ['<span class="select">' , '</span>'],
278 'insert into' => ['<span class="insert-into">' , '</span>'],
279 update => ['<span class="select">' , '</span>'],
280 'delete from' => ['<span class="delete-from">' , '</span>'],
282 set => ['<span class="set">', '</span>'],
283 from => ['<span class="from">' , '</span>'],
285 where => ['<span class="where">' , '</span>'],
286 values => ['<span class="values">', '</span>'],
288 join => ['<span class="join">' , '</span>'],
289 'left join' => ['<span class="left-join">','</span>'],
290 on => ['<span class="on">' , '</span>'],
292 'group by' => ['<span class="group-by">', '</span>'],
293 having => ['<span class="having">', '</span>'],
294 'order by' => ['<span class="order-by">', '</span>'],
296 skip => ['<span class="skip">', '</span>'],
297 first => ['<span class="first">', '</span>'],
298 limit => ['<span class="limit">', '</span>'],
299 offset => ['<span class="offset">', '</span>'],
301 'begin work' => ['<span class="begin-work">', '</span>'],
302 commit => ['<span class="commit">', '</span>'],
303 rollback => ['<span class="rollback">', '</span>'],
304 savepoint => ['<span class="savepoint">', '</span>'],
305 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
306 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
308 indentmap => \%indents,
318 my $args = { (ref $_[0] eq 'HASH') ? %{$_[0]} : @_ };
319 my $profile = delete $args->{profile} || 'none';
321 die "No such profile '$profile'!" unless exists $profiles{$profile};
323 return $merger->merge( $profiles{$profile}, $args );
329 # tokenize string, and remove all optional whitespace
331 foreach my $token (split $tokenizer_re, $s) {
332 push @$tokens, $token if (
341 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
345 my ($self, $tokens, $state) = @_;
348 while (1) { # left-associative parsing
352 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
354 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
356 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
358 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
363 my $token = shift @$tokens;
365 # nested expression in ()
366 if ($token eq '(' ) {
367 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
368 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
369 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
371 push @left, [ '-PAREN' => \@right ];
375 elsif ($token =~ $and_or_re) {
378 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
380 # Merge chunks if "logic" matches
381 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
388 elsif ($token eq ',') {
390 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
392 # deal with malformed lists ( foo, bar, , baz )
393 @right = [] unless @right;
395 @right = [ -MISC => [ @right ] ] if @right > 1;
398 @left = [ -LIST => [ [], @right ] ];
400 elsif ($left[0][0] eq '-LIST') {
401 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
407 @left = [ -LIST => [ @left, @right ] ];
411 # binary operator keywords
412 elsif ($token =~ $binary_op_re) {
415 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
417 # A between with a simple LITERAL for a 1st RHS argument needs a
418 # rerun of the search to (hopefully) find the proper AND construct
419 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
420 unshift @$tokens, $right[1][0];
421 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
424 @left = [$op => [ @left, @right ]];
428 elsif ( $token =~ $unary_op_re ) {
430 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
432 push @left, [ $op => \@right ];
435 # expression terminator keywords
436 elsif ( $token =~ $expr_start_re ) {
438 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
440 push @left, [ $op => \@right ];
444 elsif ( $token =~ $placeholder_re) {
445 push @left, [ -PLACEHOLDER => [ $token ] ];
448 # check if the current token is an unknown op-start
449 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
450 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
453 # we're now in "unknown token" land - start eating tokens until
454 # we see something familiar, OR in the case of RHS (binop) stop
455 # after the first token
456 # Also stop processing when we could end up with an unknown func
458 my @lits = [ -LITERAL => [$token] ];
460 unshift @lits, pop @left if @left == 1;
462 unless ( $state == PARSE_RHS ) {
466 $tokens->[0] !~ $all_std_keywords_re
468 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
470 push @lits, [ -LITERAL => [ shift @$tokens ] ];
474 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
479 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
483 while ($#left > $i) {
484 if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
485 splice @left, $i, 2, [ -MISC => [
486 map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
495 return @left if $state == PARSE_RHS;
497 # deal with post-fix operators
500 if ($tokens->[0] =~ $asc_desc_re) {
501 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
508 my ($self, $keyword) = @_;
510 if (my $around = $self->colormap->{lc $keyword}) {
511 $keyword = "$around->[0]$keyword$around->[1]";
525 my ($self, $keyword, $depth) = @_;
528 if (defined $self->indentmap->{lc $keyword}) {
529 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
531 $before = '' if $depth == 0 and defined $starters{lc $keyword};
532 return [$before, ''];
535 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
538 my ($self, $tree) = @_;
539 $tree = $tree->[0] while ref $tree;
541 defined $tree && defined $self->indentmap->{lc $tree};
544 sub fill_in_placeholder {
545 my ($self, $bindargs) = @_;
547 if ($self->fill_in_placeholders) {
548 my $val = shift @{$bindargs} || '';
549 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
550 my ($left, $right) = @{$self->placeholder_surround};
553 $val = qq('$val') if $quoted;
554 return qq($left$val$right)
559 # FIXME - terrible name for a user facing API
561 my ($self, $tree, $bindargs) = @_;
562 $self->_unparse($tree, [@{$bindargs||[]}], 0);
566 my ($self, $tree, $bindargs, $depth) = @_;
568 if (not $tree or not @$tree) {
572 # FIXME - needs a config switch to disable
573 $self->_parenthesis_unroll($tree);
575 my ($op, $args) = @{$tree}[0,1];
577 if (! defined $op or (! ref $op and ! defined $args) ) {
578 require Data::Dumper;
579 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
580 Data::Dumper::Dumper($tree)
585 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
587 elsif ($op eq '-LITERAL') { # literal has different sig
590 elsif ($op eq '-PLACEHOLDER') {
591 return $self->fill_in_placeholder($bindargs);
593 elsif ($op eq '-PAREN') {
594 return sprintf ('( %s )',
595 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
597 ($self->_is_key($args)
598 ? ( $self->newline||'' ) . $self->indent($depth + 1)
603 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
604 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
606 elsif ($op eq '-LIST' ) {
607 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
609 elsif ($op eq '-MISC' ) {
610 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
612 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
614 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
617 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
619 my $rhs = $self->_unparse($args, $bindargs, $depth);
621 return sprintf "$l%s$r", join(
622 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
626 $self->format_keyword($op),
627 (length $rhs ? $rhs : () ),
632 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
633 my @unrollable_ops = (
641 my $unrollable_ops_re = join ' | ', @unrollable_ops;
642 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
644 sub _parenthesis_unroll {
648 return unless (ref $ast and ref $ast->[1]);
655 for my $child (@{$ast->[1]}) {
657 # the current node in this loop is *always* a PAREN
658 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
659 push @children, $child;
663 # unroll nested parenthesis
664 while ( $ast->[0] ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
665 $child = $child->[1][0];
669 # if the parent operator explicitly allows it nuke the parenthesis
670 if ( $ast->[0] =~ $unrollable_ops_re ) {
671 push @children, @{$child->[1]};
675 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
679 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
681 $child->[1][0][0] eq $ast->[0]
683 push @children, @{$child->[1][0][1]};
687 # only *ONE* LITERAL or placeholder element
688 # as an AND/OR/NOT argument
690 @{$child->[1]} == 1 && (
691 $child->[1][0][0] eq '-LITERAL'
693 $child->[1][0][0] eq '-PLACEHOLDER'
695 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
698 push @children, @{$child->[1]};
702 # an AND/OR expression with only one binop in the parenthesis
703 # with exactly two grandchildren
704 # the only time when we can *not* unroll this is when both
705 # the parent and the child are mathops (in which case we'll
706 # break precedence) or when the child is BETWEEN (special
711 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
713 $child->[1][0][0] =~ $binary_op_re
715 $child->[1][0][0] ne 'BETWEEN'
717 @{$child->[1][0][1]} == 2
720 $child->[1][0][0] =~ $alphanum_cmp_op_re
722 $ast->[0] =~ $alphanum_cmp_op_re
725 push @children, @{$child->[1]};
729 # a function binds tighter than a mathop - see if our ancestor is a
730 # mathop, and our content is:
731 # a single non-mathop child with a single PAREN grandchild which
732 # would indicate mathop ( nonmathop ( ... ) )
733 # or a single non-mathop with a single LITERAL ( nonmathop foo )
734 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
738 @{$child->[1][0][1]} == 1
740 $ast->[0] =~ $alphanum_cmp_op_re
742 $child->[1][0][0] !~ $alphanum_cmp_op_re
745 $child->[1][0][1][0][0] eq '-PAREN'
747 $child->[1][0][1][0][0] eq '-LITERAL'
749 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
752 push @children, @{$child->[1]};
756 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
757 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
761 @{$child->[1][0][1]} == 1
763 $child->[1][0][0] ne 'NOT'
765 ref $child->[1][0][1][0] eq 'ARRAY'
767 $child->[1][0][1][0][0] eq '-PAREN'
769 push @children, @{$child->[1]};
774 # otherwise no more mucking for this pass
776 push @children, $child;
780 $ast->[1] = \@children;
785 sub _strip_asc_from_order_by {
786 my ($self, $ast) = @_;
791 $ast->[0] ne 'ORDER BY'
797 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
798 $to_replace = [ $ast->[1][0] ];
800 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
801 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
804 @$_ = @{$_->[1][0]} for @$to_replace;
809 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
817 SQL::Abstract::Tree - Represent SQL as an AST
821 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
823 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
833 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
836 profile => 'console', # predefined profile to use (default: 'none')
837 fill_in_placeholders => 1, # true for placeholder population
838 placeholder_surround => # The strings that will be wrapped around
839 [GREEN, RESET], # populated placeholders if the above is set
840 indent_string => ' ', # the string used when indenting
841 indent_amount => 2, # how many of above string to use for a single
843 newline => "\n", # string for newline
845 select => [RED, RESET], # a pair of strings defining what to surround
846 # the keyword with for colorization
850 select => 0, # A zero means that the keyword will start on
852 from => 1, # Any other positive integer means that after
853 on => 2, # said newline it will get that many indents
858 Returns a new SQL::Abstract::Tree object. All arguments are optional.
862 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
863 and C<html>. Typically a user will probably just use C<console> or
864 C<console_monochrome>, but if something about a profile bothers you, merely
865 use the profile and override the parts that you don't like.
869 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
871 Takes C<$sql> and C<\@bindargs>.
873 Returns a formatting string based on the string passed in
877 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
879 Returns a "tree" representing passed in SQL. Please do not depend on the
880 structure of the returned tree. It may be stable at some point, but not yet.
884 $sqlat->unparse($tree_structure, \@bindargs)
886 Transform "tree" into SQL, applying various transforms on the way.
888 =head2 format_keyword
890 $sqlat->format_keyword('SELECT')
892 Currently this just takes a keyword and puts the C<colormap> stuff around it.
893 Later on it may do more and allow for coderef based transforms.
897 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
899 Returns whitespace to be inserted around a keyword.
901 =head2 fill_in_placeholder
903 my $value = $sqlat->fill_in_placeholder(\@bindargs)
905 Removes last arg from passed arrayref and returns it, surrounded with
906 the values in placeholder_surround, and then surrounded with single quotes.
910 Returns as many indent strings as indent amounts times the first argument.
918 =head2 fill_in_placeholders
938 =head2 placeholder_surround