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};
9 local $ENV{PERL_STRICTURES_EXTRA} = 0;
10 # load all of these now, so that lazy-loading does not escape
11 # the current PERL_STRICTURES_EXTRA setting
16 require Method::Generate::Accessor;
17 require Method::Generate::Constructor;
20 Sub::Quote->import('quote_sub');
21 ${^WARNING_BITS} &= ( $initial_fatal_bits | ~ $warnings::DeadBits{all} );
23 # END pre-Moo2 import block
31 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
32 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
34 my $quote_left = qr/[\`\'\"\[]/;
35 my $quote_right = qr/[\`\'\"\]]/;
37 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
39 # These SQL keywords always signal end of the current expression (except inside
40 # of a parenthesized subexpression).
41 # Format: A list of strings that will be compiled to extended syntax ie.
42 # /.../x) regexes, without capturing parentheses. They will be automatically
43 # anchored to op boundaries (excluding quotes) to match the whole token.
44 my @expression_start_keywords = (
53 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
54 (?: (?: CROSS | INNER | OUTER ) \s+ )?
60 '(?: DEFAULT \s+ )? VALUES',
75 'ROLLBACK \s+ TO \s+ SAVEPOINT',
78 'RELEASE \s+ SAVEPOINT',
82 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
83 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
85 # These are binary operator keywords always a single LHS and RHS
86 # * AND/OR are handled separately as they are N-ary
87 # * so is NOT as being unary
88 # * BETWEEN without parentheses around the ANDed arguments (which
89 # makes it a non-binary op) is detected and accommodated in
91 # * AS is not really an operator but is handled here as it's also LHS/RHS
93 # this will be included in the $binary_op_re, the distinction is interesting during
94 # testing as one is tighter than the other, plus alphanum cmp ops have different
95 # look ahead/behind (e.g. "x"="y" )
96 my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /);
97 my $alphanum_cmp_op_re = join ("\n\t|\n", map
98 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
99 @alphanum_cmp_op_keywords
101 $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x;
103 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
104 $binary_op_re = join "\n\t|\n",
105 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
107 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
109 $binary_op_re = qr/$binary_op_re/x;
111 my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix;
113 my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re;
114 $unary_op_re = join "\n\t|\n",
115 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
117 $unary_op_re = qr/$unary_op_re/x;
119 my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x;
120 my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x;
122 my $tokenizer_re = join("\n\t|\n",
128 $op_look_behind . ' \* ' . $op_look_ahead,
129 (map { quotemeta $_ } qw/, ( )/),
133 # this one *is* capturing for the split below
134 # splits on whitespace if all else fails
135 # has to happen before the composing qr's are anchored (below)
136 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x;
138 # Parser states for _recurse_parse()
139 use constant PARSE_TOP_LEVEL => 0;
140 use constant PARSE_IN_EXPR => 1;
141 use constant PARSE_IN_PARENS => 2;
142 use constant PARSE_IN_FUNC => 3;
143 use constant PARSE_RHS => 4;
144 use constant PARSE_LIST_ELT => 5;
146 my $expr_term_re = qr/$expr_start_re | \)/x;
147 my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x;
148 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x;
150 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
163 $all_std_keywords_re,
165 $_ = qr/ \A $_ \z /x;
168 # what can be bunched together under one MISC in an AST
169 my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x;
195 newline indent_string indent_amount fill_in_placeholders placeholder_surround
198 has [qw( indentmap colormap )] => ( is => 'ro', default => quote_sub('{}') );
200 # class global is in fact desired
205 my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_};
207 if (my $p = delete $args->{profile}) {
209 if ($p eq 'console') {
211 fill_in_placeholders => 1,
212 placeholder_surround => ['?/', ''],
213 indent_string => ' ',
217 indentmap => \%indents,
219 ! ( eval { require Term::ANSIColor } ) ? () : do {
220 my $c = \&Term::ANSIColor::color;
222 my $red = [$c->('red') , $c->('reset')];
223 my $cyan = [$c->('cyan') , $c->('reset')];
224 my $green = [$c->('green') , $c->('reset')];
225 my $yellow = [$c->('yellow') , $c->('reset')];
226 my $blue = [$c->('blue') , $c->('reset')];
227 my $magenta = [$c->('magenta'), $c->('reset')];
228 my $b_o_w = [$c->('black on_white'), $c->('reset')];
230 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
232 'begin work' => $b_o_w,
236 'rollback to savepoint' => $b_o_w,
237 'release savepoint' => $b_o_w,
240 'insert into' => $red,
242 'delete from' => $red,
251 'left join' => $magenta,
254 'group by' => $yellow,
256 'order by' => $yellow,
267 elsif ($p eq 'console_monochrome') {
269 fill_in_placeholders => 1,
270 placeholder_surround => ['?/', ''],
271 indent_string => ' ',
274 indentmap => \%indents,
277 elsif ($p eq 'html') {
279 fill_in_placeholders => 1,
280 placeholder_surround => ['<span class="placeholder">', '</span>'],
281 indent_string => ' ',
283 newline => "<br />\n",
285 (my $class = $_) =~ s/\s+/-/g;
286 ( $_ => [ qq|<span class="$class">|, '</span>' ] )
289 qw(commit rollback savepoint),
290 'begin work', 'rollback to savepoint', 'release savepoint',
292 indentmap => \%indents,
295 elsif ($p eq 'none') {
299 croak "No such profile '$p'";
302 # see if we got any duplicates and merge if needed
303 if (scalar grep { exists $args->{$_} } keys %extra_args) {
305 $args = ($merger ||= do {
307 my $m = Hash::Merge->new;
309 $m->specify_behavior({
311 SCALAR => sub { $_[1] },
312 ARRAY => sub { [ $_[0], @{$_[1]} ] },
313 HASH => sub { $_[1] },
316 SCALAR => sub { $_[1] },
317 ARRAY => sub { $_[1] },
318 HASH => sub { $_[1] },
321 SCALAR => sub { $_[1] },
322 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
323 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
325 }, 'SQLA::Tree Behavior' );
328 })->merge(\%extra_args, $args );
332 $args = { %extra_args, %$args };
342 return [] unless defined $s;
344 # tokenize string, and remove all optional whitespace
346 foreach my $token (split $tokenizer_re, $s) {
347 push @$tokens, $token if (
356 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
360 my ($self, $tokens, $state) = @_;
363 while (1) { # left-associative parsing
367 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
369 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
371 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
373 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
378 my $token = shift @$tokens;
380 # nested expression in ()
381 if ($token eq '(' ) {
382 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
383 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
384 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
386 push @left, [ '-PAREN' => \@right ];
390 elsif ($token =~ $and_or_re) {
393 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
395 # Merge chunks if "logic" matches
396 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
403 elsif ($token eq ',') {
405 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
407 # deal with malformed lists ( foo, bar, , baz )
408 @right = [] unless @right;
410 @right = [ -MISC => [ @right ] ] if @right > 1;
413 @left = [ -LIST => [ [], @right ] ];
415 elsif ($left[0][0] eq '-LIST') {
416 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
422 @left = [ -LIST => [ @left, @right ] ];
426 # binary operator keywords
427 elsif ($token =~ $binary_op_re) {
430 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
432 # A between with a simple LITERAL for a 1st RHS argument needs a
433 # rerun of the search to (hopefully) find the proper AND construct
434 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
435 unshift @$tokens, $right[1][0];
436 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
439 push @left, [$op => [ (@left ? pop @left : ''), @right ]];
443 elsif ( $token =~ $unary_op_re ) {
446 # normalize RNO explicitly
447 $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/;
449 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
451 push @left, [ $op => \@right ];
454 # expression terminator keywords
455 elsif ( $token =~ $expr_start_re ) {
457 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
459 push @left, [ $op => \@right ];
463 elsif ( $token =~ $placeholder_re) {
464 push @left, [ -PLACEHOLDER => [ $token ] ];
467 # check if the current token is an unknown op-start
468 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
469 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
472 # we're now in "unknown token" land - start eating tokens until
473 # we see something familiar, OR in the case of RHS (binop) stop
474 # after the first token
475 # Also stop processing when we could end up with an unknown func
477 my @lits = [ -LITERAL => [$token] ];
479 unshift @lits, pop @left if @left == 1;
481 unless ( $state == PARSE_RHS ) {
485 $tokens->[0] !~ $all_std_keywords_re
487 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
489 push @lits, [ -LITERAL => [ shift @$tokens ] ];
493 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
498 # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single
502 while ($#left > $i) {
503 if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) {
504 splice @left, $i, 2, [ -MISC => [
505 map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1])
514 return @left if $state == PARSE_RHS;
516 # deal with post-fix operators
519 if ($tokens->[0] =~ $asc_desc_re) {
520 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
527 my ($self, $keyword) = @_;
529 if (my $around = $self->colormap->{lc $keyword}) {
530 $keyword = "$around->[0]$keyword$around->[1]";
544 my ($self, $keyword, $depth) = @_;
547 if (defined $self->indentmap->{lc $keyword}) {
548 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
550 $before = '' if $depth == 0 and defined $starters{lc $keyword};
551 return [$before, ''];
554 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
557 my ($self, $tree) = @_;
558 $tree = $tree->[0] while ref $tree;
560 defined $tree && defined $self->indentmap->{lc $tree};
563 sub fill_in_placeholder {
564 my ($self, $bindargs) = @_;
566 if ($self->fill_in_placeholders) {
567 my $val = shift @{$bindargs} || '';
568 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
569 my ($left, $right) = @{$self->placeholder_surround};
572 $val = qq('$val') if $quoted;
573 return qq($left$val$right)
578 # FIXME - terrible name for a user facing API
580 my ($self, $tree, $bindargs) = @_;
581 $self->_unparse($tree, [@{$bindargs||[]}], 0);
585 my ($self, $tree, $bindargs, $depth) = @_;
587 if (not $tree or not @$tree) {
591 # FIXME - needs a config switch to disable
592 $self->_parenthesis_unroll($tree);
594 my ($op, $args) = @{$tree}[0,1];
596 if (! defined $op or (! ref $op and ! defined $args) ) {
597 require Data::Dumper;
598 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
599 Data::Dumper::Dumper($tree)
604 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
606 elsif ($op eq '-LITERAL') { # literal has different sig
609 elsif ($op eq '-PLACEHOLDER') {
610 return $self->fill_in_placeholder($bindargs);
612 elsif ($op eq '-PAREN') {
613 return sprintf ('( %s )',
614 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
616 ($self->_is_key($args)
617 ? ( $self->newline||'' ) . $self->indent($depth + 1)
622 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
623 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
625 elsif ($op eq '-LIST' ) {
626 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
628 elsif ($op eq '-MISC' ) {
629 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
631 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
633 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
636 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
638 my $rhs = $self->_unparse($args, $bindargs, $depth);
640 return sprintf "$l%s$r", join(
641 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
645 $self->format_keyword($op),
646 (length $rhs ? $rhs : () ),
651 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
652 my @unrollable_ops = (
660 my $unrollable_ops_re = join ' | ', @unrollable_ops;
661 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
663 sub _parenthesis_unroll {
667 return unless (ref $ast and ref $ast->[1]);
674 for my $child (@{$ast->[1]}) {
676 # the current node in this loop is *always* a PAREN
677 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
678 push @children, $child;
682 my $parent_op = $ast->[0];
684 # unroll nested parenthesis
685 while ( $parent_op ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
686 $child = $child->[1][0];
690 # set to CHILD in the case of PARENT ( CHILD )
691 # but NOT in the case of PARENT( CHILD1, CHILD2 )
692 my $single_child_op = (@{$child->[1]} == 1) ? $child->[1][0][0] : '';
694 my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef;
696 my $single_grandchild_op
697 = ( $child_op_argc||0 == 1 and ref $child->[1][0][1][0] eq 'ARRAY' )
698 ? $child->[1][0][1][0][0]
702 # if the parent operator explicitly allows it AND the child isn't a subselect
703 # nuke the parenthesis
704 if ($parent_op =~ $unrollable_ops_re and $single_child_op ne 'SELECT') {
705 push @children, @{$child->[1]};
709 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
711 $single_child_op eq $parent_op
713 ( $parent_op eq 'AND' or $parent_op eq 'OR')
715 push @children, @{$child->[1][0][1]};
719 # only *ONE* LITERAL or placeholder element
720 # as an AND/OR/NOT argument
722 ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' )
724 ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' )
726 push @children, @{$child->[1]};
730 # an AND/OR expression with only one binop in the parenthesis
731 # with exactly two grandchildren
732 # the only time when we can *not* unroll this is when both
733 # the parent and the child are mathops (in which case we'll
734 # break precedence) or when the child is BETWEEN (special
737 ($parent_op eq 'AND' or $parent_op eq 'OR')
739 $single_child_op =~ $binary_op_re
741 $single_child_op ne 'BETWEEN'
746 $single_child_op =~ $alphanum_cmp_op_re
748 $parent_op =~ $alphanum_cmp_op_re
751 push @children, @{$child->[1]};
755 # a function binds tighter than a mathop - see if our ancestor is a
756 # mathop, and our content is:
757 # a single non-mathop child with a single PAREN grandchild which
758 # would indicate mathop ( nonmathop ( ... ) )
759 # or a single non-mathop with a single LITERAL ( nonmathop foo )
760 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
764 $parent_op =~ $alphanum_cmp_op_re
766 $single_child_op !~ $alphanum_cmp_op_re
771 $single_grandchild_op eq '-PAREN'
773 $single_grandchild_op eq '-LITERAL'
775 $single_grandchild_op eq '-PLACEHOLDER'
778 push @children, @{$child->[1]};
782 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
783 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
784 # and except for the case of RNO, where the double are explicit syntax
786 $parent_op ne 'ROW_NUMBER() OVER'
790 $single_child_op ne 'NOT'
794 $single_grandchild_op eq '-PAREN'
796 push @children, @{$child->[1]};
801 # otherwise no more mucking for this pass
803 push @children, $child;
807 $ast->[1] = \@children;
812 sub _strip_asc_from_order_by {
813 my ($self, $ast) = @_;
818 $ast->[0] ne 'ORDER BY'
824 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
825 $to_replace = [ $ast->[1][0] ];
827 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
828 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
831 @$_ = @{$_->[1][0]} for @$to_replace;
836 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
844 SQL::Abstract::Tree - Represent SQL as an AST
848 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
850 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
860 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
863 profile => 'console', # predefined profile to use (default: 'none')
864 fill_in_placeholders => 1, # true for placeholder population
865 placeholder_surround => # The strings that will be wrapped around
866 [GREEN, RESET], # populated placeholders if the above is set
867 indent_string => ' ', # the string used when indenting
868 indent_amount => 2, # how many of above string to use for a single
870 newline => "\n", # string for newline
872 select => [RED, RESET], # a pair of strings defining what to surround
873 # the keyword with for colorization
877 select => 0, # A zero means that the keyword will start on
879 from => 1, # Any other positive integer means that after
880 on => 2, # said newline it will get that many indents
885 Returns a new SQL::Abstract::Tree object. All arguments are optional.
889 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
890 and C<html>. Typically a user will probably just use C<console> or
891 C<console_monochrome>, but if something about a profile bothers you, merely
892 use the profile and override the parts that you don't like.
896 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
898 Takes C<$sql> and C<\@bindargs>.
900 Returns a formatting string based on the string passed in
904 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
906 Returns a "tree" representing passed in SQL. Please do not depend on the
907 structure of the returned tree. It may be stable at some point, but not yet.
911 $sqlat->unparse($tree_structure, \@bindargs)
913 Transform "tree" into SQL, applying various transforms on the way.
915 =head2 format_keyword
917 $sqlat->format_keyword('SELECT')
919 Currently this just takes a keyword and puts the C<colormap> stuff around it.
920 Later on it may do more and allow for coderef based transforms.
924 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
926 Returns whitespace to be inserted around a keyword.
928 =head2 fill_in_placeholder
930 my $value = $sqlat->fill_in_placeholder(\@bindargs)
932 Removes last arg from passed arrayref and returns it, surrounded with
933 the values in placeholder_surround, and then surrounded with single quotes.
937 Returns as many indent strings as indent amounts times the first argument.
945 =head2 fill_in_placeholders
965 =head2 placeholder_surround