1 package SQL::Abstract::Tree;
9 use base 'Class::Accessor::Grouped';
11 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
12 newline indent_string indent_amount colormap indentmap fill_in_placeholders
16 my $merger = Hash::Merge->new;
18 $merger->specify_behavior({
20 SCALAR => sub { $_[1] },
21 ARRAY => sub { [ $_[0], @{$_[1]} ] },
22 HASH => sub { $_[1] },
25 SCALAR => sub { $_[1] },
26 ARRAY => sub { $_[1] },
27 HASH => sub { $_[1] },
30 SCALAR => sub { $_[1] },
31 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
32 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
34 }, 'SQLA::Tree Behavior' );
37 # Parser states for _recurse_parse()
38 use constant PARSE_TOP_LEVEL => 0;
39 use constant PARSE_IN_EXPR => 1;
40 use constant PARSE_IN_PARENS => 2;
41 use constant PARSE_RHS => 3;
42 use constant PARSE_IN_FUNC => 4;
44 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
45 my $op_look_behind = '(?: (?<= [\s\)\(] ) | \A )';
46 my $quote_left = qr/[\`\'\"\[]/;
47 my $quote_right = qr/[\`\'\"\]]/;
49 # These SQL keywords always signal end of the current expression (except inside
50 # of a parenthesized subexpression).
51 # Format: A list of strings that will be compiled to extended syntax ie.
52 # /.../x) regexes, without capturing parentheses. They will be automatically
53 # anchored to op boundaries (excluding quotes) to match the whole token.
54 my @expression_start_keywords = (
63 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
64 (?: (?: CROSS | INNER | OUTER ) \s+ )?
82 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
85 my $exp_start_re = join ("\n\t|\n", @expression_start_keywords );
86 $exp_start_re = qr/ $op_look_behind (?i: $exp_start_re ) $op_look_ahead /x;
88 # These are binary operator keywords always a single LHS and RHS
89 # * AND/OR are handled separately as they are N-ary
90 # * so is NOT as being unary
91 # * BETWEEN without paranthesis around the ANDed arguments (which
92 # makes it a non-binary op) is detected and accomodated in
95 # this will be included in the $binary_op_re, the distinction is interesting during
96 # testing as one is tighter than the other, plus mathops have different look
97 # ahead/behind (e.g. "x"="y" )
98 my @math_op_keywords = (qw/ < > != <> = <= >= /);
99 my $math_re = join ("\n\t|\n", map
100 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
103 $math_re = qr/$math_re/x;
105 sub _math_op_re { $math_re }
108 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
109 $binary_op_re = "(?: $op_look_behind (?i: $binary_op_re ) $op_look_ahead ) \n\t|\n $math_re";
110 $binary_op_re = qr/$binary_op_re/x;
112 sub _binary_op_re { $binary_op_re }
115 my $tokenizer_re = join("\n\t|\n",
118 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
119 (map { quotemeta $_ } qw/( ) ? */),
122 #this one *is* capturing
123 $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* /x;
144 fill_in_placeholders => 1,
145 placeholder_surround => ['?/', ''],
146 indent_string => ' ',
150 indentmap => { %indents },
152 eval { require Term::ANSIColor }
154 my $c = \&Term::ANSIColor::color;
156 placeholder_surround => [$c->('black on_cyan'), $c->('reset')],
158 select => [$c->('red'), $c->('reset')],
159 'insert into' => [$c->('red'), $c->('reset')],
160 update => [$c->('red'), $c->('reset')],
161 'delete from' => [$c->('red'), $c->('reset')],
163 set => [$c->('cyan'), $c->('reset')],
164 from => [$c->('cyan'), $c->('reset')],
166 where => [$c->('green'), $c->('reset')],
167 values => [$c->('yellow'), $c->('reset')],
169 join => [$c->('magenta'), $c->('reset')],
170 'left join' => [$c->('magenta'), $c->('reset')],
171 on => [$c->('blue'), $c->('reset')],
173 'group by' => [$c->('yellow'), $c->('reset')],
174 'order by' => [$c->('yellow'), $c->('reset')],
179 console_monochrome => {
180 fill_in_placeholders => 1,
181 placeholder_surround => ['?/', ''],
182 indent_string => ' ',
186 indentmap => { %indents },
189 fill_in_placeholders => 1,
190 placeholder_surround => ['<span class="placeholder">', '</span>'],
191 indent_string => ' ',
193 newline => "<br />\n",
195 select => ['<span class="select">' , '</span>'],
196 'insert into' => ['<span class="insert-into">' , '</span>'],
197 update => ['<span class="select">' , '</span>'],
198 'delete from' => ['<span class="delete-from">' , '</span>'],
199 where => ['<span class="where">' , '</span>'],
200 from => ['<span class="from">' , '</span>'],
201 join => ['<span class="join">' , '</span>'],
202 on => ['<span class="on">' , '</span>'],
203 'group by' => ['<span class="group-by">', '</span>'],
204 'order by' => ['<span class="order-by">', '</span>'],
205 set => ['<span class="set">', '</span>'],
206 into => ['<span class="into">', '</span>'],
207 values => ['<span class="values">', '</span>'],
209 indentmap => { %indents },
219 my $args = shift || {};
221 my $profile = delete $args->{profile} || 'none';
222 my $data = $merger->merge( $profiles{$profile}, $args );
230 # tokenize string, and remove all optional whitespace
232 foreach my $token (split $tokenizer_re, $s) {
233 push @$tokens, $token if (length $token) && ($token =~ /\S/);
236 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
241 my ($self, $tokens, $state) = @_;
244 while (1) { # left-associative parsing
246 my $lookahead = $tokens->[0];
247 if ( not defined($lookahead)
249 ($state == PARSE_IN_PARENS && $lookahead eq ')')
251 ($state == PARSE_IN_EXPR && $lookahead =~ qr/ ^ (?: $exp_start_re | \) ) $ /x )
253 ($state == PARSE_RHS && $lookahead =~ qr/ ^ (?: $exp_start_re | $binary_op_re | (?i: AND | OR | NOT ) | \) ) $ /x )
255 ($state == PARSE_IN_FUNC && $lookahead ne '(')
260 my $token = shift @$tokens;
262 # nested expression in ()
263 if ($token eq '(' ) {
264 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
265 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
266 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
268 $left = $left ? [$left, [PAREN => [$right||()] ]]
269 : [PAREN => [$right||()] ];
272 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
274 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
276 # Merge chunks if logic matches
277 if (ref $right and $op eq $right->[0]) {
278 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
281 $left = [$op => [$left, $right]];
284 # binary operator keywords
285 elsif ( $token =~ /^ $binary_op_re $ /x ) {
287 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
289 # A between with a simple LITERAL for a 1st RHS argument needs a
290 # rerun of the search to (hopefully) find the proper AND construct
291 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
292 unshift @$tokens, $right->[1][0];
293 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
296 $left = [$op => [$left, $right] ];
298 # expression terminator keywords (as they start a new expression)
299 elsif ( $token =~ / ^ $exp_start_re $ /x ) {
301 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
302 $left = $left ? [ $left, [$op => [$right] ]]
303 : [ $op => [$right] ];
306 elsif ( $token =~ /^ NOT $/ix ) {
308 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
309 $left = $left ? [ @$left, [$op => [$right] ]]
310 : [ $op => [$right] ];
314 elsif (@$tokens && $tokens->[0] eq '(') {
315 my $right = $self->_recurse_parse($tokens, PARSE_IN_FUNC);
317 $left = $left ? [ $left, [ $token => [$right||()] ]]
318 : [ $token => [$right||()] ];
320 # literal (eat everything on the right until RHS termination)
322 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
323 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
324 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
330 my ($self, $keyword) = @_;
332 if (my $around = $self->colormap->{lc $keyword}) {
333 $keyword = "$around->[0]$keyword$around->[1]";
347 my ($self, $keyword, $depth) = @_;
350 if (defined $self->indentmap->{lc $keyword}) {
351 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
353 $before = '' if $depth == 0 and defined $starters{lc $keyword};
354 return [$before, ' '];
357 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
360 my ($self, $tree) = @_;
361 $tree = $tree->[0] while ref $tree;
363 defined $tree && defined $self->indentmap->{lc $tree};
366 sub fill_in_placeholder {
367 my ($self, $bindargs) = @_;
369 if ($self->fill_in_placeholders) {
370 my $val = shift @{$bindargs} || '';
371 my ($left, $right) = @{$self->placeholder_surround};
374 return qq($left$val$right)
380 my ($self, $tree, $bindargs, $depth) = @_;
384 if (not $tree or not @$tree) {
388 my ($car, $cdr) = @{$tree}[0,1];
390 if (! defined $car or (! ref $car and ! defined $cdr) ) {
391 require Data::Dumper;
392 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
393 Data::Dumper::Dumper($tree)
398 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
400 elsif ($car eq 'LITERAL') {
401 if ($cdr->[0] eq '?') {
402 return $self->fill_in_placeholder($bindargs)
406 elsif ($car eq 'PAREN') {
409 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
410 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
412 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
413 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
416 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
417 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
421 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
429 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
431 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
441 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
444 profile => 'console', # predefined profile to use (default: 'none')
445 fill_in_placeholders => 1, # true for placeholder population
446 placeholder_surround => # The strings that will be wrapped around
447 [GREEN, RESET], # populated placeholders if the above is set
448 indent_string => ' ', # the string used when indenting
449 indent_amount => 2, # how many of above string to use for a single
451 newline => "\n", # string for newline
453 select => [RED, RESET], # a pair of strings defining what to surround
454 # the keyword with for colorization
458 select => 0, # A zero means that the keyword will start on
460 from => 1, # Any other positive integer means that after
461 on => 2, # said newline it will get that many indents
466 Returns a new SQL::Abstract::Tree object. All arguments are optional.
470 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
471 and C<html>. Typically a user will probably just use C<console> or
472 C<console_monochrome>, but if something about a profile bothers you, merely
473 use the profile and override the parts that you don't like.
477 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
479 Takes C<$sql> and C<\@bindargs>.
481 Returns a formatting string based on the string passed in
485 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
487 Returns a "tree" representing passed in SQL. Please do not depend on the
488 structure of the returned tree. It may be stable at some point, but not yet.
492 $sqlat->parse($tree_structure, \@bindargs)
494 Transform "tree" into SQL, applying various transforms on the way.
496 =head2 format_keyword
498 $sqlat->format_keyword('SELECT')
500 Currently this just takes a keyword and puts the C<colormap> stuff around it.
501 Later on it may do more and allow for coderef based transforms.
505 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
507 Returns whitespace to be inserted around a keyword.
509 =head2 fill_in_placeholder
511 my $value = $sqlat->fill_in_placeholder(\@bindargs)
513 Removes last arg from passed arrayref and returns it, surrounded with
514 the values in placeholder_surround, and then surrounded with single quotes.
518 Returns as many indent strings as indent amounts times the first argument.
526 =head2 fill_in_placeholders
546 =head2 placeholder_surround