1 package SQL::Abstract::Tree;
10 use base 'Class::Accessor::Grouped';
12 __PACKAGE__->mk_group_accessors( simple => qw(
13 newline indent_string indent_amount colormap indentmap fill_in_placeholders
17 my $merger = Hash::Merge->new;
19 $merger->specify_behavior({
21 SCALAR => sub { $_[1] },
22 ARRAY => sub { [ $_[0], @{$_[1]} ] },
23 HASH => sub { $_[1] },
26 SCALAR => sub { $_[1] },
27 ARRAY => sub { $_[1] },
28 HASH => sub { $_[1] },
31 SCALAR => sub { $_[1] },
32 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
33 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
35 }, 'SQLA::Tree Behavior' );
37 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
38 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
40 my $quote_left = qr/[\`\'\"\[]/;
41 my $quote_right = qr/[\`\'\"\]]/;
43 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
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 = (
59 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
60 (?: (?: CROSS | INNER | OUTER ) \s+ )?
66 '(?: DEFAULT \s+ )? VALUES',
80 'ROLLBACK \s+ TO \s+ SAVEPOINT',
83 'RELEASE \s+ SAVEPOINT',
85 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
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;
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
97 # * AS is not really an operator but is handled here as it's also LHS/RHS
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
107 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
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",
113 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
115 $binary_op_re = qr/$binary_op_re/x;
117 my $unary_op_re = '(?: NOT \s+ EXISTS | NOT )';
118 $unary_op_re = join "\n\t|\n",
119 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
121 $unary_op_re = qr/$unary_op_re/x;
123 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
124 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
126 my $tokenizer_re = join("\n\t|\n",
132 $op_look_behind . ' \* ' . $op_look_ahead,
133 (map { quotemeta $_ } qw/, ( )/),
137 # this one *is* capturing for the split below
138 # splits on whitespace if all else fails
139 # has to happen before the composing qr's are anchored (below)
140 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
142 # Parser states for _recurse_parse()
143 use constant PARSE_TOP_LEVEL => 0;
144 use constant PARSE_IN_EXPR => 1;
145 use constant PARSE_IN_PARENS => 2;
146 use constant PARSE_IN_FUNC => 3;
147 use constant PARSE_RHS => 4;
148 use constant PARSE_LIST_ELT => 5;
150 my $expr_term_re = qr/$expr_start_re | \)/x;
151 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
152 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
154 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
167 $all_std_keywords_re,
169 $_ = qr/ \A $_ \z /x;
172 # what can be bunched together under one MISC in an AST
173 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
199 fill_in_placeholders => 1,
200 placeholder_surround => ['?/', ''],
201 indent_string => ' ',
205 indentmap => \%indents,
207 eval { require Term::ANSIColor }
209 my $c = \&Term::ANSIColor::color;
211 my $red = [$c->('red') , $c->('reset')];
212 my $cyan = [$c->('cyan') , $c->('reset')];
213 my $green = [$c->('green') , $c->('reset')];
214 my $yellow = [$c->('yellow') , $c->('reset')];
215 my $blue = [$c->('blue') , $c->('reset')];
216 my $magenta = [$c->('magenta'), $c->('reset')];
217 my $b_o_w = [$c->('black on_white'), $c->('reset')];
219 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
221 'begin work' => $b_o_w,
225 'rollback to savepoint' => $b_o_w,
226 'release savepoint' => $b_o_w,
229 'insert into' => $red,
231 'delete from' => $red,
240 'left join' => $magenta,
243 'group by' => $yellow,
245 'order by' => $yellow,
255 console_monochrome => {
256 fill_in_placeholders => 1,
257 placeholder_surround => ['?/', ''],
258 indent_string => ' ',
262 indentmap => \%indents,
265 fill_in_placeholders => 1,
266 placeholder_surround => ['<span class="placeholder">', '</span>'],
267 indent_string => ' ',
269 newline => "<br />\n",
271 select => ['<span class="select">' , '</span>'],
272 'insert into' => ['<span class="insert-into">' , '</span>'],
273 update => ['<span class="select">' , '</span>'],
274 'delete from' => ['<span class="delete-from">' , '</span>'],
276 set => ['<span class="set">', '</span>'],
277 from => ['<span class="from">' , '</span>'],
279 where => ['<span class="where">' , '</span>'],
280 values => ['<span class="values">', '</span>'],
282 join => ['<span class="join">' , '</span>'],
283 'left join' => ['<span class="left-join">','</span>'],
284 on => ['<span class="on">' , '</span>'],
286 'group by' => ['<span class="group-by">', '</span>'],
287 having => ['<span class="having">', '</span>'],
288 'order by' => ['<span class="order-by">', '</span>'],
290 skip => ['<span class="skip">', '</span>'],
291 first => ['<span class="first">', '</span>'],
292 limit => ['<span class="limit">', '</span>'],
293 offset => ['<span class="offset">', '</span>'],
295 'begin work' => ['<span class="begin-work">', '</span>'],
296 commit => ['<span class="commit">', '</span>'],
297 rollback => ['<span class="rollback">', '</span>'],
298 savepoint => ['<span class="savepoint">', '</span>'],
299 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
300 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
302 indentmap => \%indents,
312 my $args = shift || {};
314 my $profile = delete $args->{profile} || 'none';
316 die "No such profile '$profile'!" unless exists $profiles{$profile};
318 my $data = $merger->merge( $profiles{$profile}, $args );
326 # tokenize string, and remove all optional whitespace
328 foreach my $token (split $tokenizer_re, $s) {
329 push @$tokens, $token if (
338 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
342 my ($self, $tokens, $state) = @_;
345 while (1) { # left-associative parsing
349 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
351 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
353 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
355 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
360 my $token = shift @$tokens;
362 # nested expression in ()
363 if ($token eq '(' ) {
364 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
365 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
366 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
368 push @left, [ '-PAREN' => \@right ];
372 elsif ($token =~ $and_or_re) {
375 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
377 # Merge chunks if "logic" matches
378 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
385 elsif ($token eq ',') {
387 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
389 # deal with malformed lists ( foo, bar, , baz )
390 @right = [] unless @right;
392 @right = [ -MISC => [ @right ] ] if @right > 1;
395 @left = [ -LIST => [ [], @right ] ];
397 elsif ($left[0][0] eq '-LIST') {
398 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
404 @left = [ -LIST => [ @left, @right ] ];
408 # binary operator keywords
409 elsif ($token =~ $binary_op_re) {
412 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
414 # A between with a simple LITERAL for a 1st RHS argument needs a
415 # rerun of the search to (hopefully) find the proper AND construct
416 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
417 unshift @$tokens, $right[1][0];
418 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
421 @left = [$op => [ @left, @right ]];
425 elsif ( $token =~ $unary_op_re ) {
427 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
429 push @left, [ $op => \@right ];
432 # expression terminator keywords
433 elsif ( $token =~ $expr_start_re ) {
435 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
437 push @left, [ $op => \@right ];
441 elsif ( $token =~ $placeholder_re) {
442 push @left, [ -PLACEHOLDER => [ $token ] ];
445 # check if the current token is an unknown op-start
446 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
447 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
450 # we're now in "unknown token" land - start eating tokens until
451 # we see something familiar, OR in the case of RHS (binop) stop
452 # after the first token
453 # Also stop processing when we could end up with an unknown func
455 my @lits = [ -LITERAL => [$token] ];
457 unshift @lits, pop @left if @left == 1;
459 unless ( $state == PARSE_RHS ) {
463 $tokens->[0] !~ $all_std_keywords_re
465 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
467 push @lits, [ -LITERAL => [ shift @$tokens ] ];
471 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
476 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
480 while ($#left > $i) {
481 if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
482 splice @left, $i, 2, [ -MISC => [
483 map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
492 return @left if $state == PARSE_RHS;
494 # deal with post-fix operators
497 if ($tokens->[0] =~ $asc_desc_re) {
498 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
505 my ($self, $keyword) = @_;
507 if (my $around = $self->colormap->{lc $keyword}) {
508 $keyword = "$around->[0]$keyword$around->[1]";
522 my ($self, $keyword, $depth) = @_;
525 if (defined $self->indentmap->{lc $keyword}) {
526 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
528 $before = '' if $depth == 0 and defined $starters{lc $keyword};
529 return [$before, ''];
532 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
535 my ($self, $tree) = @_;
536 $tree = $tree->[0] while ref $tree;
538 defined $tree && defined $self->indentmap->{lc $tree};
541 sub fill_in_placeholder {
542 my ($self, $bindargs) = @_;
544 if ($self->fill_in_placeholders) {
545 my $val = shift @{$bindargs} || '';
546 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
547 my ($left, $right) = @{$self->placeholder_surround};
550 $val = qq('$val') if $quoted;
551 return qq($left$val$right)
556 # FIXME - terrible name for a user facing API
558 my ($self, $tree, $bindargs) = @_;
559 $self->_unparse($tree, [@{$bindargs||[]}], 0);
563 my ($self, $tree, $bindargs, $depth) = @_;
565 if (not $tree or not @$tree) {
569 # FIXME - needs a config switch to disable
570 $self->_parenthesis_unroll($tree);
572 my ($op, $args) = @{$tree}[0,1];
574 if (! defined $op or (! ref $op and ! defined $args) ) {
575 require Data::Dumper;
576 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
577 Data::Dumper::Dumper($tree)
582 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
584 elsif ($op eq '-LITERAL') { # literal has different sig
587 elsif ($op eq '-PLACEHOLDER') {
588 return $self->fill_in_placeholder($bindargs);
590 elsif ($op eq '-PAREN') {
591 return sprintf ('( %s )',
592 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
594 ($self->_is_key($args)
595 ? ( $self->newline||'' ) . $self->indent($depth + 1)
600 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
601 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
603 elsif ($op eq '-LIST' ) {
604 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
606 elsif ($op eq '-MISC' ) {
607 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
609 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
611 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
614 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
616 my $rhs = $self->_unparse($args, $bindargs, $depth);
618 return sprintf "$l%s$r", join(
619 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
623 $self->format_keyword($op),
624 (length $rhs ? $rhs : () ),
629 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
630 my @unrollable_ops = (
638 my $unrollable_ops_re = join ' | ', @unrollable_ops;
639 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
641 sub _parenthesis_unroll {
645 return unless (ref $ast and ref $ast->[1]);
652 for my $child (@{$ast->[1]}) {
654 # the current node in this loop is *always* a PAREN
655 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
656 push @children, $child;
660 # unroll nested parenthesis
661 while ( @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
662 $child = $child->[1][0];
666 # if the parent operator explicitly allows it nuke the parenthesis
667 if ( $ast->[0] =~ $unrollable_ops_re ) {
668 push @children, @{$child->[1]};
672 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
676 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
678 $child->[1][0][0] eq $ast->[0]
680 push @children, @{$child->[1][0][1]};
684 # only *ONE* LITERAL or placeholder element
685 # as an AND/OR/NOT argument
687 @{$child->[1]} == 1 && (
688 $child->[1][0][0] eq '-LITERAL'
690 $child->[1][0][0] eq '-PLACEHOLDER'
692 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
695 push @children, @{$child->[1]};
699 # an AND/OR expression with only one binop in the parenthesis
700 # with exactly two grandchildren
701 # the only time when we can *not* unroll this is when both
702 # the parent and the child are mathops (in which case we'll
703 # break precedence) or when the child is BETWEEN (special
708 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
710 $child->[1][0][0] =~ $binary_op_re
712 $child->[1][0][0] ne 'BETWEEN'
714 @{$child->[1][0][1]} == 2
717 $child->[1][0][0] =~ $alphanum_cmp_op_re
719 $ast->[0] =~ $alphanum_cmp_op_re
722 push @children, @{$child->[1]};
726 # a function binds tighter than a mathop - see if our ancestor is a
727 # mathop, and our content is:
728 # a single non-mathop child with a single PAREN grandchild which
729 # would indicate mathop ( nonmathop ( ... ) )
730 # or a single non-mathop with a single LITERAL ( nonmathop foo )
731 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
735 @{$child->[1][0][1]} == 1
737 $ast->[0] =~ $alphanum_cmp_op_re
739 $child->[1][0][0] !~ $alphanum_cmp_op_re
742 $child->[1][0][1][0][0] eq '-PAREN'
744 $child->[1][0][1][0][0] eq '-LITERAL'
746 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
749 push @children, @{$child->[1]};
753 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
754 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
758 @{$child->[1][0][1]} == 1
760 $child->[1][0][0] ne 'NOT'
762 ref $child->[1][0][1][0] eq 'ARRAY'
764 $child->[1][0][1][0][0] eq '-PAREN'
766 push @children, @{$child->[1]};
771 # otherwise no more mucking for this pass
773 push @children, $child;
777 $ast->[1] = \@children;
782 sub _strip_asc_from_order_by {
783 my ($self, $ast) = @_;
788 $ast->[0] ne 'ORDER BY'
794 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
795 $to_replace = [ $ast->[1][0] ];
797 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
798 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
801 @$_ = @{$_->[1][0]} for @$to_replace;
806 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
814 SQL::Abstract::Tree - Represent SQL as an AST
818 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
820 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
830 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
833 profile => 'console', # predefined profile to use (default: 'none')
834 fill_in_placeholders => 1, # true for placeholder population
835 placeholder_surround => # The strings that will be wrapped around
836 [GREEN, RESET], # populated placeholders if the above is set
837 indent_string => ' ', # the string used when indenting
838 indent_amount => 2, # how many of above string to use for a single
840 newline => "\n", # string for newline
842 select => [RED, RESET], # a pair of strings defining what to surround
843 # the keyword with for colorization
847 select => 0, # A zero means that the keyword will start on
849 from => 1, # Any other positive integer means that after
850 on => 2, # said newline it will get that many indents
855 Returns a new SQL::Abstract::Tree object. All arguments are optional.
859 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
860 and C<html>. Typically a user will probably just use C<console> or
861 C<console_monochrome>, but if something about a profile bothers you, merely
862 use the profile and override the parts that you don't like.
866 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
868 Takes C<$sql> and C<\@bindargs>.
870 Returns a formatting string based on the string passed in
874 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
876 Returns a "tree" representing passed in SQL. Please do not depend on the
877 structure of the returned tree. It may be stable at some point, but not yet.
881 $sqlat->unparse($tree_structure, \@bindargs)
883 Transform "tree" into SQL, applying various transforms on the way.
885 =head2 format_keyword
887 $sqlat->format_keyword('SELECT')
889 Currently this just takes a keyword and puts the C<colormap> stuff around it.
890 Later on it may do more and allow for coderef based transforms.
894 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
896 Returns whitespace to be inserted around a keyword.
898 =head2 fill_in_placeholder
900 my $value = $sqlat->fill_in_placeholder(\@bindargs)
902 Removes last arg from passed arrayref and returns it, surrounded with
903 the values in placeholder_surround, and then surrounded with single quotes.
907 Returns as many indent strings as indent amounts times the first argument.
915 =head2 fill_in_placeholders
935 =head2 placeholder_surround