1 package SQL::Abstract::Tree;
7 use Sub::Quote 'quote_sub';
9 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
10 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
12 my $quote_left = qr/[\`\'\"\[]/;
13 my $quote_right = qr/[\`\'\"\]]/;
15 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
17 # These SQL keywords always signal end of the current expression (except inside
18 # of a parenthesized subexpression).
19 # Format: A list of strings that will be compiled to extended syntax ie.
20 # /.../x) regexes, without capturing parentheses. They will be automatically
21 # anchored to op boundaries (excluding quotes) to match the whole token.
22 my @expression_start_keywords = (
31 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
32 (?: (?: CROSS | INNER | OUTER ) \s+ )?
38 '(?: DEFAULT \s+ )? VALUES',
53 'ROLLBACK \s+ TO \s+ SAVEPOINT',
56 'RELEASE \s+ SAVEPOINT',
60 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
61 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
63 # These are binary operator keywords always a single LHS and RHS
64 # * AND/OR are handled separately as they are N-ary
65 # * so is NOT as being unary
66 # * BETWEEN without parentheses around the ANDed arguments (which
67 # makes it a non-binary op) is detected and accommodated in
69 # * AS is not really an operator but is handled here as it's also LHS/RHS
71 # this will be included in the $binary_op_re, the distinction is interesting during
72 # testing as one is tighter than the other, plus alphanum cmp ops have different
73 # look ahead/behind (e.g. "x"="y" )
74 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
75 my $alphanum_cmp_op_re = join ("\n\t|\n", map
76 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
77 @alphanum_cmp_op_keywords
79 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
81 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN [RI]?LIKE REGEXP/) . ')';
82 $binary_op_re = join "\n\t|\n",
83 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
85 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
87 $binary_op_re = qr/$binary_op_re/x;
89 my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix;
91 my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re;
92 $unary_op_re = join "\n\t|\n",
93 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
95 $unary_op_re = qr/$unary_op_re/x;
97 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
98 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
100 my $tokenizer_re = join("\n\t|\n",
106 $op_look_behind . ' \* ' . $op_look_ahead,
107 (map { quotemeta $_ } qw/, ( )/),
111 # this one *is* capturing for the split below
112 # splits on whitespace if all else fails
113 # has to happen before the composing qr's are anchored (below)
114 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
116 # Parser states for _recurse_parse()
117 use constant PARSE_TOP_LEVEL => 0;
118 use constant PARSE_IN_EXPR => 1;
119 use constant PARSE_IN_PARENS => 2;
120 use constant PARSE_IN_FUNC => 3;
121 use constant PARSE_RHS => 4;
122 use constant PARSE_LIST_ELT => 5;
124 my $expr_term_re = qr/$expr_start_re | \)/x;
125 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
126 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
128 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
141 $all_std_keywords_re,
143 $_ = qr/ \A $_ \z /x;
146 # what can be bunched together under one MISC in an AST
147 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
173 newline indent_string indent_amount fill_in_placeholders placeholder_surround
176 has [qw( indentmap colormap )] => ( is => 'ro', default => quote_sub('{}') );
178 # class global is in fact desired
183 my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_};
185 if (my $p = delete $args->{profile}) {
187 if ($p eq 'console') {
189 fill_in_placeholders => 1,
190 placeholder_surround => ['?/', ''],
191 indent_string => ' ',
195 indentmap => \%indents,
197 ! ( eval { require Term::ANSIColor } ) ? () : do {
198 my $c = \&Term::ANSIColor::color;
200 my $red = [$c->('red') , $c->('reset')];
201 my $cyan = [$c->('cyan') , $c->('reset')];
202 my $green = [$c->('green') , $c->('reset')];
203 my $yellow = [$c->('yellow') , $c->('reset')];
204 my $blue = [$c->('blue') , $c->('reset')];
205 my $magenta = [$c->('magenta'), $c->('reset')];
206 my $b_o_w = [$c->('black on_white'), $c->('reset')];
208 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
210 'begin work' => $b_o_w,
214 'rollback to savepoint' => $b_o_w,
215 'release savepoint' => $b_o_w,
218 'insert into' => $red,
220 'delete from' => $red,
229 'left join' => $magenta,
232 'group by' => $yellow,
234 'order by' => $yellow,
245 elsif ($p eq 'console_monochrome') {
247 fill_in_placeholders => 1,
248 placeholder_surround => ['?/', ''],
249 indent_string => ' ',
252 indentmap => \%indents,
255 elsif ($p eq 'html') {
257 fill_in_placeholders => 1,
258 placeholder_surround => ['<span class="placeholder">', '</span>'],
259 indent_string => ' ',
261 newline => "<br />\n",
263 (my $class = $_) =~ s/\s+/-/g;
264 ( $_ => [ qq|<span class="$class">|, '</span>' ] )
267 qw(commit rollback savepoint),
268 'begin work', 'rollback to savepoint', 'release savepoint',
270 indentmap => \%indents,
273 elsif ($p eq 'none') {
277 croak "No such profile '$p'";
280 # see if we got any duplicates and merge if needed
281 if (scalar grep { exists $args->{$_} } keys %extra_args) {
283 $args = ($merger ||= do {
285 my $m = Hash::Merge->new;
287 $m->specify_behavior({
289 SCALAR => sub { $_[1] },
290 ARRAY => sub { [ $_[0], @{$_[1]} ] },
291 HASH => sub { $_[1] },
294 SCALAR => sub { $_[1] },
295 ARRAY => sub { $_[1] },
296 HASH => sub { $_[1] },
299 SCALAR => sub { $_[1] },
300 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
301 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
303 }, 'SQLA::Tree Behavior' );
306 })->merge(\%extra_args, $args );
310 $args = { %extra_args, %$args };
320 return [] unless defined $s;
322 # tokenize string, and remove all optional whitespace
324 foreach my $token (split $tokenizer_re, $s) {
325 push @$tokens, $token if (
334 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
338 my ($self, $tokens, $state) = @_;
341 while (1) { # left-associative parsing
345 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
347 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
349 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
351 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
356 my $token = shift @$tokens;
358 # nested expression in ()
359 if ($token eq '(' ) {
360 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
361 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
362 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
364 push @left, [ '-PAREN' => \@right ];
368 elsif ($token =~ $and_or_re) {
371 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
373 # Merge chunks if "logic" matches
374 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
381 elsif ($token eq ',') {
383 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
385 # deal with malformed lists ( foo, bar, , baz )
386 @right = [] unless @right;
388 @right = [ -MISC => [ @right ] ] if @right > 1;
391 @left = [ -LIST => [ [], @right ] ];
393 elsif ($left[0][0] eq '-LIST') {
394 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
400 @left = [ -LIST => [ @left, @right ] ];
404 # binary operator keywords
405 elsif ($token =~ $binary_op_re) {
408 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
410 # A between with a simple LITERAL for a 1st RHS argument needs a
411 # rerun of the search to (hopefully) find the proper AND construct
412 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
413 unshift @$tokens, $right[1][0];
414 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
417 push @left, [$op => [ (@left ? pop @left : ''), @right ]];
421 elsif ($token =~ $unary_op_re) {
424 # normalize RNO explicitly
425 $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_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 my $parent_op = $ast->[0];
662 # unroll nested parenthesis
663 while ( $parent_op ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
664 $child = $child->[1][0];
668 # set to CHILD in the case of PARENT ( CHILD )
669 # but NOT in the case of PARENT( CHILD1, CHILD2 )
670 my $single_child_op = (@{$child->[1]} == 1) ? $child->[1][0][0] : '';
672 my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef;
674 my $single_grandchild_op
675 = ( $child_op_argc||0 == 1 and ref $child->[1][0][1][0] eq 'ARRAY' )
676 ? $child->[1][0][1][0][0]
680 # if the parent operator explicitly allows it AND the child isn't a subselect
681 # nuke the parenthesis
682 if ($parent_op =~ $unrollable_ops_re and $single_child_op ne 'SELECT') {
683 push @children, @{$child->[1]};
687 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
689 $single_child_op eq $parent_op
691 ( $parent_op eq 'AND' or $parent_op eq 'OR')
693 push @children, @{$child->[1][0][1]};
697 # only *ONE* LITERAL or placeholder element
698 # as an AND/OR/NOT argument
700 ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' )
702 ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' )
704 push @children, @{$child->[1]};
708 # an AND/OR expression with only one binop in the parenthesis
709 # with exactly two grandchildren
710 # the only time when we can *not* unroll this is when both
711 # the parent and the child are mathops (in which case we'll
712 # break precedence) or when the child is BETWEEN (special
715 ($parent_op eq 'AND' or $parent_op eq 'OR')
717 $single_child_op =~ $binary_op_re
719 $single_child_op ne 'BETWEEN'
724 $single_child_op =~ $alphanum_cmp_op_re
726 $parent_op =~ $alphanum_cmp_op_re
729 push @children, @{$child->[1]};
733 # a function binds tighter than a mathop - see if our ancestor is a
734 # mathop, and our content is:
735 # a single non-mathop child with a single PAREN grandchild which
736 # would indicate mathop ( nonmathop ( ... ) )
737 # or a single non-mathop with a single LITERAL ( nonmathop foo )
738 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
742 $parent_op =~ $alphanum_cmp_op_re
744 $single_child_op !~ $alphanum_cmp_op_re
749 $single_grandchild_op eq '-PAREN'
751 $single_grandchild_op eq '-LITERAL'
753 $single_grandchild_op eq '-PLACEHOLDER'
756 push @children, @{$child->[1]};
760 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
761 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
762 # and except for the case of RNO, where the double are explicit syntax
764 $parent_op ne 'ROW_NUMBER() OVER'
768 $single_child_op ne 'NOT'
772 $single_grandchild_op eq '-PAREN'
774 push @children, @{$child->[1]};
779 # otherwise no more mucking for this pass
781 push @children, $child;
785 $ast->[1] = \@children;
790 sub _strip_asc_from_order_by {
791 my ($self, $ast) = @_;
796 $ast->[0] ne 'ORDER BY'
802 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
803 $to_replace = [ $ast->[1][0] ];
805 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
806 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
809 @$_ = @{$_->[1][0]} for @$to_replace;
814 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
822 SQL::Abstract::Tree - Represent SQL as an AST
826 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
828 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
838 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
841 profile => 'console', # predefined profile to use (default: 'none')
842 fill_in_placeholders => 1, # true for placeholder population
843 placeholder_surround => # The strings that will be wrapped around
844 [GREEN, RESET], # populated placeholders if the above is set
845 indent_string => ' ', # the string used when indenting
846 indent_amount => 2, # how many of above string to use for a single
848 newline => "\n", # string for newline
850 select => [RED, RESET], # a pair of strings defining what to surround
851 # the keyword with for colorization
855 select => 0, # A zero means that the keyword will start on
857 from => 1, # Any other positive integer means that after
858 on => 2, # said newline it will get that many indents
863 Returns a new SQL::Abstract::Tree object. All arguments are optional.
867 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
868 and C<html>. Typically a user will probably just use C<console> or
869 C<console_monochrome>, but if something about a profile bothers you, merely
870 use the profile and override the parts that you don't like.
874 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
876 Takes C<$sql> and C<\@bindargs>.
878 Returns a formatting string based on the string passed in
882 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
884 Returns a "tree" representing passed in SQL. Please do not depend on the
885 structure of the returned tree. It may be stable at some point, but not yet.
889 $sqlat->unparse($tree_structure, \@bindargs)
891 Transform "tree" into SQL, applying various transforms on the way.
893 =head2 format_keyword
895 $sqlat->format_keyword('SELECT')
897 Currently this just takes a keyword and puts the C<colormap> stuff around it.
898 Later on it may do more and allow for coderef based transforms.
902 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
904 Returns whitespace to be inserted around a keyword.
906 =head2 fill_in_placeholder
908 my $value = $sqlat->fill_in_placeholder(\@bindargs)
910 Removes last arg from passed arrayref and returns it, surrounded with
911 the values in placeholder_surround, and then surrounded with single quotes.
915 Returns as many indent strings as indent amounts times the first argument.
923 =head2 fill_in_placeholders
943 =head2 placeholder_surround