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+ )?
78 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
81 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
82 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
84 # These are binary operator keywords always a single LHS and RHS
85 # * AND/OR are handled separately as they are N-ary
86 # * so is NOT as being unary
87 # * BETWEEN without paranthesis around the ANDed arguments (which
88 # makes it a non-binary op) is detected and accomodated in
91 # this will be included in the $binary_op_re, the distinction is interesting during
92 # testing as one is tighter than the other, plus mathops have different look
93 # ahead/behind (e.g. "x"="y" )
94 my @math_op_keywords = (qw/ < > != <> = <= >= /);
95 my $math_re = join ("\n\t|\n", map
96 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
99 $math_re = qr/$math_re/x;
101 sub _math_op_re { $math_re }
104 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
105 $binary_op_re = join "\n\t|\n",
106 "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
108 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
110 $binary_op_re = qr/$binary_op_re/x;
112 sub _binary_op_re { $binary_op_re }
114 my $all_known_re = join("\n\t|\n",
117 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
118 (map { quotemeta $_ } qw/, ( ) */),
122 $all_known_re = qr/$all_known_re/x;
124 #this one *is* capturing for the split below
125 # splits on whitespace if all else fails
126 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
128 # Parser states for _recurse_parse()
129 use constant PARSE_TOP_LEVEL => 0;
130 use constant PARSE_IN_EXPR => 1;
131 use constant PARSE_IN_PARENS => 2;
132 use constant PARSE_IN_FUNC => 3;
133 use constant PARSE_RHS => 4;
135 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
136 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
137 my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
158 fill_in_placeholders => 1,
159 placeholder_surround => ['?/', ''],
160 indent_string => ' ',
164 indentmap => { %indents },
166 eval { require Term::ANSIColor }
168 my $c = \&Term::ANSIColor::color;
170 placeholder_surround => [$c->('black on_cyan'), $c->('reset')],
172 select => [$c->('red'), $c->('reset')],
173 'insert into' => [$c->('red'), $c->('reset')],
174 update => [$c->('red'), $c->('reset')],
175 'delete from' => [$c->('red'), $c->('reset')],
177 set => [$c->('cyan'), $c->('reset')],
178 from => [$c->('cyan'), $c->('reset')],
180 where => [$c->('green'), $c->('reset')],
181 values => [$c->('yellow'), $c->('reset')],
183 join => [$c->('magenta'), $c->('reset')],
184 'left join' => [$c->('magenta'), $c->('reset')],
185 on => [$c->('blue'), $c->('reset')],
187 'group by' => [$c->('yellow'), $c->('reset')],
188 'order by' => [$c->('yellow'), $c->('reset')],
193 console_monochrome => {
194 fill_in_placeholders => 1,
195 placeholder_surround => ['?/', ''],
196 indent_string => ' ',
200 indentmap => { %indents },
203 fill_in_placeholders => 1,
204 placeholder_surround => ['<span class="placeholder">', '</span>'],
205 indent_string => ' ',
207 newline => "<br />\n",
209 select => ['<span class="select">' , '</span>'],
210 'insert into' => ['<span class="insert-into">' , '</span>'],
211 update => ['<span class="select">' , '</span>'],
212 'delete from' => ['<span class="delete-from">' , '</span>'],
213 where => ['<span class="where">' , '</span>'],
214 from => ['<span class="from">' , '</span>'],
215 join => ['<span class="join">' , '</span>'],
216 on => ['<span class="on">' , '</span>'],
217 'group by' => ['<span class="group-by">', '</span>'],
218 'order by' => ['<span class="order-by">', '</span>'],
219 set => ['<span class="set">', '</span>'],
220 into => ['<span class="into">', '</span>'],
221 values => ['<span class="values">', '</span>'],
223 indentmap => { %indents },
233 my $args = shift || {};
235 my $profile = delete $args->{profile} || 'none';
236 my $data = $merger->merge( $profiles{$profile}, $args );
244 # tokenize string, and remove all optional whitespace
246 foreach my $token (split $tokenizer_re, $s) {
247 push @$tokens, $token if (
255 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
259 my ($self, $tokens, $state) = @_;
262 while (1) { # left-associative parsing
264 my $lookahead = $tokens->[0];
265 if ( not defined($lookahead)
267 ($state == PARSE_IN_PARENS && $lookahead eq ')')
269 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
271 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
273 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
278 my $token = shift @$tokens;
280 # nested expression in ()
281 if ($token eq '(' ) {
282 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
283 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
284 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
286 $left = $left ? [$left, [PAREN => [$right||()] ]]
287 : [PAREN => [$right||()] ];
289 # AND/OR and LIST (,)
290 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
291 my $op = ($token eq ',') ? 'LIST' : uc $token;
293 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
295 # Merge chunks if logic matches
296 if (ref $right and $op eq $right->[0]) {
297 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
300 $left = [$op => [ $left||(), $right||() ]];
303 # binary operator keywords
304 elsif ( $token =~ /^ $binary_op_re $ /x ) {
306 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
308 # A between with a simple LITERAL for a 1st RHS argument needs a
309 # rerun of the search to (hopefully) find the proper AND construct
310 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
311 unshift @$tokens, $right->[1][0];
312 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
315 $left = [$op => [$left, $right] ];
317 # expression terminator keywords (as they start a new expression)
318 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
320 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
321 $left = $left ? [ $left, [$op => [$right] ]]
322 : [ $op => [$right] ];
325 elsif ( $token =~ /^ NOT $/ix ) {
327 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
328 $left = $left ? [ @$left, [$op => [$right] ]]
329 : [ $op => [$right] ];
332 elsif ( $token =~ $placeholder_re) {
333 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
334 : [ PLACEHOLDER => [ $token ] ];
336 # we're now in "unknown token" land - start eating tokens until
337 # we see something familiar
341 # check if the current token is an unknown op-start
342 if (@$tokens and $tokens->[0] =~ $func_start_re) {
343 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
346 $right = [ LITERAL => [ $token ] ];
349 $left = $left ? [ $left, $right ]
356 my ($self, $keyword) = @_;
358 if (my $around = $self->colormap->{lc $keyword}) {
359 $keyword = "$around->[0]$keyword$around->[1]";
373 my ($self, $keyword, $depth) = @_;
376 if (defined $self->indentmap->{lc $keyword}) {
377 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
379 $before = '' if $depth == 0 and defined $starters{lc $keyword};
380 return [$before, ' '];
383 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
386 my ($self, $tree) = @_;
387 $tree = $tree->[0] while ref $tree;
389 defined $tree && defined $self->indentmap->{lc $tree};
392 sub fill_in_placeholder {
393 my ($self, $bindargs) = @_;
395 if ($self->fill_in_placeholders) {
396 my $val = shift @{$bindargs} || '';
397 my ($left, $right) = @{$self->placeholder_surround};
400 return qq($left$val$right)
405 # FIXME - terrible name for a user facing API
407 my ($self, $tree, $bindargs) = @_;
408 $self->_unparse($tree, [@{$bindargs||[]}], 0);
412 my ($self, $tree, $bindargs, $depth) = @_;
414 if (not $tree or not @$tree) {
418 my ($car, $cdr) = @{$tree}[0,1];
420 if (! defined $car or (! ref $car and ! defined $cdr) ) {
421 require Data::Dumper;
422 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
423 Data::Dumper::Dumper($tree)
428 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
430 elsif ($car eq 'LITERAL') {
433 elsif ($car eq 'PLACEHOLDER') {
434 return $self->fill_in_placeholder($bindargs);
436 elsif ($car eq 'PAREN') {
439 map $self->_unparse($_, $bindargs, $depth + 2), @{$cdr}) .
440 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
442 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
443 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
445 elsif ($car eq 'LIST' ) {
446 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
449 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
450 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->_unparse($cdr, $bindargs, $depth);
454 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
462 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
464 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
474 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
477 profile => 'console', # predefined profile to use (default: 'none')
478 fill_in_placeholders => 1, # true for placeholder population
479 placeholder_surround => # The strings that will be wrapped around
480 [GREEN, RESET], # populated placeholders if the above is set
481 indent_string => ' ', # the string used when indenting
482 indent_amount => 2, # how many of above string to use for a single
484 newline => "\n", # string for newline
486 select => [RED, RESET], # a pair of strings defining what to surround
487 # the keyword with for colorization
491 select => 0, # A zero means that the keyword will start on
493 from => 1, # Any other positive integer means that after
494 on => 2, # said newline it will get that many indents
499 Returns a new SQL::Abstract::Tree object. All arguments are optional.
503 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
504 and C<html>. Typically a user will probably just use C<console> or
505 C<console_monochrome>, but if something about a profile bothers you, merely
506 use the profile and override the parts that you don't like.
510 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
512 Takes C<$sql> and C<\@bindargs>.
514 Returns a formatting string based on the string passed in
518 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
520 Returns a "tree" representing passed in SQL. Please do not depend on the
521 structure of the returned tree. It may be stable at some point, but not yet.
525 $sqlat->parse($tree_structure, \@bindargs)
527 Transform "tree" into SQL, applying various transforms on the way.
529 =head2 format_keyword
531 $sqlat->format_keyword('SELECT')
533 Currently this just takes a keyword and puts the C<colormap> stuff around it.
534 Later on it may do more and allow for coderef based transforms.
538 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
540 Returns whitespace to be inserted around a keyword.
542 =head2 fill_in_placeholder
544 my $value = $sqlat->fill_in_placeholder(\@bindargs)
546 Removes last arg from passed arrayref and returns it, surrounded with
547 the values in placeholder_surround, and then surrounded with single quotes.
551 Returns as many indent strings as indent amounts times the first argument.
559 =head2 fill_in_placeholders
579 =head2 placeholder_surround