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',
67 '(?: NOT \s+)? EXISTS',
81 'ROLLBACK \s+ TO \s+ SAVEPOINT',
84 'RELEASE \s+ SAVEPOINT',
86 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
89 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
90 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
92 # These are binary operator keywords always a single LHS and RHS
93 # * AND/OR are handled separately as they are N-ary
94 # * so is NOT as being unary
95 # * BETWEEN without paranthesis around the ANDed arguments (which
96 # makes it a non-binary op) is detected and accomodated in
98 # * AS is not really an operator but is handled here as it's also LHS/RHS
100 # this will be included in the $binary_op_re, the distinction is interesting during
101 # testing as one is tighter than the other, plus mathops have different look
102 # ahead/behind (e.g. "x"="y" )
103 my @math_op_keywords = (qw/ < > != <> = <= >= /);
104 my $math_re = join ("\n\t|\n", map
105 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
108 $math_re = qr/$math_re/x;
110 sub _math_op_re { $math_re }
113 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
114 $binary_op_re = join "\n\t|\n",
115 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
117 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
119 $binary_op_re = qr/$binary_op_re/x;
121 sub _binary_op_re { $binary_op_re }
123 my $all_known_re = join("\n\t|\n",
126 "$op_look_behind (?i: AND|OR|NOT|\\* ) $op_look_ahead",
127 (map { quotemeta $_ } qw/, ( )/),
131 $all_known_re = qr/$all_known_re/x;
133 #this one *is* capturing for the split below
134 # splits on whitespace if all else fails
135 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
137 # Parser states for _recurse_parse()
138 use constant PARSE_TOP_LEVEL => 0;
139 use constant PARSE_IN_EXPR => 1;
140 use constant PARSE_IN_PARENS => 2;
141 use constant PARSE_IN_FUNC => 3;
142 use constant PARSE_RHS => 4;
144 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
145 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
146 my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
172 fill_in_placeholders => 1,
173 placeholder_surround => ['?/', ''],
174 indent_string => ' ',
178 indentmap => \%indents,
180 eval { require Term::ANSIColor }
182 my $c = \&Term::ANSIColor::color;
184 my $red = [$c->('red') , $c->('reset')];
185 my $cyan = [$c->('cyan') , $c->('reset')];
186 my $green = [$c->('green') , $c->('reset')];
187 my $yellow = [$c->('yellow') , $c->('reset')];
188 my $blue = [$c->('blue') , $c->('reset')];
189 my $magenta = [$c->('magenta'), $c->('reset')];
190 my $b_o_w = [$c->('black on_white'), $c->('reset')];
192 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
194 'begin work' => $b_o_w,
198 'rollback to savepoint' => $b_o_w,
199 'release savepoint' => $b_o_w,
202 'insert into' => $red,
204 'delete from' => $red,
213 'left join' => $magenta,
216 'group by' => $yellow,
218 'order by' => $yellow,
228 console_monochrome => {
229 fill_in_placeholders => 1,
230 placeholder_surround => ['?/', ''],
231 indent_string => ' ',
235 indentmap => \%indents,
238 fill_in_placeholders => 1,
239 placeholder_surround => ['<span class="placeholder">', '</span>'],
240 indent_string => ' ',
242 newline => "<br />\n",
244 select => ['<span class="select">' , '</span>'],
245 'insert into' => ['<span class="insert-into">' , '</span>'],
246 update => ['<span class="select">' , '</span>'],
247 'delete from' => ['<span class="delete-from">' , '</span>'],
249 set => ['<span class="set">', '</span>'],
250 from => ['<span class="from">' , '</span>'],
252 where => ['<span class="where">' , '</span>'],
253 values => ['<span class="values">', '</span>'],
255 join => ['<span class="join">' , '</span>'],
256 'left join' => ['<span class="left-join">','</span>'],
257 on => ['<span class="on">' , '</span>'],
259 'group by' => ['<span class="group-by">', '</span>'],
260 having => ['<span class="having">', '</span>'],
261 'order by' => ['<span class="order-by">', '</span>'],
263 skip => ['<span class="skip">', '</span>'],
264 first => ['<span class="first">', '</span>'],
265 limit => ['<span class="limit">', '</span>'],
266 offset => ['<span class="offset">', '</span>'],
268 'begin work' => ['<span class="begin-work">', '</span>'],
269 commit => ['<span class="commit">', '</span>'],
270 rollback => ['<span class="rollback">', '</span>'],
271 savepoint => ['<span class="savepoint">', '</span>'],
272 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
273 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
275 indentmap => \%indents,
285 my $args = shift || {};
287 my $profile = delete $args->{profile} || 'none';
289 die "No such profile '$profile'!" unless exists $profiles{$profile};
291 my $data = $merger->merge( $profiles{$profile}, $args );
299 # tokenize string, and remove all optional whitespace
301 foreach my $token (split $tokenizer_re, $s) {
302 push @$tokens, $token if (
310 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
314 # this is temporary, lists can be parsed *without* recursing, but
315 # it requires a massive rewrite of the AST generator
316 no warnings qw/recursion/;
318 my ($self, $tokens, $state) = @_;
321 while (1) { # left-associative parsing
323 my $lookahead = $tokens->[0];
324 if ( not defined($lookahead)
326 ($state == PARSE_IN_PARENS && $lookahead eq ')')
328 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
330 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
332 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
337 my $token = shift @$tokens;
339 # nested expression in ()
340 if ($token eq '(' ) {
341 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
342 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
343 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
345 $left = $left ? [$left, [PAREN => [$right||()] ]]
346 : [PAREN => [$right||()] ];
348 # AND/OR and LIST (,)
349 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
350 my $op = ($token eq ',') ? 'LIST' : uc $token;
352 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR) || [];
354 # Merge chunks if logic matches
355 if (ref $right and @$right and $op eq $right->[0]) {
356 $left = [ (shift @$right ), [$left||[], map { @$_ } @$right] ];
359 $left = [$op => [ $left||[], $right ]];
362 # binary operator keywords
363 elsif ( $token =~ /^ $binary_op_re $ /x ) {
365 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
367 # A between with a simple LITERAL for a 1st RHS argument needs a
368 # rerun of the search to (hopefully) find the proper AND construct
369 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
370 unshift @$tokens, $right->[1][0];
371 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
374 $left = [$op => [$left, $right] ];
376 # expression terminator keywords (as they start a new expression)
377 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
379 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
380 $left = $left ? [ $left, [$op => [$right||()] ]]
381 : [ $op => [$right||()] ];
384 elsif ( $token =~ /^ NOT $/ix ) {
386 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
387 $left = $left ? [ @$left, [$op => [$right||()] ]]
388 : [ $op => [$right||()] ];
391 elsif ( $token =~ $placeholder_re) {
392 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
393 : [ PLACEHOLDER => [ $token ] ];
395 # we're now in "unknown token" land - start eating tokens until
396 # we see something familiar
400 # check if the current token is an unknown op-start
401 if (@$tokens and $tokens->[0] =~ $func_start_re) {
402 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
405 $right = [ LITERAL => [ $token ] ];
408 $left = $left ? [ $left, $right ]
416 my ($self, $keyword) = @_;
418 if (my $around = $self->colormap->{lc $keyword}) {
419 $keyword = "$around->[0]$keyword$around->[1]";
433 my ($self, $keyword, $depth) = @_;
436 if (defined $self->indentmap->{lc $keyword}) {
437 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
439 $before = '' if $depth == 0 and defined $starters{lc $keyword};
440 return [$before, ''];
443 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
446 my ($self, $tree) = @_;
447 $tree = $tree->[0] while ref $tree;
449 defined $tree && defined $self->indentmap->{lc $tree};
452 sub fill_in_placeholder {
453 my ($self, $bindargs) = @_;
455 if ($self->fill_in_placeholders) {
456 my $val = shift @{$bindargs} || '';
457 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
458 my ($left, $right) = @{$self->placeholder_surround};
461 $val = qq('$val') if $quoted;
462 return qq($left$val$right)
467 # FIXME - terrible name for a user facing API
469 my ($self, $tree, $bindargs) = @_;
470 $self->_unparse($tree, [@{$bindargs||[]}], 0);
474 my ($self, $tree, $bindargs, $depth) = @_;
476 if (not $tree or not @$tree) {
480 # FIXME - needs a config switch to disable
481 $self->_parenthesis_unroll($tree);
483 my ($car, $cdr) = @{$tree}[0,1];
485 if (! defined $car or (! ref $car and ! defined $cdr) ) {
486 require Data::Dumper;
487 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
488 Data::Dumper::Dumper($tree)
493 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
495 elsif ($car eq 'LITERAL') {
498 elsif ($car eq 'PLACEHOLDER') {
499 return $self->fill_in_placeholder($bindargs);
501 elsif ($car eq 'PAREN') {
502 return sprintf ('( %s )',
503 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
505 ($self->_is_key($cdr)
506 ? ( $self->newline||'' ) . $self->indent($depth + 1)
511 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
512 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
514 elsif ($car eq 'LIST' ) {
515 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
518 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
520 return sprintf "$l%s%s%s$r",
521 $self->format_keyword($car),
522 ( ref $cdr eq 'ARRAY' and ref $cdr->[0] eq 'ARRAY' and $cdr->[0][0] and $cdr->[0][0] eq 'PAREN' )
526 $self->_unparse($cdr, $bindargs, $depth),
531 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
532 my @unrollable_ops = (
540 my $unrollable_ops_re = join ' | ', @unrollable_ops;
541 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
543 sub _parenthesis_unroll {
547 return unless (ref $ast and ref $ast->[1]);
554 for my $child (@{$ast->[1]}) {
556 # the current node in this loop is *always* a PAREN
557 if (! ref $child or ! @$child or $child->[0] ne 'PAREN') {
558 push @children, $child;
562 # unroll nested parenthesis
563 while ( @{$child->[1]} && $child->[1][0][0] eq 'PAREN') {
564 $child = $child->[1][0];
568 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
570 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
572 $child->[1][0][0] eq $ast->[0]
574 push @children, @{$child->[1][0][1]};
578 # if the parent operator explcitly allows it nuke the parenthesis
579 elsif ( $ast->[0] =~ $unrollable_ops_re ) {
580 push @children, $child->[1][0];
584 # only *ONE* LITERAL or placeholder element
585 # as an AND/OR/NOT argument
587 @{$child->[1]} == 1 && (
588 $child->[1][0][0] eq 'LITERAL'
590 $child->[1][0][0] eq 'PLACEHOLDER'
592 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
595 push @children, $child->[1][0];
599 # an AND/OR expression with only one binop in the parenthesis
600 # with exactly two grandchildren
601 # the only time when we can *not* unroll this is when both
602 # the parent and the child are mathops (in which case we'll
603 # break precedence) or when the child is BETWEEN (special
608 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
610 $child->[1][0][0] =~ SQL::Abstract::Tree::_binary_op_re()
612 $child->[1][0][0] ne 'BETWEEN'
614 @{$child->[1][0][1]} == 2
617 $child->[1][0][0] =~ SQL::Abstract::Tree::_math_op_re()
619 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
622 push @children, $child->[1][0];
626 # a function binds tighter than a mathop - see if our ancestor is a
627 # mathop, and our content is:
628 # a single non-mathop child with a single PAREN grandchild which
629 # would indicate mathop ( nonmathop ( ... ) )
630 # or a single non-mathop with a single LITERAL ( nonmathop foo )
631 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
635 @{$child->[1][0][1]} == 1
637 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
639 $child->[1][0][0] !~ SQL::Abstract::Tree::_math_op_re
642 $child->[1][0][1][0][0] eq 'PAREN'
644 $child->[1][0][1][0][0] eq 'LITERAL'
646 $child->[1][0][1][0][0] eq 'PLACEHOLDER'
649 push @children, $child->[1][0];
654 # otherwise no more mucking for this pass
656 push @children, $child;
660 $ast->[1] = \@children;
666 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
674 SQL::Abstract::Tree - Represent SQL as an AST
678 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
680 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
690 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
693 profile => 'console', # predefined profile to use (default: 'none')
694 fill_in_placeholders => 1, # true for placeholder population
695 placeholder_surround => # The strings that will be wrapped around
696 [GREEN, RESET], # populated placeholders if the above is set
697 indent_string => ' ', # the string used when indenting
698 indent_amount => 2, # how many of above string to use for a single
700 newline => "\n", # string for newline
702 select => [RED, RESET], # a pair of strings defining what to surround
703 # the keyword with for colorization
707 select => 0, # A zero means that the keyword will start on
709 from => 1, # Any other positive integer means that after
710 on => 2, # said newline it will get that many indents
715 Returns a new SQL::Abstract::Tree object. All arguments are optional.
719 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
720 and C<html>. Typically a user will probably just use C<console> or
721 C<console_monochrome>, but if something about a profile bothers you, merely
722 use the profile and override the parts that you don't like.
726 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
728 Takes C<$sql> and C<\@bindargs>.
730 Returns a formatting string based on the string passed in
734 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
736 Returns a "tree" representing passed in SQL. Please do not depend on the
737 structure of the returned tree. It may be stable at some point, but not yet.
741 $sqlat->parse($tree_structure, \@bindargs)
743 Transform "tree" into SQL, applying various transforms on the way.
745 =head2 format_keyword
747 $sqlat->format_keyword('SELECT')
749 Currently this just takes a keyword and puts the C<colormap> stuff around it.
750 Later on it may do more and allow for coderef based transforms.
754 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
756 Returns whitespace to be inserted around a keyword.
758 =head2 fill_in_placeholder
760 my $value = $sqlat->fill_in_placeholder(\@bindargs)
762 Removes last arg from passed arrayref and returns it, surrounded with
763 the values in placeholder_surround, and then surrounded with single quotes.
767 Returns as many indent strings as indent amounts times the first argument.
775 =head2 fill_in_placeholders
795 =head2 placeholder_surround