1 package SQL::Abstract::Tree;
10 use base 'Class::Accessor::Grouped';
12 __PACKAGE__->mk_group_accessors( simple => $_ ) for 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 paranthesis around the ANDed arguments (which
95 # makes it a non-binary op) is detected and accomodated 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 mathops have different look
101 # ahead/behind (e.g. "x"="y" )
102 my @math_op_keywords = (qw/ < > != <> = <= >= /);
103 my $math_re = join ("\n\t|\n", map
104 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
107 $math_re = qr/$math_re/x;
109 sub _math_op_re { $math_re }
112 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
113 $binary_op_re = join "\n\t|\n",
114 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
116 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
118 $binary_op_re = qr/$binary_op_re/x;
120 sub _binary_op_re { $binary_op_re }
122 my $unary_op_re = '(?: NOT \s+ EXISTS | NOT )';
123 $unary_op_re = join "\n\t|\n",
124 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
126 $unary_op_re = qr/$unary_op_re/x;
128 sub _unary_op_re { $unary_op_re }
130 my $all_known_re = join("\n\t|\n",
134 "$op_look_behind (?i: AND|OR|\\* ) $op_look_ahead",
135 (map { quotemeta $_ } qw/, ( )/),
139 $all_known_re = qr/$all_known_re/x;
141 #this one *is* capturing for the split below
142 # splits on whitespace if all else fails
143 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
145 # Parser states for _recurse_parse()
146 use constant PARSE_TOP_LEVEL => 0;
147 use constant PARSE_IN_EXPR => 1;
148 use constant PARSE_IN_PARENS => 2;
149 use constant PARSE_IN_FUNC => 3;
150 use constant PARSE_RHS => 4;
151 use constant PARSE_LIST_ELT => 5;
153 my $asc_desc_re = qr/^ (?: ASC | DESC ) $/xi;
154 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
155 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | (?i: AND | OR | \, ) ) $/x;
156 my $common_single_args_re = qr/ ^ (?: \* | $placeholder_re ) $/x;
157 my $all_std_keywords_re = qr/^ (?: $rhs_term_re | \( | $common_single_args_re ) $/x;
184 fill_in_placeholders => 1,
185 placeholder_surround => ['?/', ''],
186 indent_string => ' ',
190 indentmap => \%indents,
192 eval { require Term::ANSIColor }
194 my $c = \&Term::ANSIColor::color;
196 my $red = [$c->('red') , $c->('reset')];
197 my $cyan = [$c->('cyan') , $c->('reset')];
198 my $green = [$c->('green') , $c->('reset')];
199 my $yellow = [$c->('yellow') , $c->('reset')];
200 my $blue = [$c->('blue') , $c->('reset')];
201 my $magenta = [$c->('magenta'), $c->('reset')];
202 my $b_o_w = [$c->('black on_white'), $c->('reset')];
204 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
206 'begin work' => $b_o_w,
210 'rollback to savepoint' => $b_o_w,
211 'release savepoint' => $b_o_w,
214 'insert into' => $red,
216 'delete from' => $red,
225 'left join' => $magenta,
228 'group by' => $yellow,
230 'order by' => $yellow,
240 console_monochrome => {
241 fill_in_placeholders => 1,
242 placeholder_surround => ['?/', ''],
243 indent_string => ' ',
247 indentmap => \%indents,
250 fill_in_placeholders => 1,
251 placeholder_surround => ['<span class="placeholder">', '</span>'],
252 indent_string => ' ',
254 newline => "<br />\n",
256 select => ['<span class="select">' , '</span>'],
257 'insert into' => ['<span class="insert-into">' , '</span>'],
258 update => ['<span class="select">' , '</span>'],
259 'delete from' => ['<span class="delete-from">' , '</span>'],
261 set => ['<span class="set">', '</span>'],
262 from => ['<span class="from">' , '</span>'],
264 where => ['<span class="where">' , '</span>'],
265 values => ['<span class="values">', '</span>'],
267 join => ['<span class="join">' , '</span>'],
268 'left join' => ['<span class="left-join">','</span>'],
269 on => ['<span class="on">' , '</span>'],
271 'group by' => ['<span class="group-by">', '</span>'],
272 having => ['<span class="having">', '</span>'],
273 'order by' => ['<span class="order-by">', '</span>'],
275 skip => ['<span class="skip">', '</span>'],
276 first => ['<span class="first">', '</span>'],
277 limit => ['<span class="limit">', '</span>'],
278 offset => ['<span class="offset">', '</span>'],
280 'begin work' => ['<span class="begin-work">', '</span>'],
281 commit => ['<span class="commit">', '</span>'],
282 rollback => ['<span class="rollback">', '</span>'],
283 savepoint => ['<span class="savepoint">', '</span>'],
284 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
285 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
287 indentmap => \%indents,
297 my $args = shift || {};
299 my $profile = delete $args->{profile} || 'none';
301 die "No such profile '$profile'!" unless exists $profiles{$profile};
303 my $data = $merger->merge( $profiles{$profile}, $args );
311 # tokenize string, and remove all optional whitespace
313 foreach my $token (split $tokenizer_re, $s) {
314 push @$tokens, $token if (
323 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
327 my ($self, $tokens, $state) = @_;
330 while (1) { # left-associative parsing
334 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
336 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
338 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
340 ($state == PARSE_LIST_ELT && $tokens->[0] =~ qr/^ (?: $expr_term_re | \, ) $/x)
345 my $token = shift @$tokens;
347 # nested expression in ()
348 if ($token eq '(' ) {
349 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
350 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
351 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
353 push @left, [ '-PAREN' => \@right ];
357 elsif ($token =~ /^ (?: OR | AND ) $/ix ) {
360 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
362 # Merge chunks if "logic" matches
363 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
370 elsif ($token eq ',') {
372 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
374 # deal with malformed lists ( foo, bar, , baz )
375 @right = [] unless @right;
377 @right = [ -MISC => [ @right ] ] if @right > 1;
380 @left = [ -LIST => [ [], @right ] ];
382 elsif ($left[0][0] eq '-LIST') {
383 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
389 @left = [ -LIST => [ @left, @right ] ];
393 # binary operator keywords
394 elsif ($token =~ $binary_op_re) {
397 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
399 # A between with a simple LITERAL for a 1st RHS argument needs a
400 # rerun of the search to (hopefully) find the proper AND construct
401 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
402 unshift @$tokens, $right[1][0];
403 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
406 @left = [$op => [ @left, @right ]];
410 elsif ( $token =~ $unary_op_re ) {
412 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
414 push @left, [ $op => \@right ];
417 # expression terminator keywords
418 elsif ( $token =~ $expr_start_re ) {
420 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
422 push @left, [ $op => \@right ];
426 elsif ( $token =~ $placeholder_re) {
427 push @left, [ -PLACEHOLDER => [ $token ] ];
430 # check if the current token is an unknown op-start
431 elsif (@$tokens and $tokens->[0] =~ qr/^ (?: \( | $common_single_args_re ) $/x ) {
432 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
435 # we're now in "unknown token" land - start eating tokens until
436 # we see something familiar
438 my @lits = [ -LITERAL => [$token] ];
440 while (@$tokens and $tokens->[0] !~ $all_std_keywords_re) {
441 push @lits, [ -LITERAL => [ shift @$tokens ] ];
445 unshift @lits, pop @left;
448 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
453 # deal with post-fix operators (only when sql is sane - i.e. we have one element to apply to)
454 if (@left == 1 and @$tokens) {
457 if ($tokens->[0] =~ $asc_desc_re) {
458 my $op = shift @$tokens;
460 # if -MISC - this is a literal collection, do not promote asc/desc to an op
461 if ($left[0][0] eq '-MISC') {
462 push @{$left[0][1]}, [ -LITERAL => [ $op ] ];
465 @left = [ ('-' . uc ($op)) => [ @left ] ];
473 my ($self, $keyword) = @_;
475 if (my $around = $self->colormap->{lc $keyword}) {
476 $keyword = "$around->[0]$keyword$around->[1]";
490 my ($self, $keyword, $depth) = @_;
493 if (defined $self->indentmap->{lc $keyword}) {
494 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
496 $before = '' if $depth == 0 and defined $starters{lc $keyword};
497 return [$before, ''];
500 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
503 my ($self, $tree) = @_;
504 $tree = $tree->[0] while ref $tree;
506 defined $tree && defined $self->indentmap->{lc $tree};
509 sub fill_in_placeholder {
510 my ($self, $bindargs) = @_;
512 if ($self->fill_in_placeholders) {
513 my $val = shift @{$bindargs} || '';
514 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
515 my ($left, $right) = @{$self->placeholder_surround};
518 $val = qq('$val') if $quoted;
519 return qq($left$val$right)
524 # FIXME - terrible name for a user facing API
526 my ($self, $tree, $bindargs) = @_;
527 $self->_unparse($tree, [@{$bindargs||[]}], 0);
531 my ($self, $tree, $bindargs, $depth) = @_;
533 if (not $tree or not @$tree) {
537 # FIXME - needs a config switch to disable
538 $self->_parenthesis_unroll($tree);
540 my ($op, $args) = @{$tree}[0,1];
542 if (! defined $op or (! ref $op and ! defined $args) ) {
543 require Data::Dumper;
544 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
545 Data::Dumper::Dumper($tree)
550 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
552 elsif ($op eq '-LITERAL') { # literal has different sig
555 elsif ($op eq '-PLACEHOLDER') {
556 return $self->fill_in_placeholder($bindargs);
558 elsif ($op eq '-PAREN') {
559 return sprintf ('( %s )',
560 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
562 ($self->_is_key($args)
563 ? ( $self->newline||'' ) . $self->indent($depth + 1)
568 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ / ^ $binary_op_re $ /x ) {
569 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
571 elsif ($op eq '-LIST' ) {
572 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
574 elsif ($op eq '-MISC' ) {
575 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
578 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
579 return sprintf "$l%s%s%s$r",
580 $self->format_keyword($op),
581 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
585 $self->_unparse($args, $bindargs, $depth),
590 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
591 my @unrollable_ops = (
599 my $unrollable_ops_re = join ' | ', @unrollable_ops;
600 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
602 sub _parenthesis_unroll {
606 return unless (ref $ast and ref $ast->[1]);
613 for my $child (@{$ast->[1]}) {
615 # the current node in this loop is *always* a PAREN
616 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
617 push @children, $child;
621 # unroll nested parenthesis
622 while ( @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
623 $child = $child->[1][0];
627 # if the parent operator explcitly allows it nuke the parenthesis
628 if ( $ast->[0] =~ $unrollable_ops_re ) {
629 push @children, @{$child->[1]};
633 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
637 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
639 $child->[1][0][0] eq $ast->[0]
641 push @children, @{$child->[1][0][1]};
645 # only *ONE* LITERAL or placeholder element
646 # as an AND/OR/NOT argument
648 @{$child->[1]} == 1 && (
649 $child->[1][0][0] eq '-LITERAL'
651 $child->[1][0][0] eq '-PLACEHOLDER'
653 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
656 push @children, @{$child->[1]};
660 # an AND/OR expression with only one binop in the parenthesis
661 # with exactly two grandchildren
662 # the only time when we can *not* unroll this is when both
663 # the parent and the child are mathops (in which case we'll
664 # break precedence) or when the child is BETWEEN (special
669 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
671 $child->[1][0][0] =~ SQL::Abstract::Tree::_binary_op_re()
673 $child->[1][0][0] ne 'BETWEEN'
675 @{$child->[1][0][1]} == 2
678 $child->[1][0][0] =~ SQL::Abstract::Tree::_math_op_re()
680 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
683 push @children, @{$child->[1]};
687 # a function binds tighter than a mathop - see if our ancestor is a
688 # mathop, and our content is:
689 # a single non-mathop child with a single PAREN grandchild which
690 # would indicate mathop ( nonmathop ( ... ) )
691 # or a single non-mathop with a single LITERAL ( nonmathop foo )
692 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
696 @{$child->[1][0][1]} == 1
698 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
700 $child->[1][0][0] !~ SQL::Abstract::Tree::_math_op_re
703 $child->[1][0][1][0][0] eq '-PAREN'
705 $child->[1][0][1][0][0] eq '-LITERAL'
707 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
710 push @children, @{$child->[1]};
715 # otherwise no more mucking for this pass
717 push @children, $child;
721 $ast->[1] = \@children;
726 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
734 SQL::Abstract::Tree - Represent SQL as an AST
738 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
740 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
750 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
753 profile => 'console', # predefined profile to use (default: 'none')
754 fill_in_placeholders => 1, # true for placeholder population
755 placeholder_surround => # The strings that will be wrapped around
756 [GREEN, RESET], # populated placeholders if the above is set
757 indent_string => ' ', # the string used when indenting
758 indent_amount => 2, # how many of above string to use for a single
760 newline => "\n", # string for newline
762 select => [RED, RESET], # a pair of strings defining what to surround
763 # the keyword with for colorization
767 select => 0, # A zero means that the keyword will start on
769 from => 1, # Any other positive integer means that after
770 on => 2, # said newline it will get that many indents
775 Returns a new SQL::Abstract::Tree object. All arguments are optional.
779 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
780 and C<html>. Typically a user will probably just use C<console> or
781 C<console_monochrome>, but if something about a profile bothers you, merely
782 use the profile and override the parts that you don't like.
786 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
788 Takes C<$sql> and C<\@bindargs>.
790 Returns a formatting string based on the string passed in
794 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
796 Returns a "tree" representing passed in SQL. Please do not depend on the
797 structure of the returned tree. It may be stable at some point, but not yet.
801 $sqlat->parse($tree_structure, \@bindargs)
803 Transform "tree" into SQL, applying various transforms on the way.
805 =head2 format_keyword
807 $sqlat->format_keyword('SELECT')
809 Currently this just takes a keyword and puts the C<colormap> stuff around it.
810 Later on it may do more and allow for coderef based transforms.
814 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
816 Returns whitespace to be inserted around a keyword.
818 =head2 fill_in_placeholder
820 my $value = $sqlat->fill_in_placeholder(\@bindargs)
822 Removes last arg from passed arrayref and returns it, surrounded with
823 the values in placeholder_surround, and then surrounded with single quotes.
827 Returns as many indent strings as indent amounts times the first argument.
835 =head2 fill_in_placeholders
855 =head2 placeholder_surround