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 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_op_re = join ("\n\t|\n", map
104 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
107 $math_op_re = qr/$math_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 composiign 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 $common_single_args_re = qr/ \* | $placeholder_re /x;
153 my $all_std_keywords_re = qr/ $rhs_term_re | \( | $common_single_args_re /x;
155 # anchor everything - even though keywords are separated by the tokenizer, leakage may occur
168 $common_single_args_re,
169 $all_std_keywords_re,
171 $_ = qr/ \A $_ \z /x;
200 fill_in_placeholders => 1,
201 placeholder_surround => ['?/', ''],
202 indent_string => ' ',
206 indentmap => \%indents,
208 eval { require Term::ANSIColor }
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,
256 console_monochrome => {
257 fill_in_placeholders => 1,
258 placeholder_surround => ['?/', ''],
259 indent_string => ' ',
263 indentmap => \%indents,
266 fill_in_placeholders => 1,
267 placeholder_surround => ['<span class="placeholder">', '</span>'],
268 indent_string => ' ',
270 newline => "<br />\n",
272 select => ['<span class="select">' , '</span>'],
273 'insert into' => ['<span class="insert-into">' , '</span>'],
274 update => ['<span class="select">' , '</span>'],
275 'delete from' => ['<span class="delete-from">' , '</span>'],
277 set => ['<span class="set">', '</span>'],
278 from => ['<span class="from">' , '</span>'],
280 where => ['<span class="where">' , '</span>'],
281 values => ['<span class="values">', '</span>'],
283 join => ['<span class="join">' , '</span>'],
284 'left join' => ['<span class="left-join">','</span>'],
285 on => ['<span class="on">' , '</span>'],
287 'group by' => ['<span class="group-by">', '</span>'],
288 having => ['<span class="having">', '</span>'],
289 'order by' => ['<span class="order-by">', '</span>'],
291 skip => ['<span class="skip">', '</span>'],
292 first => ['<span class="first">', '</span>'],
293 limit => ['<span class="limit">', '</span>'],
294 offset => ['<span class="offset">', '</span>'],
296 'begin work' => ['<span class="begin-work">', '</span>'],
297 commit => ['<span class="commit">', '</span>'],
298 rollback => ['<span class="rollback">', '</span>'],
299 savepoint => ['<span class="savepoint">', '</span>'],
300 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
301 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
303 indentmap => \%indents,
313 my $args = shift || {};
315 my $profile = delete $args->{profile} || 'none';
317 die "No such profile '$profile'!" unless exists $profiles{$profile};
319 my $data = $merger->merge( $profiles{$profile}, $args );
327 # tokenize string, and remove all optional whitespace
329 foreach my $token (split $tokenizer_re, $s) {
330 push @$tokens, $token if (
339 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
343 my ($self, $tokens, $state) = @_;
346 while (1) { # left-associative parsing
350 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
352 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
354 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
356 ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) )
361 my $token = shift @$tokens;
363 # nested expression in ()
364 if ($token eq '(' ) {
365 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
366 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
367 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
369 push @left, [ '-PAREN' => \@right ];
373 elsif ($token =~ $and_or_re) {
376 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
378 # Merge chunks if "logic" matches
379 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
386 elsif ($token eq ',') {
388 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
390 # deal with malformed lists ( foo, bar, , baz )
391 @right = [] unless @right;
393 @right = [ -MISC => [ @right ] ] if @right > 1;
396 @left = [ -LIST => [ [], @right ] ];
398 elsif ($left[0][0] eq '-LIST') {
399 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
405 @left = [ -LIST => [ @left, @right ] ];
409 # binary operator keywords
410 elsif ($token =~ $binary_op_re) {
413 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
415 # A between with a simple LITERAL for a 1st RHS argument needs a
416 # rerun of the search to (hopefully) find the proper AND construct
417 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
418 unshift @$tokens, $right[1][0];
419 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
422 @left = [$op => [ @left, @right ]];
426 elsif ( $token =~ $unary_op_re ) {
428 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
430 push @left, [ $op => \@right ];
433 # expression terminator keywords
434 elsif ( $token =~ $expr_start_re ) {
436 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
438 push @left, [ $op => \@right ];
442 elsif ( $token =~ $placeholder_re) {
443 push @left, [ -PLACEHOLDER => [ $token ] ];
446 # check if the current token is an unknown op-start
447 elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $common_single_args_re ) ) {
448 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
451 # we're now in "unknown token" land - start eating tokens until
452 # we see something familiar
454 my @lits = [ -LITERAL => [$token] ];
456 while (@$tokens and $tokens->[0] !~ $all_std_keywords_re) {
457 push @lits, [ -LITERAL => [ shift @$tokens ] ];
461 unshift @lits, pop @left;
464 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
469 # deal with post-fix operators (only when sql is sane - i.e. we have one element to apply to)
470 if (@left == 1 and @$tokens) {
473 if ($tokens->[0] =~ $asc_desc_re) {
474 my $op = shift @$tokens;
476 # if -MISC - this is a literal collection, do not promote asc/desc to an op
477 if ($left[0][0] eq '-MISC') {
478 push @{$left[0][1]}, [ -LITERAL => [ $op ] ];
481 @left = [ ('-' . uc ($op)) => [ @left ] ];
489 my ($self, $keyword) = @_;
491 if (my $around = $self->colormap->{lc $keyword}) {
492 $keyword = "$around->[0]$keyword$around->[1]";
506 my ($self, $keyword, $depth) = @_;
509 if (defined $self->indentmap->{lc $keyword}) {
510 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
512 $before = '' if $depth == 0 and defined $starters{lc $keyword};
513 return [$before, ''];
516 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
519 my ($self, $tree) = @_;
520 $tree = $tree->[0] while ref $tree;
522 defined $tree && defined $self->indentmap->{lc $tree};
525 sub fill_in_placeholder {
526 my ($self, $bindargs) = @_;
528 if ($self->fill_in_placeholders) {
529 my $val = shift @{$bindargs} || '';
530 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
531 my ($left, $right) = @{$self->placeholder_surround};
534 $val = qq('$val') if $quoted;
535 return qq($left$val$right)
540 # FIXME - terrible name for a user facing API
542 my ($self, $tree, $bindargs) = @_;
543 $self->_unparse($tree, [@{$bindargs||[]}], 0);
547 my ($self, $tree, $bindargs, $depth) = @_;
549 if (not $tree or not @$tree) {
553 # FIXME - needs a config switch to disable
554 $self->_parenthesis_unroll($tree);
556 my ($op, $args) = @{$tree}[0,1];
558 if (! defined $op or (! ref $op and ! defined $args) ) {
559 require Data::Dumper;
560 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
561 Data::Dumper::Dumper($tree)
566 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
568 elsif ($op eq '-LITERAL') { # literal has different sig
571 elsif ($op eq '-PLACEHOLDER') {
572 return $self->fill_in_placeholder($bindargs);
574 elsif ($op eq '-PAREN') {
575 return sprintf ('( %s )',
576 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
578 ($self->_is_key($args)
579 ? ( $self->newline||'' ) . $self->indent($depth + 1)
584 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) {
585 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
587 elsif ($op eq '-LIST' ) {
588 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
590 elsif ($op eq '-MISC' ) {
591 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
594 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
595 return sprintf "$l%s%s%s$r",
596 $self->format_keyword($op),
597 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
601 $self->_unparse($args, $bindargs, $depth),
606 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
607 my @unrollable_ops = (
615 my $unrollable_ops_re = join ' | ', @unrollable_ops;
616 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
618 sub _parenthesis_unroll {
622 return unless (ref $ast and ref $ast->[1]);
629 for my $child (@{$ast->[1]}) {
631 # the current node in this loop is *always* a PAREN
632 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
633 push @children, $child;
637 # unroll nested parenthesis
638 while ( @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
639 $child = $child->[1][0];
643 # if the parent operator explcitly allows it nuke the parenthesis
644 if ( $ast->[0] =~ $unrollable_ops_re ) {
645 push @children, @{$child->[1]};
649 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
653 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
655 $child->[1][0][0] eq $ast->[0]
657 push @children, @{$child->[1][0][1]};
661 # only *ONE* LITERAL or placeholder element
662 # as an AND/OR/NOT argument
664 @{$child->[1]} == 1 && (
665 $child->[1][0][0] eq '-LITERAL'
667 $child->[1][0][0] eq '-PLACEHOLDER'
669 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
672 push @children, @{$child->[1]};
676 # an AND/OR expression with only one binop in the parenthesis
677 # with exactly two grandchildren
678 # the only time when we can *not* unroll this is when both
679 # the parent and the child are mathops (in which case we'll
680 # break precedence) or when the child is BETWEEN (special
685 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
687 $child->[1][0][0] =~ $binary_op_re
689 $child->[1][0][0] ne 'BETWEEN'
691 @{$child->[1][0][1]} == 2
694 $child->[1][0][0] =~ $math_op_re
696 $ast->[0] =~ $math_op_re
699 push @children, @{$child->[1]};
703 # a function binds tighter than a mathop - see if our ancestor is a
704 # mathop, and our content is:
705 # a single non-mathop child with a single PAREN grandchild which
706 # would indicate mathop ( nonmathop ( ... ) )
707 # or a single non-mathop with a single LITERAL ( nonmathop foo )
708 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
712 @{$child->[1][0][1]} == 1
714 $ast->[0] =~ $math_op_re
716 $child->[1][0][0] !~ $math_op_re
719 $child->[1][0][1][0][0] eq '-PAREN'
721 $child->[1][0][1][0][0] eq '-LITERAL'
723 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
726 push @children, @{$child->[1]};
731 # otherwise no more mucking for this pass
733 push @children, $child;
737 $ast->[1] = \@children;
742 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
750 SQL::Abstract::Tree - Represent SQL as an AST
754 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
756 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
766 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
769 profile => 'console', # predefined profile to use (default: 'none')
770 fill_in_placeholders => 1, # true for placeholder population
771 placeholder_surround => # The strings that will be wrapped around
772 [GREEN, RESET], # populated placeholders if the above is set
773 indent_string => ' ', # the string used when indenting
774 indent_amount => 2, # how many of above string to use for a single
776 newline => "\n", # string for newline
778 select => [RED, RESET], # a pair of strings defining what to surround
779 # the keyword with for colorization
783 select => 0, # A zero means that the keyword will start on
785 from => 1, # Any other positive integer means that after
786 on => 2, # said newline it will get that many indents
791 Returns a new SQL::Abstract::Tree object. All arguments are optional.
795 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
796 and C<html>. Typically a user will probably just use C<console> or
797 C<console_monochrome>, but if something about a profile bothers you, merely
798 use the profile and override the parts that you don't like.
802 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
804 Takes C<$sql> and C<\@bindargs>.
806 Returns a formatting string based on the string passed in
810 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
812 Returns a "tree" representing passed in SQL. Please do not depend on the
813 structure of the returned tree. It may be stable at some point, but not yet.
817 $sqlat->unparse($tree_structure, \@bindargs)
819 Transform "tree" into SQL, applying various transforms on the way.
821 =head2 format_keyword
823 $sqlat->format_keyword('SELECT')
825 Currently this just takes a keyword and puts the C<colormap> stuff around it.
826 Later on it may do more and allow for coderef based transforms.
830 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
832 Returns whitespace to be inserted around a keyword.
834 =head2 fill_in_placeholder
836 my $value = $sqlat->fill_in_placeholder(\@bindargs)
838 Removes last arg from passed arrayref and returns it, surrounded with
839 the values in placeholder_surround, and then surrounded with single quotes.
843 Returns as many indent strings as indent amounts times the first argument.
851 =head2 fill_in_placeholders
871 =head2 placeholder_surround