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;
198 fill_in_placeholders => 1,
199 placeholder_surround => ['?/', ''],
200 indent_string => ' ',
204 indentmap => \%indents,
206 eval { require Term::ANSIColor }
208 my $c = \&Term::ANSIColor::color;
210 my $red = [$c->('red') , $c->('reset')];
211 my $cyan = [$c->('cyan') , $c->('reset')];
212 my $green = [$c->('green') , $c->('reset')];
213 my $yellow = [$c->('yellow') , $c->('reset')];
214 my $blue = [$c->('blue') , $c->('reset')];
215 my $magenta = [$c->('magenta'), $c->('reset')];
216 my $b_o_w = [$c->('black on_white'), $c->('reset')];
218 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
220 'begin work' => $b_o_w,
224 'rollback to savepoint' => $b_o_w,
225 'release savepoint' => $b_o_w,
228 'insert into' => $red,
230 'delete from' => $red,
239 'left join' => $magenta,
242 'group by' => $yellow,
244 'order by' => $yellow,
254 console_monochrome => {
255 fill_in_placeholders => 1,
256 placeholder_surround => ['?/', ''],
257 indent_string => ' ',
261 indentmap => \%indents,
264 fill_in_placeholders => 1,
265 placeholder_surround => ['<span class="placeholder">', '</span>'],
266 indent_string => ' ',
268 newline => "<br />\n",
270 select => ['<span class="select">' , '</span>'],
271 'insert into' => ['<span class="insert-into">' , '</span>'],
272 update => ['<span class="select">' , '</span>'],
273 'delete from' => ['<span class="delete-from">' , '</span>'],
275 set => ['<span class="set">', '</span>'],
276 from => ['<span class="from">' , '</span>'],
278 where => ['<span class="where">' , '</span>'],
279 values => ['<span class="values">', '</span>'],
281 join => ['<span class="join">' , '</span>'],
282 'left join' => ['<span class="left-join">','</span>'],
283 on => ['<span class="on">' , '</span>'],
285 'group by' => ['<span class="group-by">', '</span>'],
286 having => ['<span class="having">', '</span>'],
287 'order by' => ['<span class="order-by">', '</span>'],
289 skip => ['<span class="skip">', '</span>'],
290 first => ['<span class="first">', '</span>'],
291 limit => ['<span class="limit">', '</span>'],
292 offset => ['<span class="offset">', '</span>'],
294 'begin work' => ['<span class="begin-work">', '</span>'],
295 commit => ['<span class="commit">', '</span>'],
296 rollback => ['<span class="rollback">', '</span>'],
297 savepoint => ['<span class="savepoint">', '</span>'],
298 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
299 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
301 indentmap => \%indents,
311 my $args = shift || {};
313 my $profile = delete $args->{profile} || 'none';
315 die "No such profile '$profile'!" unless exists $profiles{$profile};
317 my $data = $merger->merge( $profiles{$profile}, $args );
325 # tokenize string, and remove all optional whitespace
327 foreach my $token (split $tokenizer_re, $s) {
328 push @$tokens, $token if (
337 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
341 my ($self, $tokens, $state) = @_;
344 while (1) { # left-associative parsing
348 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
350 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
352 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
354 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
359 my $token = shift @$tokens;
361 # nested expression in ()
362 if ($token eq '(' ) {
363 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
364 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
365 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
367 push @left, [ '-PAREN' => \@right ];
371 elsif ($token =~ $and_or_re) {
374 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
376 # Merge chunks if "logic" matches
377 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
384 elsif ($token eq ',') {
386 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
388 # deal with malformed lists ( foo, bar, , baz )
389 @right = [] unless @right;
391 @right = [ -MISC => [ @right ] ] if @right > 1;
394 @left = [ -LIST => [ [], @right ] ];
396 elsif ($left[0][0] eq '-LIST') {
397 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
403 @left = [ -LIST => [ @left, @right ] ];
407 # binary operator keywords
408 elsif ($token =~ $binary_op_re) {
411 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
413 # A between with a simple LITERAL for a 1st RHS argument needs a
414 # rerun of the search to (hopefully) find the proper AND construct
415 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
416 unshift @$tokens, $right[1][0];
417 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
420 @left = [$op => [ @left, @right ]];
424 elsif ( $token =~ $unary_op_re ) {
426 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
428 push @left, [ $op => \@right ];
431 # expression terminator keywords
432 elsif ( $token =~ $expr_start_re ) {
434 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
436 push @left, [ $op => \@right ];
440 elsif ( $token =~ $placeholder_re) {
441 push @left, [ -PLACEHOLDER => [ $token ] ];
444 # check if the current token is an unknown op-start
445 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) {
446 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
449 # we're now in "unknown token" land - start eating tokens until
450 # we see something familiar, OR in the case of RHS (binop) stop
451 # after the first token
452 # Also stop processing when we could end up with an unknown func
454 my @lits = [ -LITERAL => [$token] ];
456 unless ( $state == PARSE_RHS ) {
460 $tokens->[0] !~ $all_std_keywords_re
462 ! ( @$tokens > 1 and $tokens->[1] eq '(' )
464 push @lits, [ -LITERAL => [ shift @$tokens ] ];
469 unshift @lits, pop @left;
472 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
479 # deal with post-fix operators (asc/desc)
480 if ($tokens->[0] =~ $asc_desc_re) {
481 return @left if $state == PARSE_RHS;
482 @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ];
485 return @left if $state == PARSE_RHS and $left[-1][0] eq '-LITERAL';
491 my ($self, $keyword) = @_;
493 if (my $around = $self->colormap->{lc $keyword}) {
494 $keyword = "$around->[0]$keyword$around->[1]";
508 my ($self, $keyword, $depth) = @_;
511 if (defined $self->indentmap->{lc $keyword}) {
512 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
514 $before = '' if $depth == 0 and defined $starters{lc $keyword};
515 return [$before, ''];
518 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
521 my ($self, $tree) = @_;
522 $tree = $tree->[0] while ref $tree;
524 defined $tree && defined $self->indentmap->{lc $tree};
527 sub fill_in_placeholder {
528 my ($self, $bindargs) = @_;
530 if ($self->fill_in_placeholders) {
531 my $val = shift @{$bindargs} || '';
532 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
533 my ($left, $right) = @{$self->placeholder_surround};
536 $val = qq('$val') if $quoted;
537 return qq($left$val$right)
542 # FIXME - terrible name for a user facing API
544 my ($self, $tree, $bindargs) = @_;
545 $self->_unparse($tree, [@{$bindargs||[]}], 0);
549 my ($self, $tree, $bindargs, $depth) = @_;
551 if (not $tree or not @$tree) {
555 # FIXME - needs a config switch to disable
556 $self->_parenthesis_unroll($tree);
558 my ($op, $args) = @{$tree}[0,1];
560 if (! defined $op or (! ref $op and ! defined $args) ) {
561 require Data::Dumper;
562 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
563 Data::Dumper::Dumper($tree)
568 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
570 elsif ($op eq '-LITERAL') { # literal has different sig
573 elsif ($op eq '-PLACEHOLDER') {
574 return $self->fill_in_placeholder($bindargs);
576 elsif ($op eq '-PAREN') {
577 return sprintf ('( %s )',
578 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
580 ($self->_is_key($args)
581 ? ( $self->newline||'' ) . $self->indent($depth + 1)
586 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
587 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
589 elsif ($op eq '-LIST' ) {
590 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
592 elsif ($op eq '-MISC' ) {
593 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
595 elsif ($op =~ qr/^-(ASC|DESC)$/ ) {
597 return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir);
600 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
602 my $rhs = $self->_unparse($args, $bindargs, $depth);
604 return sprintf "$l%s$r", join(
605 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
609 $self->format_keyword($op),
610 (length $rhs ? $rhs : () ),
615 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
616 my @unrollable_ops = (
624 my $unrollable_ops_re = join ' | ', @unrollable_ops;
625 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
627 sub _parenthesis_unroll {
631 return unless (ref $ast and ref $ast->[1]);
638 for my $child (@{$ast->[1]}) {
640 # the current node in this loop is *always* a PAREN
641 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
642 push @children, $child;
646 # unroll nested parenthesis
647 while ( @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
648 $child = $child->[1][0];
652 # if the parent operator explicitly allows it nuke the parenthesis
653 if ( $ast->[0] =~ $unrollable_ops_re ) {
654 push @children, @{$child->[1]};
658 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
662 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
664 $child->[1][0][0] eq $ast->[0]
666 push @children, @{$child->[1][0][1]};
670 # only *ONE* LITERAL or placeholder element
671 # as an AND/OR/NOT argument
673 @{$child->[1]} == 1 && (
674 $child->[1][0][0] eq '-LITERAL'
676 $child->[1][0][0] eq '-PLACEHOLDER'
678 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
681 push @children, @{$child->[1]};
685 # an AND/OR expression with only one binop in the parenthesis
686 # with exactly two grandchildren
687 # the only time when we can *not* unroll this is when both
688 # the parent and the child are mathops (in which case we'll
689 # break precedence) or when the child is BETWEEN (special
694 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
696 $child->[1][0][0] =~ $binary_op_re
698 $child->[1][0][0] ne 'BETWEEN'
700 @{$child->[1][0][1]} == 2
703 $child->[1][0][0] =~ $alphanum_cmp_op_re
705 $ast->[0] =~ $alphanum_cmp_op_re
708 push @children, @{$child->[1]};
712 # a function binds tighter than a mathop - see if our ancestor is a
713 # mathop, and our content is:
714 # a single non-mathop child with a single PAREN grandchild which
715 # would indicate mathop ( nonmathop ( ... ) )
716 # or a single non-mathop with a single LITERAL ( nonmathop foo )
717 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
721 @{$child->[1][0][1]} == 1
723 $ast->[0] =~ $alphanum_cmp_op_re
725 $child->[1][0][0] !~ $alphanum_cmp_op_re
728 $child->[1][0][1][0][0] eq '-PAREN'
730 $child->[1][0][1][0][0] eq '-LITERAL'
732 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
735 push @children, @{$child->[1]};
739 # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens
740 # except for the case of ( NOT ( ... ) ) which has already been handled earlier
744 @{$child->[1][0][1]} == 1
746 $child->[1][0][0] ne 'NOT'
748 ref $child->[1][0][1][0] eq 'ARRAY'
750 $child->[1][0][1][0][0] eq '-PAREN'
752 push @children, @{$child->[1]};
757 # otherwise no more mucking for this pass
759 push @children, $child;
763 $ast->[1] = \@children;
768 sub _strip_asc_from_order_by {
769 my ($self, $ast) = @_;
774 $ast->[0] ne 'ORDER BY'
780 if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') {
781 $to_replace = [ $ast->[1][0] ];
783 elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') {
784 $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ];
787 @$_ = @{$_->[1][0]} for @$to_replace;
792 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
800 SQL::Abstract::Tree - Represent SQL as an AST
804 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
806 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
816 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
819 profile => 'console', # predefined profile to use (default: 'none')
820 fill_in_placeholders => 1, # true for placeholder population
821 placeholder_surround => # The strings that will be wrapped around
822 [GREEN, RESET], # populated placeholders if the above is set
823 indent_string => ' ', # the string used when indenting
824 indent_amount => 2, # how many of above string to use for a single
826 newline => "\n", # string for newline
828 select => [RED, RESET], # a pair of strings defining what to surround
829 # the keyword with for colorization
833 select => 0, # A zero means that the keyword will start on
835 from => 1, # Any other positive integer means that after
836 on => 2, # said newline it will get that many indents
841 Returns a new SQL::Abstract::Tree object. All arguments are optional.
845 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
846 and C<html>. Typically a user will probably just use C<console> or
847 C<console_monochrome>, but if something about a profile bothers you, merely
848 use the profile and override the parts that you don't like.
852 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
854 Takes C<$sql> and C<\@bindargs>.
856 Returns a formatting string based on the string passed in
860 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
862 Returns a "tree" representing passed in SQL. Please do not depend on the
863 structure of the returned tree. It may be stable at some point, but not yet.
867 $sqlat->unparse($tree_structure, \@bindargs)
869 Transform "tree" into SQL, applying various transforms on the way.
871 =head2 format_keyword
873 $sqlat->format_keyword('SELECT')
875 Currently this just takes a keyword and puts the C<colormap> stuff around it.
876 Later on it may do more and allow for coderef based transforms.
880 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
882 Returns whitespace to be inserted around a keyword.
884 =head2 fill_in_placeholder
886 my $value = $sqlat->fill_in_placeholder(\@bindargs)
888 Removes last arg from passed arrayref and returns it, surrounded with
889 the values in placeholder_surround, and then surrounded with single quotes.
893 Returns as many indent strings as indent amounts times the first argument.
901 =head2 fill_in_placeholders
921 =head2 placeholder_surround