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',
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
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 ) $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 $all_known_re = join("\n\t|\n",
125 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
126 (map { quotemeta $_ } qw/, ( ) */),
130 $all_known_re = qr/$all_known_re/x;
132 #this one *is* capturing for the split below
133 # splits on whitespace if all else fails
134 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
136 # Parser states for _recurse_parse()
137 use constant PARSE_TOP_LEVEL => 0;
138 use constant PARSE_IN_EXPR => 1;
139 use constant PARSE_IN_PARENS => 2;
140 use constant PARSE_IN_FUNC => 3;
141 use constant PARSE_RHS => 4;
143 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
144 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
145 my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
171 fill_in_placeholders => 1,
172 placeholder_surround => ['?/', ''],
173 indent_string => ' ',
177 indentmap => \%indents,
179 eval { require Term::ANSIColor }
181 my $c = \&Term::ANSIColor::color;
183 my $red = [$c->('red') , $c->('reset')];
184 my $cyan = [$c->('cyan') , $c->('reset')];
185 my $green = [$c->('green') , $c->('reset')];
186 my $yellow = [$c->('yellow') , $c->('reset')];
187 my $blue = [$c->('blue') , $c->('reset')];
188 my $magenta = [$c->('magenta'), $c->('reset')];
189 my $b_o_w = [$c->('black on_white'), $c->('reset')];
191 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
193 'begin work' => $b_o_w,
197 'rollback to savepoint' => $b_o_w,
198 'release savepoint' => $b_o_w,
201 'insert into' => $red,
203 'delete from' => $red,
212 'left join' => $magenta,
215 'group by' => $yellow,
217 'order by' => $yellow,
227 console_monochrome => {
228 fill_in_placeholders => 1,
229 placeholder_surround => ['?/', ''],
230 indent_string => ' ',
234 indentmap => \%indents,
237 fill_in_placeholders => 1,
238 placeholder_surround => ['<span class="placeholder">', '</span>'],
239 indent_string => ' ',
241 newline => "<br />\n",
243 select => ['<span class="select">' , '</span>'],
244 'insert into' => ['<span class="insert-into">' , '</span>'],
245 update => ['<span class="select">' , '</span>'],
246 'delete from' => ['<span class="delete-from">' , '</span>'],
248 set => ['<span class="set">', '</span>'],
249 from => ['<span class="from">' , '</span>'],
251 where => ['<span class="where">' , '</span>'],
252 values => ['<span class="values">', '</span>'],
254 join => ['<span class="join">' , '</span>'],
255 'left join' => ['<span class="left-join">','</span>'],
256 on => ['<span class="on">' , '</span>'],
258 'group by' => ['<span class="group-by">', '</span>'],
259 having => ['<span class="having">', '</span>'],
260 'order by' => ['<span class="order-by">', '</span>'],
262 skip => ['<span class="skip">', '</span>'],
263 first => ['<span class="first">', '</span>'],
264 limit => ['<span class="limit">', '</span>'],
265 offset => ['<span class="offset">', '</span>'],
267 'begin work' => ['<span class="begin-work">', '</span>'],
268 commit => ['<span class="commit">', '</span>'],
269 rollback => ['<span class="rollback">', '</span>'],
270 savepoint => ['<span class="savepoint">', '</span>'],
271 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
272 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
274 indentmap => \%indents,
284 my $args = shift || {};
286 my $profile = delete $args->{profile} || 'none';
288 die "No such profile '$profile'!" unless exists $profiles{$profile};
290 my $data = $merger->merge( $profiles{$profile}, $args );
298 # tokenize string, and remove all optional whitespace
300 foreach my $token (split $tokenizer_re, $s) {
301 push @$tokens, $token if (
309 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
313 my ($self, $tokens, $state) = @_;
316 while (1) { # left-associative parsing
318 my $lookahead = $tokens->[0];
319 if ( not defined($lookahead)
321 ($state == PARSE_IN_PARENS && $lookahead eq ')')
323 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
325 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
327 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
332 my $token = shift @$tokens;
334 # nested expression in ()
335 if ($token eq '(' ) {
336 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
337 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
338 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
340 $left = $left ? [$left, [PAREN => [$right||()] ]]
341 : [PAREN => [$right||()] ];
343 # AND/OR and LIST (,)
344 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
345 my $op = ($token eq ',') ? 'LIST' : uc $token;
347 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
349 # Merge chunks if logic matches
350 if (ref $right and $op eq $right->[0]) {
351 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
354 $left = [$op => [ $left||(), $right||() ]];
357 # binary operator keywords
358 elsif ( $token =~ /^ $binary_op_re $ /x ) {
360 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
362 # A between with a simple LITERAL for a 1st RHS argument needs a
363 # rerun of the search to (hopefully) find the proper AND construct
364 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
365 unshift @$tokens, $right->[1][0];
366 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
369 $left = [$op => [$left, $right] ];
371 # expression terminator keywords (as they start a new expression)
372 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
374 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
375 $left = $left ? [ $left, [$op => [$right||()] ]]
376 : [ $op => [$right||()] ];
379 elsif ( $token =~ /^ NOT $/ix ) {
381 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
382 $left = $left ? [ @$left, [$op => [$right] ]]
383 : [ $op => [$right] ];
386 elsif ( $token =~ $placeholder_re) {
387 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
388 : [ PLACEHOLDER => [ $token ] ];
390 # we're now in "unknown token" land - start eating tokens until
391 # we see something familiar
395 # check if the current token is an unknown op-start
396 if (@$tokens and $tokens->[0] =~ $func_start_re) {
397 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
400 $right = [ LITERAL => [ $token ] ];
403 $left = $left ? [ $left, $right ]
410 my ($self, $keyword) = @_;
412 if (my $around = $self->colormap->{lc $keyword}) {
413 $keyword = "$around->[0]$keyword$around->[1]";
427 my ($self, $keyword, $depth) = @_;
430 if (defined $self->indentmap->{lc $keyword}) {
431 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
433 $before = '' if $depth == 0 and defined $starters{lc $keyword};
434 return [$before, ''];
437 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
440 my ($self, $tree) = @_;
441 $tree = $tree->[0] while ref $tree;
443 defined $tree && defined $self->indentmap->{lc $tree};
446 sub fill_in_placeholder {
447 my ($self, $bindargs) = @_;
449 if ($self->fill_in_placeholders) {
450 my $val = shift @{$bindargs} || '';
451 $val =~ s/^(')(.*)(')$/$2/;
452 my ($lquo, $rquo) = ($1 || '', $3 || '');
453 my ($left, $right) = @{$self->placeholder_surround};
456 return qq($left$lquo$val$rquo$right)
461 # FIXME - terrible name for a user facing API
463 my ($self, $tree, $bindargs) = @_;
464 $self->_unparse($tree, [@{$bindargs||[]}], 0);
468 my ($self, $tree, $bindargs, $depth) = @_;
470 if (not $tree or not @$tree) {
474 my ($car, $cdr) = @{$tree}[0,1];
476 if (! defined $car or (! ref $car and ! defined $cdr) ) {
477 require Data::Dumper;
478 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
479 Data::Dumper::Dumper($tree)
484 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
486 elsif ($car eq 'LITERAL') {
489 elsif ($car eq 'PLACEHOLDER') {
490 return $self->fill_in_placeholder($bindargs);
492 elsif ($car eq 'PAREN') {
493 return sprintf ('( %s )',
494 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
496 ($self->_is_key($cdr)
497 ? ( $self->newline||'' ) . $self->indent($depth + 1)
502 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
503 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
505 elsif ($car eq 'LIST' ) {
506 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
509 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
511 return sprintf "$l%s%s%s$r",
512 $self->format_keyword($car),
513 ( ref $cdr eq 'ARRAY' and ref $cdr->[0] eq 'ARRAY' and $cdr->[0][0] and $cdr->[0][0] eq 'PAREN' )
517 $self->_unparse($cdr, $bindargs, $depth),
522 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
530 SQL::Abstract::Tree - Represent SQL as an AST
534 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
536 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
546 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
549 profile => 'console', # predefined profile to use (default: 'none')
550 fill_in_placeholders => 1, # true for placeholder population
551 placeholder_surround => # The strings that will be wrapped around
552 [GREEN, RESET], # populated placeholders if the above is set
553 indent_string => ' ', # the string used when indenting
554 indent_amount => 2, # how many of above string to use for a single
556 newline => "\n", # string for newline
558 select => [RED, RESET], # a pair of strings defining what to surround
559 # the keyword with for colorization
563 select => 0, # A zero means that the keyword will start on
565 from => 1, # Any other positive integer means that after
566 on => 2, # said newline it will get that many indents
571 Returns a new SQL::Abstract::Tree object. All arguments are optional.
575 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
576 and C<html>. Typically a user will probably just use C<console> or
577 C<console_monochrome>, but if something about a profile bothers you, merely
578 use the profile and override the parts that you don't like.
582 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
584 Takes C<$sql> and C<\@bindargs>.
586 Returns a formatting string based on the string passed in
590 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
592 Returns a "tree" representing passed in SQL. Please do not depend on the
593 structure of the returned tree. It may be stable at some point, but not yet.
597 $sqlat->parse($tree_structure, \@bindargs)
599 Transform "tree" into SQL, applying various transforms on the way.
601 =head2 format_keyword
603 $sqlat->format_keyword('SELECT')
605 Currently this just takes a keyword and puts the C<colormap> stuff around it.
606 Later on it may do more and allow for coderef based transforms.
610 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
612 Returns whitespace to be inserted around a keyword.
614 =head2 fill_in_placeholder
616 my $value = $sqlat->fill_in_placeholder(\@bindargs)
618 Removes last arg from passed arrayref and returns it, surrounded with
619 the values in placeholder_surround, and then surrounded with single quotes.
623 Returns as many indent strings as indent amounts times the first argument.
631 =head2 fill_in_placeholders
651 =head2 placeholder_surround