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',
81 'ROLLBACK \s+ TO \s+ SAVEPOINT',
84 'RELEASE \s+ SAVEPOINT',
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 $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix;
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",
123 $unary_op_re = qr/$unary_op_re/x;
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;
128 my $tokenizer_re = join("\n\t|\n",
134 $op_look_behind . ' \* ' . $op_look_ahead,
135 (map { quotemeta $_ } qw/, ( )/),
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;
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;
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;
156 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
169 $all_std_keywords_re,
171 $_ = qr/ \A $_ \z /x;
174 # what can be bunched together under one MISC in an AST
175 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
201 fill_in_placeholders => 1,
202 placeholder_surround => ['?/', ''],
203 indent_string => ' ',
207 indentmap => \%indents,
209 eval { require Term::ANSIColor }
211 my $c = \&Term::ANSIColor::color;
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')];
221 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
223 'begin work' => $b_o_w,
227 'rollback to savepoint' => $b_o_w,
228 'release savepoint' => $b_o_w,
231 'insert into' => $red,
233 'delete from' => $red,
242 'left join' => $magenta,
245 'group by' => $yellow,
247 'order by' => $yellow,
257 console_monochrome => {
258 fill_in_placeholders => 1,
259 placeholder_surround => ['?/', ''],
260 indent_string => ' ',
264 indentmap => \%indents,
267 fill_in_placeholders => 1,
268 placeholder_surround => ['<span class="placeholder">', '</span>'],
269 indent_string => ' ',
271 newline => "<br />\n",
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>'],
278 set => ['<span class="set">', '</span>'],
279 from => ['<span class="from">' , '</span>'],
281 where => ['<span class="where">' , '</span>'],
282 values => ['<span class="values">', '</span>'],
284 join => ['<span class="join">' , '</span>'],
285 'left join' => ['<span class="left-join">','</span>'],
286 on => ['<span class="on">' , '</span>'],
288 'group by' => ['<span class="group-by">', '</span>'],
289 having => ['<span class="having">', '</span>'],
290 'order by' => ['<span class="order-by">', '</span>'],
292 skip => ['<span class="skip">', '</span>'],
293 first => ['<span class="first">', '</span>'],
294 limit => ['<span class="limit">', '</span>'],
295 offset => ['<span class="offset">', '</span>'],
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>'],
304 indentmap => \%indents,
314 my $args = shift || {};
316 my $profile = delete $args->{profile} || 'none';
318 die "No such profile '$profile'!" unless exists $profiles{$profile};
320 my $data = $merger->merge( $profiles{$profile}, $args );
328 return [] unless defined $s;
330 # tokenize string, and remove all optional whitespace
332 foreach my $token (split $tokenizer_re, $s) {
333 push @$tokens, $token if (
342 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
346 my ($self, $tokens, $state) = @_;
349 while (1) { # left-associative parsing
353 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
355 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
357 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
359 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
364 my $token = shift @$tokens;
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);
372 push @left, [ '-PAREN' => \@right ];
376 elsif ($token =~ $and_or_re) {
379 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
381 # Merge chunks if "logic" matches
382 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
389 elsif ($token eq ',') {
391 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
393 # deal with malformed lists ( foo, bar, , baz )
394 @right = [] unless @right;
396 @right = [ -MISC => [ @right ] ] if @right > 1;
399 @left = [ -LIST => [ [], @right ] ];
401 elsif ($left[0][0] eq '-LIST') {
402 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
408 @left = [ -LIST => [ @left, @right ] ];
412 # binary operator keywords
413 elsif ($token =~ $binary_op_re) {
416 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
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);
425 push @left, [$op => [ (@left ? pop @left : ''), @right ]];
429 elsif ( $token =~ $unary_op_re ) {
432 # normalize RNO explicitly
433 $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/;
435 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
437 push @left, [ $op => \@right ];
440 # expression terminator keywords
441 elsif ( $token =~ $expr_start_re ) {
443 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
445 push @left, [ $op => \@right ];
449 elsif ( $token =~ $placeholder_re) {
450 push @left, [ -PLACEHOLDER => [ $token ] ];
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) ] ];
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
463 my @lits = [ -LITERAL => [$token] ];
465 unshift @lits, pop @left if @left == 1;
467 unless ( $state == PARSE_RHS ) {
471 $tokens->[0] !~ $all_std_keywords_re
473 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
475 push @lits, [ -LITERAL => [ shift @$tokens ] ];
479 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
484 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
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])
500 return @left if $state == PARSE_RHS;
502 # deal with post-fix operators
505 if ($tokens->[0] =~ $asc_desc_re) {
506 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
513 my ($self, $keyword) = @_;
515 if (my $around = $self->colormap->{lc $keyword}) {
516 $keyword = "$around->[0]$keyword$around->[1]";
530 my ($self, $keyword, $depth) = @_;
533 if (defined $self->indentmap->{lc $keyword}) {
534 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
536 $before = '' if $depth == 0 and defined $starters{lc $keyword};
537 return [$before, ''];
540 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
543 my ($self, $tree) = @_;
544 $tree = $tree->[0] while ref $tree;
546 defined $tree && defined $self->indentmap->{lc $tree};
549 sub fill_in_placeholder {
550 my ($self, $bindargs) = @_;
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};
558 $val = qq('$val') if $quoted;
559 return qq($left$val$right)
564 # FIXME - terrible name for a user facing API
566 my ($self, $tree, $bindargs) = @_;
567 $self->_unparse($tree, [@{$bindargs||[]}], 0);
571 my ($self, $tree, $bindargs, $depth) = @_;
573 if (not $tree or not @$tree) {
577 # FIXME - needs a config switch to disable
578 $self->_parenthesis_unroll($tree);
580 my ($op, $args) = @{$tree}[0,1];
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)
590 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
592 elsif ($op eq '-LITERAL') { # literal has different sig
595 elsif ($op eq '-PLACEHOLDER') {
596 return $self->fill_in_placeholder($bindargs);
598 elsif ($op eq '-PAREN') {
599 return sprintf ('( %s )',
600 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
602 ($self->_is_key($args)
603 ? ( $self->newline||'' ) . $self->indent($depth + 1)
608 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
609 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
611 elsif ($op eq '-LIST' ) {
612 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
614 elsif ($op eq '-MISC' ) {
615 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
617 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
619 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
622 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
624 my $rhs = $self->_unparse($args, $bindargs, $depth);
626 return sprintf "$l%s$r", join(
627 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
631 $self->format_keyword($op),
632 (length $rhs ? $rhs : () ),
637 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
638 my @unrollable_ops = (
646 my $unrollable_ops_re = join ' | ', @unrollable_ops;
647 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
649 sub _parenthesis_unroll {
653 return unless (ref $ast and ref $ast->[1]);
660 for my $child (@{$ast->[1]}) {
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;
668 my $parent_op = $ast->[0];
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];
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] : '';
680 my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef;
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]
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]};
695 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
697 $single_child_op eq $parent_op
699 ( $parent_op eq 'AND' or $parent_op eq 'OR')
701 push @children, @{$child->[1][0][1]};
705 # only *ONE* LITERAL or placeholder element
706 # as an AND/OR/NOT argument
708 ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' )
710 ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' )
712 push @children, @{$child->[1]};
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
723 ($parent_op eq 'AND' or $parent_op eq 'OR')
725 $single_child_op =~ $binary_op_re
727 $single_child_op ne 'BETWEEN'
732 $single_child_op =~ $alphanum_cmp_op_re
734 $parent_op =~ $alphanum_cmp_op_re
737 push @children, @{$child->[1]};
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 ? )
750 $parent_op =~ $alphanum_cmp_op_re
752 $single_child_op !~ $alphanum_cmp_op_re
757 $single_grandchild_op eq '-PAREN'
759 $single_grandchild_op eq '-LITERAL'
761 $single_grandchild_op eq '-PLACEHOLDER'
764 push @children, @{$child->[1]};
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
772 $parent_op ne 'ROW_NUMBER() OVER'
776 $single_child_op ne 'NOT'
780 $single_grandchild_op eq '-PAREN'
782 push @children, @{$child->[1]};
787 # otherwise no more mucking for this pass
789 push @children, $child;
793 $ast->[1] = \@children;
798 sub _strip_asc_from_order_by {
799 my ($self, $ast) = @_;
804 $ast->[0] ne 'ORDER BY'
810 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
811 $to_replace = [ $ast->[1][0] ];
813 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
814 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
817 @$_ = @{$_->[1][0]} for @$to_replace;
822 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
830 SQL::Abstract::Tree - Represent SQL as an AST
834 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
836 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
846 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
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
856 newline => "\n", # string for newline
858 select => [RED, RESET], # a pair of strings defining what to surround
859 # the keyword with for colorization
863 select => 0, # A zero means that the keyword will start on
865 from => 1, # Any other positive integer means that after
866 on => 2, # said newline it will get that many indents
871 Returns a new SQL::Abstract::Tree object. All arguments are optional.
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.
882 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
884 Takes C<$sql> and C<\@bindargs>.
886 Returns a formatting string based on the string passed in
890 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
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.
897 $sqlat->unparse($tree_structure, \@bindargs)
899 Transform "tree" into SQL, applying various transforms on the way.
901 =head2 format_keyword
903 $sqlat->format_keyword('SELECT')
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.
910 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
912 Returns whitespace to be inserted around a keyword.
914 =head2 fill_in_placeholder
916 my $value = $sqlat->fill_in_placeholder(\@bindargs)
918 Removes last arg from passed arrayref and returns it, surrounded with
919 the values in placeholder_surround, and then surrounded with single quotes.
923 Returns as many indent strings as indent amounts times the first argument.
931 =head2 fill_in_placeholders
951 =head2 placeholder_surround