1 package SQL::Abstract::Tree;
3 use SQL::Abstract::_TempExtlib;
8 use Sub::Quote 'quote_sub';
13 newline indent_string indent_amount fill_in_placeholders
18 )] => ( is => 'rw', default => quote_sub('{}') );
22 )] => ( is => 'rw', default => quote_sub('[]') );
24 my $merger = Hash::Merge->new;
26 $merger->specify_behavior({
28 SCALAR => sub { $_[1] },
29 ARRAY => sub { [ $_[0], @{$_[1]} ] },
30 HASH => sub { $_[1] },
33 SCALAR => sub { $_[1] },
34 ARRAY => sub { $_[1] },
35 HASH => sub { $_[1] },
38 SCALAR => sub { $_[1] },
39 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
40 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
42 }, 'SQLA::Tree Behavior' );
44 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
45 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
47 my $quote_left = qr/[\`\'\"\[]/;
48 my $quote_right = qr/[\`\'\"\]]/;
50 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
52 # These SQL keywords always signal end of the current expression (except inside
53 # of a parenthesized subexpression).
54 # Format: A list of strings that will be compiled to extended syntax ie.
55 # /.../x) regexes, without capturing parentheses. They will be automatically
56 # anchored to op boundaries (excluding quotes) to match the whole token.
57 my @expression_start_keywords = (
66 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
67 (?: (?: CROSS | INNER | OUTER ) \s+ )?
73 '(?: DEFAULT \s+ )? VALUES',
88 'ROLLBACK \s+ TO \s+ SAVEPOINT',
91 'RELEASE \s+ SAVEPOINT',
93 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
96 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
97 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
99 # These are binary operator keywords always a single LHS and RHS
100 # * AND/OR are handled separately as they are N-ary
101 # * so is NOT as being unary
102 # * BETWEEN without parentheses around the ANDed arguments (which
103 # makes it a non-binary op) is detected and accommodated in
105 # * AS is not really an operator but is handled here as it's also LHS/RHS
107 # this will be included in the $binary_op_re, the distinction is interesting during
108 # testing as one is tighter than the other, plus alphanum cmp ops have different
109 # look ahead/behind (e.g. "x"="y" )
110 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
111 my $alphanum_cmp_op_re = join ("\n\t|\n", map
112 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
113 @alphanum_cmp_op_keywords
115 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
117 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
118 $binary_op_re = join "\n\t|\n",
119 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
121 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
123 $binary_op_re = qr/$binary_op_re/x;
125 my $unary_op_re = '(?: NOT \s+ EXISTS | NOT )';
126 $unary_op_re = join "\n\t|\n",
127 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
129 $unary_op_re = qr/$unary_op_re/x;
131 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
132 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
134 my $tokenizer_re = join("\n\t|\n",
140 $op_look_behind . ' \* ' . $op_look_ahead,
141 (map { quotemeta $_ } qw/, ( )/),
145 # this one *is* capturing for the split below
146 # splits on whitespace if all else fails
147 # has to happen before the composing qr's are anchored (below)
148 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
150 # Parser states for _recurse_parse()
151 use constant PARSE_TOP_LEVEL => 0;
152 use constant PARSE_IN_EXPR => 1;
153 use constant PARSE_IN_PARENS => 2;
154 use constant PARSE_IN_FUNC => 3;
155 use constant PARSE_RHS => 4;
156 use constant PARSE_LIST_ELT => 5;
158 my $expr_term_re = qr/$expr_start_re | \)/x;
159 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
160 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
162 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
175 $all_std_keywords_re,
177 $_ = qr/ \A $_ \z /x;
180 # what can be bunched together under one MISC in an AST
181 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
207 fill_in_placeholders => 1,
208 placeholder_surround => ['?/', ''],
209 indent_string => ' ',
213 indentmap => \%indents,
215 eval { require Term::ANSIColor }
217 my $c = \&Term::ANSIColor::color;
219 my $red = [$c->('red') , $c->('reset')];
220 my $cyan = [$c->('cyan') , $c->('reset')];
221 my $green = [$c->('green') , $c->('reset')];
222 my $yellow = [$c->('yellow') , $c->('reset')];
223 my $blue = [$c->('blue') , $c->('reset')];
224 my $magenta = [$c->('magenta'), $c->('reset')];
225 my $b_o_w = [$c->('black on_white'), $c->('reset')];
227 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
229 'begin work' => $b_o_w,
233 'rollback to savepoint' => $b_o_w,
234 'release savepoint' => $b_o_w,
237 'insert into' => $red,
239 'delete from' => $red,
248 'left join' => $magenta,
251 'group by' => $yellow,
253 'order by' => $yellow,
263 console_monochrome => {
264 fill_in_placeholders => 1,
265 placeholder_surround => ['?/', ''],
266 indent_string => ' ',
270 indentmap => \%indents,
273 fill_in_placeholders => 1,
274 placeholder_surround => ['<span class="placeholder">', '</span>'],
275 indent_string => ' ',
277 newline => "<br />\n",
279 select => ['<span class="select">' , '</span>'],
280 'insert into' => ['<span class="insert-into">' , '</span>'],
281 update => ['<span class="select">' , '</span>'],
282 'delete from' => ['<span class="delete-from">' , '</span>'],
284 set => ['<span class="set">', '</span>'],
285 from => ['<span class="from">' , '</span>'],
287 where => ['<span class="where">' , '</span>'],
288 values => ['<span class="values">', '</span>'],
290 join => ['<span class="join">' , '</span>'],
291 'left join' => ['<span class="left-join">','</span>'],
292 on => ['<span class="on">' , '</span>'],
294 'group by' => ['<span class="group-by">', '</span>'],
295 having => ['<span class="having">', '</span>'],
296 'order by' => ['<span class="order-by">', '</span>'],
298 skip => ['<span class="skip">', '</span>'],
299 first => ['<span class="first">', '</span>'],
300 limit => ['<span class="limit">', '</span>'],
301 offset => ['<span class="offset">', '</span>'],
303 'begin work' => ['<span class="begin-work">', '</span>'],
304 commit => ['<span class="commit">', '</span>'],
305 rollback => ['<span class="rollback">', '</span>'],
306 savepoint => ['<span class="savepoint">', '</span>'],
307 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
308 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
310 indentmap => \%indents,
320 my $args = { (ref $_[0] eq 'HASH') ? %{$_[0]} : @_ };
321 my $profile = delete $args->{profile} || 'none';
323 die "No such profile '$profile'!" unless exists $profiles{$profile};
325 return $merger->merge( $profiles{$profile}, $args );
331 # tokenize string, and remove all optional whitespace
333 foreach my $token (split $tokenizer_re, $s) {
334 push @$tokens, $token if (
343 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
347 my ($self, $tokens, $state) = @_;
350 while (1) { # left-associative parsing
354 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
356 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
358 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
360 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
365 my $token = shift @$tokens;
367 # nested expression in ()
368 if ($token eq '(' ) {
369 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
370 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
371 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
373 push @left, [ '-PAREN' => \@right ];
377 elsif ($token =~ $and_or_re) {
380 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
382 # Merge chunks if "logic" matches
383 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
390 elsif ($token eq ',') {
392 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
394 # deal with malformed lists ( foo, bar, , baz )
395 @right = [] unless @right;
397 @right = [ -MISC => [ @right ] ] if @right > 1;
400 @left = [ -LIST => [ [], @right ] ];
402 elsif ($left[0][0] eq '-LIST') {
403 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
409 @left = [ -LIST => [ @left, @right ] ];
413 # binary operator keywords
414 elsif ($token =~ $binary_op_re) {
417 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
419 # A between with a simple LITERAL for a 1st RHS argument needs a
420 # rerun of the search to (hopefully) find the proper AND construct
421 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
422 unshift @$tokens, $right[1][0];
423 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
426 @left = [$op => [ @left, @right ]];
430 elsif ( $token =~ $unary_op_re ) {
432 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
434 push @left, [ $op => \@right ];
437 # expression terminator keywords
438 elsif ( $token =~ $expr_start_re ) {
440 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
442 push @left, [ $op => \@right ];
446 elsif ( $token =~ $placeholder_re) {
447 push @left, [ -PLACEHOLDER => [ $token ] ];
450 # check if the current token is an unknown op-start
451 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
452 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
455 # we're now in "unknown token" land - start eating tokens until
456 # we see something familiar, OR in the case of RHS (binop) stop
457 # after the first token
458 # Also stop processing when we could end up with an unknown func
460 my @lits = [ -LITERAL => [$token] ];
462 unshift @lits, pop @left if @left == 1;
464 unless ( $state == PARSE_RHS ) {
468 $tokens->[0] !~ $all_std_keywords_re
470 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
472 push @lits, [ -LITERAL => [ shift @$tokens ] ];
476 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
481 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
485 while ($#left > $i) {
486 if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
487 splice @left, $i, 2, [ -MISC => [
488 map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
497 return @left if $state == PARSE_RHS;
499 # deal with post-fix operators
502 if ($tokens->[0] =~ $asc_desc_re) {
503 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
510 my ($self, $keyword) = @_;
512 if (my $around = $self->colormap->{lc $keyword}) {
513 $keyword = "$around->[0]$keyword$around->[1]";
527 my ($self, $keyword, $depth) = @_;
530 if (defined $self->indentmap->{lc $keyword}) {
531 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
533 $before = '' if $depth == 0 and defined $starters{lc $keyword};
534 return [$before, ''];
537 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
540 my ($self, $tree) = @_;
541 $tree = $tree->[0] while ref $tree;
543 defined $tree && defined $self->indentmap->{lc $tree};
546 sub fill_in_placeholder {
547 my ($self, $bindargs) = @_;
549 if ($self->fill_in_placeholders) {
550 my $val = shift @{$bindargs} || '';
551 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
552 my ($left, $right) = @{$self->placeholder_surround};
555 $val = qq('$val') if $quoted;
556 return qq($left$val$right)
561 # FIXME - terrible name for a user facing API
563 my ($self, $tree, $bindargs) = @_;
564 $self->_unparse($tree, [@{$bindargs||[]}], 0);
568 my ($self, $tree, $bindargs, $depth) = @_;
570 if (not $tree or not @$tree) {
574 # FIXME - needs a config switch to disable
575 $self->_parenthesis_unroll($tree);
577 my ($op, $args) = @{$tree}[0,1];
579 if (! defined $op or (! ref $op and ! defined $args) ) {
580 require Data::Dumper;
581 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
582 Data::Dumper::Dumper($tree)
587 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
589 elsif ($op eq '-LITERAL') { # literal has different sig
592 elsif ($op eq '-PLACEHOLDER') {
593 return $self->fill_in_placeholder($bindargs);
595 elsif ($op eq '-PAREN') {
596 return sprintf ('( %s )',
597 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
599 ($self->_is_key($args)
600 ? ( $self->newline||'' ) . $self->indent($depth + 1)
605 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
606 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
608 elsif ($op eq '-LIST' ) {
609 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
611 elsif ($op eq '-MISC' ) {
612 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
614 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
616 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
619 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
621 my $rhs = $self->_unparse($args, $bindargs, $depth);
623 return sprintf "$l%s$r", join(
624 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
628 $self->format_keyword($op),
629 (length $rhs ? $rhs : () ),
634 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
635 my @unrollable_ops = (
643 my $unrollable_ops_re = join ' | ', @unrollable_ops;
644 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
646 sub _parenthesis_unroll {
650 return unless (ref $ast and ref $ast->[1]);
657 for my $child (@{$ast->[1]}) {
659 # the current node in this loop is *always* a PAREN
660 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
661 push @children, $child;
665 # unroll nested parenthesis
666 while ( $ast->[0] ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
667 $child = $child->[1][0];
671 # if the parent operator explicitly allows it nuke the parenthesis
672 if ( $ast->[0] =~ $unrollable_ops_re ) {
673 push @children, @{$child->[1]};
677 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
681 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
683 $child->[1][0][0] eq $ast->[0]
685 push @children, @{$child->[1][0][1]};
689 # only *ONE* LITERAL or placeholder element
690 # as an AND/OR/NOT argument
692 @{$child->[1]} == 1 && (
693 $child->[1][0][0] eq '-LITERAL'
695 $child->[1][0][0] eq '-PLACEHOLDER'
697 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
700 push @children, @{$child->[1]};
704 # an AND/OR expression with only one binop in the parenthesis
705 # with exactly two grandchildren
706 # the only time when we can *not* unroll this is when both
707 # the parent and the child are mathops (in which case we'll
708 # break precedence) or when the child is BETWEEN (special
713 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
715 $child->[1][0][0] =~ $binary_op_re
717 $child->[1][0][0] ne 'BETWEEN'
719 @{$child->[1][0][1]} == 2
722 $child->[1][0][0] =~ $alphanum_cmp_op_re
724 $ast->[0] =~ $alphanum_cmp_op_re
727 push @children, @{$child->[1]};
731 # a function binds tighter than a mathop - see if our ancestor is a
732 # mathop, and our content is:
733 # a single non-mathop child with a single PAREN grandchild which
734 # would indicate mathop ( nonmathop ( ... ) )
735 # or a single non-mathop with a single LITERAL ( nonmathop foo )
736 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
740 @{$child->[1][0][1]} == 1
742 $ast->[0] =~ $alphanum_cmp_op_re
744 $child->[1][0][0] !~ $alphanum_cmp_op_re
747 $child->[1][0][1][0][0] eq '-PAREN'
749 $child->[1][0][1][0][0] eq '-LITERAL'
751 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
754 push @children, @{$child->[1]};
758 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
759 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
763 @{$child->[1][0][1]} == 1
765 $child->[1][0][0] ne 'NOT'
767 ref $child->[1][0][1][0] eq 'ARRAY'
769 $child->[1][0][1][0][0] eq '-PAREN'
771 push @children, @{$child->[1]};
776 # otherwise no more mucking for this pass
778 push @children, $child;
782 $ast->[1] = \@children;
787 sub _strip_asc_from_order_by {
788 my ($self, $ast) = @_;
793 $ast->[0] ne 'ORDER BY'
799 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
800 $to_replace = [ $ast->[1][0] ];
802 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
803 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
806 @$_ = @{$_->[1][0]} for @$to_replace;
811 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
819 SQL::Abstract::Tree - Represent SQL as an AST
823 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
825 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
835 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
838 profile => 'console', # predefined profile to use (default: 'none')
839 fill_in_placeholders => 1, # true for placeholder population
840 placeholder_surround => # The strings that will be wrapped around
841 [GREEN, RESET], # populated placeholders if the above is set
842 indent_string => ' ', # the string used when indenting
843 indent_amount => 2, # how many of above string to use for a single
845 newline => "\n", # string for newline
847 select => [RED, RESET], # a pair of strings defining what to surround
848 # the keyword with for colorization
852 select => 0, # A zero means that the keyword will start on
854 from => 1, # Any other positive integer means that after
855 on => 2, # said newline it will get that many indents
860 Returns a new SQL::Abstract::Tree object. All arguments are optional.
864 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
865 and C<html>. Typically a user will probably just use C<console> or
866 C<console_monochrome>, but if something about a profile bothers you, merely
867 use the profile and override the parts that you don't like.
871 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
873 Takes C<$sql> and C<\@bindargs>.
875 Returns a formatting string based on the string passed in
879 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
881 Returns a "tree" representing passed in SQL. Please do not depend on the
882 structure of the returned tree. It may be stable at some point, but not yet.
886 $sqlat->unparse($tree_structure, \@bindargs)
888 Transform "tree" into SQL, applying various transforms on the way.
890 =head2 format_keyword
892 $sqlat->format_keyword('SELECT')
894 Currently this just takes a keyword and puts the C<colormap> stuff around it.
895 Later on it may do more and allow for coderef based transforms.
899 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
901 Returns whitespace to be inserted around a keyword.
903 =head2 fill_in_placeholder
905 my $value = $sqlat->fill_in_placeholder(\@bindargs)
907 Removes last arg from passed arrayref and returns it, surrounded with
908 the values in placeholder_surround, and then surrounded with single quotes.
912 Returns as many indent strings as indent amounts times the first argument.
920 =head2 fill_in_placeholders
940 =head2 placeholder_surround