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 # These SQL keywords always signal end of the current expression (except inside
44 # of a parenthesized subexpression).
45 # Format: A list of strings that will be compiled to extended syntax ie.
46 # /.../x) regexes, without capturing parentheses. They will be automatically
47 # anchored to op boundaries (excluding quotes) to match the whole token.
48 my @expression_start_keywords = (
57 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
58 (?: (?: CROSS | INNER | OUTER ) \s+ )?
76 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
79 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
80 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
82 # These are binary operator keywords always a single LHS and RHS
83 # * AND/OR are handled separately as they are N-ary
84 # * so is NOT as being unary
85 # * BETWEEN without paranthesis around the ANDed arguments (which
86 # makes it a non-binary op) is detected and accomodated in
89 # this will be included in the $binary_op_re, the distinction is interesting during
90 # testing as one is tighter than the other, plus mathops have different look
91 # ahead/behind (e.g. "x"="y" )
92 my @math_op_keywords = (qw/ < > != <> = <= >= /);
93 my $math_re = join ("\n\t|\n", map
94 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
97 $math_re = qr/$math_re/x;
99 sub _math_op_re { $math_re }
102 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
103 $binary_op_re = join "\n\t|\n",
104 "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
106 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
108 $binary_op_re = qr/$binary_op_re/x;
110 sub _binary_op_re { $binary_op_re }
112 my $all_known_re = join("\n\t|\n",
115 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
116 (map { quotemeta $_ } qw/, ( ) */),
119 $all_known_re = qr/$all_known_re/x;
121 #this one *is* capturing for the split below
122 # splits on whitespace if all else fails
123 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
125 # Parser states for _recurse_parse()
126 use constant PARSE_TOP_LEVEL => 0;
127 use constant PARSE_IN_EXPR => 1;
128 use constant PARSE_IN_PARENS => 2;
129 use constant PARSE_IN_FUNC => 3;
130 use constant PARSE_RHS => 4;
132 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
133 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
134 my $func_start_re = qr/^ (?: \? | \$\d+ | \( ) $/x;
155 fill_in_placeholders => 1,
156 placeholder_surround => ['?/', ''],
157 indent_string => ' ',
161 indentmap => { %indents },
163 eval { require Term::ANSIColor }
165 my $c = \&Term::ANSIColor::color;
167 placeholder_surround => [$c->('black on_cyan'), $c->('reset')],
169 select => [$c->('red'), $c->('reset')],
170 'insert into' => [$c->('red'), $c->('reset')],
171 update => [$c->('red'), $c->('reset')],
172 'delete from' => [$c->('red'), $c->('reset')],
174 set => [$c->('cyan'), $c->('reset')],
175 from => [$c->('cyan'), $c->('reset')],
177 where => [$c->('green'), $c->('reset')],
178 values => [$c->('yellow'), $c->('reset')],
180 join => [$c->('magenta'), $c->('reset')],
181 'left join' => [$c->('magenta'), $c->('reset')],
182 on => [$c->('blue'), $c->('reset')],
184 'group by' => [$c->('yellow'), $c->('reset')],
185 'order by' => [$c->('yellow'), $c->('reset')],
190 console_monochrome => {
191 fill_in_placeholders => 1,
192 placeholder_surround => ['?/', ''],
193 indent_string => ' ',
197 indentmap => { %indents },
200 fill_in_placeholders => 1,
201 placeholder_surround => ['<span class="placeholder">', '</span>'],
202 indent_string => ' ',
204 newline => "<br />\n",
206 select => ['<span class="select">' , '</span>'],
207 'insert into' => ['<span class="insert-into">' , '</span>'],
208 update => ['<span class="select">' , '</span>'],
209 'delete from' => ['<span class="delete-from">' , '</span>'],
210 where => ['<span class="where">' , '</span>'],
211 from => ['<span class="from">' , '</span>'],
212 join => ['<span class="join">' , '</span>'],
213 on => ['<span class="on">' , '</span>'],
214 'group by' => ['<span class="group-by">', '</span>'],
215 'order by' => ['<span class="order-by">', '</span>'],
216 set => ['<span class="set">', '</span>'],
217 into => ['<span class="into">', '</span>'],
218 values => ['<span class="values">', '</span>'],
220 indentmap => { %indents },
230 my $args = shift || {};
232 my $profile = delete $args->{profile} || 'none';
233 my $data = $merger->merge( $profiles{$profile}, $args );
241 # tokenize string, and remove all optional whitespace
243 foreach my $token (split $tokenizer_re, $s) {
244 push @$tokens, $token if (
252 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
256 my ($self, $tokens, $state) = @_;
259 while (1) { # left-associative parsing
261 my $lookahead = $tokens->[0];
262 if ( not defined($lookahead)
264 ($state == PARSE_IN_PARENS && $lookahead eq ')')
266 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
268 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
270 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
275 my $token = shift @$tokens;
277 # nested expression in ()
278 if ($token eq '(' ) {
279 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
280 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
281 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
283 $left = $left ? [$left, [PAREN => [$right||()] ]]
284 : [PAREN => [$right||()] ];
286 # AND/OR and LIST (,)
287 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
288 my $op = ($token eq ',') ? 'LIST' : uc $token;
290 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
292 # Merge chunks if logic matches
293 if (ref $right and $op eq $right->[0]) {
294 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
297 $left = [$op => [ $left||(), $right||() ]];
300 # binary operator keywords
301 elsif ( $token =~ /^ $binary_op_re $ /x ) {
303 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
305 # A between with a simple LITERAL for a 1st RHS argument needs a
306 # rerun of the search to (hopefully) find the proper AND construct
307 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
308 unshift @$tokens, $right->[1][0];
309 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
312 $left = [$op => [$left, $right] ];
314 # expression terminator keywords (as they start a new expression)
315 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
317 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
318 $left = $left ? [ $left, [$op => [$right] ]]
319 : [ $op => [$right] ];
322 elsif ( $token =~ /^ NOT $/ix ) {
324 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
325 $left = $left ? [ @$left, [$op => [$right] ]]
326 : [ $op => [$right] ];
329 # we're now in "unknown token" land - start eating tokens until
330 # we see something familiar
334 # check if the current token is an unknown op-start
335 if (@$tokens and $tokens->[0] =~ $func_start_re) {
336 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
339 $right = [ LITERAL => [ $token ] ];
342 $left = $left ? [ $left, $right ]
349 my ($self, $keyword) = @_;
351 if (my $around = $self->colormap->{lc $keyword}) {
352 $keyword = "$around->[0]$keyword$around->[1]";
366 my ($self, $keyword, $depth) = @_;
369 if (defined $self->indentmap->{lc $keyword}) {
370 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
372 $before = '' if $depth == 0 and defined $starters{lc $keyword};
373 return [$before, ' '];
376 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
379 my ($self, $tree) = @_;
380 $tree = $tree->[0] while ref $tree;
382 defined $tree && defined $self->indentmap->{lc $tree};
385 sub fill_in_placeholder {
386 my ($self, $bindargs) = @_;
388 if ($self->fill_in_placeholders) {
389 my $val = shift @{$bindargs} || '';
390 my ($left, $right) = @{$self->placeholder_surround};
393 return qq($left$val$right)
398 # FIXME - terrible name for a user facing API
400 my ($self, $tree, $bindargs) = @_;
401 $self->_unparse($tree, [@{$bindargs||[]}], 0);
405 my ($self, $tree, $bindargs, $depth) = @_;
407 if (not $tree or not @$tree) {
411 my ($car, $cdr) = @{$tree}[0,1];
413 if (! defined $car or (! ref $car and ! defined $cdr) ) {
414 require Data::Dumper;
415 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
416 Data::Dumper::Dumper($tree)
421 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
423 elsif ($car eq 'LITERAL') {
424 if ($cdr->[0] eq '?') {
425 return $self->fill_in_placeholder($bindargs)
429 elsif ($car eq 'PAREN') {
432 map $self->_unparse($_, $bindargs, $depth + 2), @{$cdr}) .
433 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
435 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
436 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
438 elsif ($car eq 'LIST' ) {
439 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
442 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
443 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->_unparse($cdr, $bindargs, $depth);
447 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
455 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
457 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
467 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
470 profile => 'console', # predefined profile to use (default: 'none')
471 fill_in_placeholders => 1, # true for placeholder population
472 placeholder_surround => # The strings that will be wrapped around
473 [GREEN, RESET], # populated placeholders if the above is set
474 indent_string => ' ', # the string used when indenting
475 indent_amount => 2, # how many of above string to use for a single
477 newline => "\n", # string for newline
479 select => [RED, RESET], # a pair of strings defining what to surround
480 # the keyword with for colorization
484 select => 0, # A zero means that the keyword will start on
486 from => 1, # Any other positive integer means that after
487 on => 2, # said newline it will get that many indents
492 Returns a new SQL::Abstract::Tree object. All arguments are optional.
496 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
497 and C<html>. Typically a user will probably just use C<console> or
498 C<console_monochrome>, but if something about a profile bothers you, merely
499 use the profile and override the parts that you don't like.
503 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
505 Takes C<$sql> and C<\@bindargs>.
507 Returns a formatting string based on the string passed in
511 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
513 Returns a "tree" representing passed in SQL. Please do not depend on the
514 structure of the returned tree. It may be stable at some point, but not yet.
518 $sqlat->parse($tree_structure, \@bindargs)
520 Transform "tree" into SQL, applying various transforms on the way.
522 =head2 format_keyword
524 $sqlat->format_keyword('SELECT')
526 Currently this just takes a keyword and puts the C<colormap> stuff around it.
527 Later on it may do more and allow for coderef based transforms.
531 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
533 Returns whitespace to be inserted around a keyword.
535 =head2 fill_in_placeholder
537 my $value = $sqlat->fill_in_placeholder(\@bindargs)
539 Removes last arg from passed arrayref and returns it, surrounded with
540 the values in placeholder_surround, and then surrounded with single quotes.
544 Returns as many indent strings as indent amounts times the first argument.
552 =head2 fill_in_placeholders
572 =head2 placeholder_surround