1 package SQL::Abstract::Tree;
3 # DO NOT edit away without talking to riba first, he will just put it back
4 # BEGIN pre-Moo2 import block
7 my $initial_fatal_bits = (${^WARNING_BITS}||'') & $warnings::DeadBits{all};
8 local $ENV{PERL_STRICTURES_EXTRA} = 0;
9 require Moo; Moo->import;
10 require Sub::Quote; Sub::Quote->import('quote_sub');
11 ${^WARNING_BITS} &= ( $initial_fatal_bits | ~ $warnings::DeadBits{all} );
13 # END pre-Moo2 import block
21 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
22 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
24 my $quote_left = qr/[\`\'\"\[]/;
25 my $quote_right = qr/[\`\'\"\]]/;
27 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
29 # These SQL keywords always signal end of the current expression (except inside
30 # of a parenthesized subexpression).
31 # Format: A list of strings that will be compiled to extended syntax ie.
32 # /.../x) regexes, without capturing parentheses. They will be automatically
33 # anchored to op boundaries (excluding quotes) to match the whole token.
34 my @expression_start_keywords = (
43 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
44 (?: (?: CROSS | INNER | OUTER ) \s+ )?
50 '(?: DEFAULT \s+ )? VALUES',
65 'ROLLBACK \s+ TO \s+ SAVEPOINT',
68 'RELEASE \s+ SAVEPOINT',
72 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
73 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
75 # These are binary operator keywords always a single LHS and RHS
76 # * AND/OR are handled separately as they are N-ary
77 # * so is NOT as being unary
78 # * BETWEEN without parentheses around the ANDed arguments (which
79 # makes it a non-binary op) is detected and accommodated in
81 # * AS is not really an operator but is handled here as it's also LHS/RHS
83 # this will be included in the $binary_op_re, the distinction is interesting during
84 # testing as one is tighter than the other, plus alphanum cmp ops have different
85 # look ahead/behind (e.g. "x"="y" )
86 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
87 my $alphanum_cmp_op_re = join ("\n\t|\n", map
88 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
89 @alphanum_cmp_op_keywords
91 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
93 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
94 $binary_op_re = join "\n\t|\n",
95 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
97 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
99 $binary_op_re = qr/$binary_op_re/x;
101 my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix;
103 my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re;
104 $unary_op_re = join "\n\t|\n",
105 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
107 $unary_op_re = qr/$unary_op_re/x;
109 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
110 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
112 my $tokenizer_re = join("\n\t|\n",
118 $op_look_behind . ' \* ' . $op_look_ahead,
119 (map { quotemeta $_ } qw/, ( )/),
123 # this one *is* capturing for the split below
124 # splits on whitespace if all else fails
125 # has to happen before the composing qr's are anchored (below)
126 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
128 # Parser states for _recurse_parse()
129 use constant PARSE_TOP_LEVEL => 0;
130 use constant PARSE_IN_EXPR => 1;
131 use constant PARSE_IN_PARENS => 2;
132 use constant PARSE_IN_FUNC => 3;
133 use constant PARSE_RHS => 4;
134 use constant PARSE_LIST_ELT => 5;
136 my $expr_term_re = qr/$expr_start_re | \)/x;
137 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
138 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
140 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
153 $all_std_keywords_re,
155 $_ = qr/ \A $_ \z /x;
158 # what can be bunched together under one MISC in an AST
159 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
185 newline indent_string indent_amount fill_in_placeholders placeholder_surround
188 has [qw( indentmap colormap )] => ( is => 'ro', default => quote_sub('{}') );
190 # class global is in fact desired
195 my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_};
197 if (my $p = delete $args->{profile}) {
199 if ($p eq 'console') {
201 fill_in_placeholders => 1,
202 placeholder_surround => ['?/', ''],
203 indent_string => ' ',
207 indentmap => \%indents,
209 ! ( eval { require Term::ANSIColor } ) ? () : do {
210 my $c = \&Term::ANSIColor::color;
212 my $red = [$c->('red') , $c->('reset')];
213 my $cyan = [$c->('cyan') , $c->('reset')];
214 my $green = [$c->('green') , $c->('reset')];
215 my $yellow = [$c->('yellow') , $c->('reset')];
216 my $blue = [$c->('blue') , $c->('reset')];
217 my $magenta = [$c->('magenta'), $c->('reset')];
218 my $b_o_w = [$c->('black on_white'), $c->('reset')];
220 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
222 'begin work' => $b_o_w,
226 'rollback to savepoint' => $b_o_w,
227 'release savepoint' => $b_o_w,
230 'insert into' => $red,
232 'delete from' => $red,
241 'left join' => $magenta,
244 'group by' => $yellow,
246 'order by' => $yellow,
257 elsif ($p eq 'console_monochrome') {
259 fill_in_placeholders => 1,
260 placeholder_surround => ['?/', ''],
261 indent_string => ' ',
264 indentmap => \%indents,
267 elsif ($p eq 'html') {
269 fill_in_placeholders => 1,
270 placeholder_surround => ['<span class="placeholder">', '</span>'],
271 indent_string => ' ',
273 newline => "<br />\n",
275 (my $class = $_) =~ s/\s+/-/g;
276 ( $_ => [ qq|<span class="$class">|, '</span>' ] )
279 qw(commit rollback savepoint),
280 'begin work', 'rollback to savepoint', 'release savepoint',
282 indentmap => \%indents,
285 elsif ($p eq 'none') {
289 croak "No such profile '$p'";
292 # see if we got any duplicates and merge if needed
293 if (scalar grep { exists $args->{$_} } keys %extra_args) {
295 $args = ($merger ||= do {
297 my $m = Hash::Merge->new;
299 $m->specify_behavior({
301 SCALAR => sub { $_[1] },
302 ARRAY => sub { [ $_[0], @{$_[1]} ] },
303 HASH => sub { $_[1] },
306 SCALAR => sub { $_[1] },
307 ARRAY => sub { $_[1] },
308 HASH => sub { $_[1] },
311 SCALAR => sub { $_[1] },
312 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
313 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
315 }, 'SQLA::Tree Behavior' );
318 })->merge(\%extra_args, $args );
322 $args = { %extra_args, %$args };
332 return [] unless defined $s;
334 # tokenize string, and remove all optional whitespace
336 foreach my $token (split $tokenizer_re, $s) {
337 push @$tokens, $token if (
346 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
350 my ($self, $tokens, $state) = @_;
353 while (1) { # left-associative parsing
357 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
359 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
361 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
363 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
368 my $token = shift @$tokens;
370 # nested expression in ()
371 if ($token eq '(' ) {
372 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
373 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
374 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
376 push @left, [ '-PAREN' => \@right ];
380 elsif ($token =~ $and_or_re) {
383 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
385 # Merge chunks if "logic" matches
386 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
393 elsif ($token eq ',') {
395 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
397 # deal with malformed lists ( foo, bar, , baz )
398 @right = [] unless @right;
400 @right = [ -MISC => [ @right ] ] if @right > 1;
403 @left = [ -LIST => [ [], @right ] ];
405 elsif ($left[0][0] eq '-LIST') {
406 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
412 @left = [ -LIST => [ @left, @right ] ];
416 # binary operator keywords
417 elsif ($token =~ $binary_op_re) {
420 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
422 # A between with a simple LITERAL for a 1st RHS argument needs a
423 # rerun of the search to (hopefully) find the proper AND construct
424 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
425 unshift @$tokens, $right[1][0];
426 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
429 push @left, [$op => [ (@left ? pop @left : ''), @right ]];
433 elsif ( $token =~ $unary_op_re ) {
436 # normalize RNO explicitly
437 $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/;
439 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
441 push @left, [ $op => \@right ];
444 # expression terminator keywords
445 elsif ( $token =~ $expr_start_re ) {
447 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
449 push @left, [ $op => \@right ];
453 elsif ( $token =~ $placeholder_re) {
454 push @left, [ -PLACEHOLDER => [ $token ] ];
457 # check if the current token is an unknown op-start
458 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
459 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
462 # we're now in "unknown token" land - start eating tokens until
463 # we see something familiar, OR in the case of RHS (binop) stop
464 # after the first token
465 # Also stop processing when we could end up with an unknown func
467 my @lits = [ -LITERAL => [$token] ];
469 unshift @lits, pop @left if @left == 1;
471 unless ( $state == PARSE_RHS ) {
475 $tokens->[0] !~ $all_std_keywords_re
477 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
479 push @lits, [ -LITERAL => [ shift @$tokens ] ];
483 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
488 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
492 while ($#left > $i) {
493 if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
494 splice @left, $i, 2, [ -MISC => [
495 map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
504 return @left if $state == PARSE_RHS;
506 # deal with post-fix operators
509 if ($tokens->[0] =~ $asc_desc_re) {
510 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
517 my ($self, $keyword) = @_;
519 if (my $around = $self->colormap->{lc $keyword}) {
520 $keyword = "$around->[0]$keyword$around->[1]";
534 my ($self, $keyword, $depth) = @_;
537 if (defined $self->indentmap->{lc $keyword}) {
538 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
540 $before = '' if $depth == 0 and defined $starters{lc $keyword};
541 return [$before, ''];
544 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
547 my ($self, $tree) = @_;
548 $tree = $tree->[0] while ref $tree;
550 defined $tree && defined $self->indentmap->{lc $tree};
553 sub fill_in_placeholder {
554 my ($self, $bindargs) = @_;
556 if ($self->fill_in_placeholders) {
557 my $val = shift @{$bindargs} || '';
558 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
559 my ($left, $right) = @{$self->placeholder_surround};
562 $val = qq('$val') if $quoted;
563 return qq($left$val$right)
568 # FIXME - terrible name for a user facing API
570 my ($self, $tree, $bindargs) = @_;
571 $self->_unparse($tree, [@{$bindargs||[]}], 0);
575 my ($self, $tree, $bindargs, $depth) = @_;
577 if (not $tree or not @$tree) {
581 # FIXME - needs a config switch to disable
582 $self->_parenthesis_unroll($tree);
584 my ($op, $args) = @{$tree}[0,1];
586 if (! defined $op or (! ref $op and ! defined $args) ) {
587 require Data::Dumper;
588 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
589 Data::Dumper::Dumper($tree)
594 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
596 elsif ($op eq '-LITERAL') { # literal has different sig
599 elsif ($op eq '-PLACEHOLDER') {
600 return $self->fill_in_placeholder($bindargs);
602 elsif ($op eq '-PAREN') {
603 return sprintf ('( %s )',
604 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
606 ($self->_is_key($args)
607 ? ( $self->newline||'' ) . $self->indent($depth + 1)
612 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
613 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
615 elsif ($op eq '-LIST' ) {
616 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
618 elsif ($op eq '-MISC' ) {
619 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
621 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
623 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
626 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
628 my $rhs = $self->_unparse($args, $bindargs, $depth);
630 return sprintf "$l%s$r", join(
631 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
635 $self->format_keyword($op),
636 (length $rhs ? $rhs : () ),
641 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
642 my @unrollable_ops = (
650 my $unrollable_ops_re = join ' | ', @unrollable_ops;
651 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
653 sub _parenthesis_unroll {
657 return unless (ref $ast and ref $ast->[1]);
664 for my $child (@{$ast->[1]}) {
666 # the current node in this loop is *always* a PAREN
667 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
668 push @children, $child;
672 my $parent_op = $ast->[0];
674 # unroll nested parenthesis
675 while ( $parent_op ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
676 $child = $child->[1][0];
680 # set to CHILD in the case of PARENT ( CHILD )
681 # but NOT in the case of PARENT( CHILD1, CHILD2 )
682 my $single_child_op = (@{$child->[1]} == 1) ? $child->[1][0][0] : '';
684 my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef;
686 my $single_grandchild_op
687 = ( $child_op_argc||0 == 1 and ref $child->[1][0][1][0] eq 'ARRAY' )
688 ? $child->[1][0][1][0][0]
692 # if the parent operator explicitly allows it AND the child isn't a subselect
693 # nuke the parenthesis
694 if ($parent_op =~ $unrollable_ops_re and $single_child_op ne 'SELECT') {
695 push @children, @{$child->[1]};
699 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
701 $single_child_op eq $parent_op
703 ( $parent_op eq 'AND' or $parent_op eq 'OR')
705 push @children, @{$child->[1][0][1]};
709 # only *ONE* LITERAL or placeholder element
710 # as an AND/OR/NOT argument
712 ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' )
714 ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' )
716 push @children, @{$child->[1]};
720 # an AND/OR expression with only one binop in the parenthesis
721 # with exactly two grandchildren
722 # the only time when we can *not* unroll this is when both
723 # the parent and the child are mathops (in which case we'll
724 # break precedence) or when the child is BETWEEN (special
727 ($parent_op eq 'AND' or $parent_op eq 'OR')
729 $single_child_op =~ $binary_op_re
731 $single_child_op ne 'BETWEEN'
736 $single_child_op =~ $alphanum_cmp_op_re
738 $parent_op =~ $alphanum_cmp_op_re
741 push @children, @{$child->[1]};
745 # a function binds tighter than a mathop - see if our ancestor is a
746 # mathop, and our content is:
747 # a single non-mathop child with a single PAREN grandchild which
748 # would indicate mathop ( nonmathop ( ... ) )
749 # or a single non-mathop with a single LITERAL ( nonmathop foo )
750 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
754 $parent_op =~ $alphanum_cmp_op_re
756 $single_child_op !~ $alphanum_cmp_op_re
761 $single_grandchild_op eq '-PAREN'
763 $single_grandchild_op eq '-LITERAL'
765 $single_grandchild_op eq '-PLACEHOLDER'
768 push @children, @{$child->[1]};
772 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
773 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
774 # and except for the case of RNO, where the double are explicit syntax
776 $parent_op ne 'ROW_NUMBER() OVER'
780 $single_child_op ne 'NOT'
784 $single_grandchild_op eq '-PAREN'
786 push @children, @{$child->[1]};
791 # otherwise no more mucking for this pass
793 push @children, $child;
797 $ast->[1] = \@children;
802 sub _strip_asc_from_order_by {
803 my ($self, $ast) = @_;
808 $ast->[0] ne 'ORDER BY'
814 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
815 $to_replace = [ $ast->[1][0] ];
817 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
818 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
821 @$_ = @{$_->[1][0]} for @$to_replace;
826 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
834 SQL::Abstract::Tree - Represent SQL as an AST
838 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
840 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
850 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
853 profile => 'console', # predefined profile to use (default: 'none')
854 fill_in_placeholders => 1, # true for placeholder population
855 placeholder_surround => # The strings that will be wrapped around
856 [GREEN, RESET], # populated placeholders if the above is set
857 indent_string => ' ', # the string used when indenting
858 indent_amount => 2, # how many of above string to use for a single
860 newline => "\n", # string for newline
862 select => [RED, RESET], # a pair of strings defining what to surround
863 # the keyword with for colorization
867 select => 0, # A zero means that the keyword will start on
869 from => 1, # Any other positive integer means that after
870 on => 2, # said newline it will get that many indents
875 Returns a new SQL::Abstract::Tree object. All arguments are optional.
879 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
880 and C<html>. Typically a user will probably just use C<console> or
881 C<console_monochrome>, but if something about a profile bothers you, merely
882 use the profile and override the parts that you don't like.
886 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
888 Takes C<$sql> and C<\@bindargs>.
890 Returns a formatting string based on the string passed in
894 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
896 Returns a "tree" representing passed in SQL. Please do not depend on the
897 structure of the returned tree. It may be stable at some point, but not yet.
901 $sqlat->unparse($tree_structure, \@bindargs)
903 Transform "tree" into SQL, applying various transforms on the way.
905 =head2 format_keyword
907 $sqlat->format_keyword('SELECT')
909 Currently this just takes a keyword and puts the C<colormap> stuff around it.
910 Later on it may do more and allow for coderef based transforms.
914 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
916 Returns whitespace to be inserted around a keyword.
918 =head2 fill_in_placeholder
920 my $value = $sqlat->fill_in_placeholder(\@bindargs)
922 Removes last arg from passed arrayref and returns it, surrounded with
923 the values in placeholder_surround, and then surrounded with single quotes.
927 Returns as many indent strings as indent amounts times the first argument.
935 =head2 fill_in_placeholders
955 =head2 placeholder_surround