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',
80 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
83 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
84 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
86 # These are binary operator keywords always a single LHS and RHS
87 # * AND/OR are handled separately as they are N-ary
88 # * so is NOT as being unary
89 # * BETWEEN without paranthesis around the ANDed arguments (which
90 # makes it a non-binary op) is detected and accomodated in
93 # this will be included in the $binary_op_re, the distinction is interesting during
94 # testing as one is tighter than the other, plus mathops have different look
95 # ahead/behind (e.g. "x"="y" )
96 my @math_op_keywords = (qw/ < > != <> = <= >= /);
97 my $math_re = join ("\n\t|\n", map
98 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
101 $math_re = qr/$math_re/x;
103 sub _math_op_re { $math_re }
106 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
107 $binary_op_re = join "\n\t|\n",
108 "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
110 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
112 $binary_op_re = qr/$binary_op_re/x;
114 sub _binary_op_re { $binary_op_re }
116 my $all_known_re = join("\n\t|\n",
119 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
120 (map { quotemeta $_ } qw/, ( ) */),
124 $all_known_re = qr/$all_known_re/x;
126 #this one *is* capturing for the split below
127 # splits on whitespace if all else fails
128 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
130 # Parser states for _recurse_parse()
131 use constant PARSE_TOP_LEVEL => 0;
132 use constant PARSE_IN_EXPR => 1;
133 use constant PARSE_IN_PARENS => 2;
134 use constant PARSE_IN_FUNC => 3;
135 use constant PARSE_RHS => 4;
137 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
138 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
139 my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
164 fill_in_placeholders => 1,
165 placeholder_surround => ['?/', ''],
166 indent_string => ' ',
170 indentmap => { %indents },
172 eval { require Term::ANSIColor }
174 my $c = \&Term::ANSIColor::color;
176 placeholder_surround => [q(') . $c->('black on_magenta'), $c->('reset') . q(')],
178 select => [$c->('red'), $c->('reset')],
179 'insert into' => [$c->('red'), $c->('reset')],
180 update => [$c->('red'), $c->('reset')],
181 'delete from' => [$c->('red'), $c->('reset')],
183 set => [$c->('cyan'), $c->('reset')],
184 from => [$c->('cyan'), $c->('reset')],
186 where => [$c->('green'), $c->('reset')],
187 values => [$c->('yellow'), $c->('reset')],
189 join => [$c->('magenta'), $c->('reset')],
190 'left join' => [$c->('magenta'), $c->('reset')],
191 on => [$c->('blue'), $c->('reset')],
193 'group by' => [$c->('yellow'), $c->('reset')],
194 'order by' => [$c->('yellow'), $c->('reset')],
196 skip => [$c->('green'), $c->('reset')],
197 first => [$c->('green'), $c->('reset')],
198 limit => [$c->('green'), $c->('reset')],
199 offset => [$c->('green'), $c->('reset')],
204 console_monochrome => {
205 fill_in_placeholders => 1,
206 placeholder_surround => ['?/', ''],
207 indent_string => ' ',
211 indentmap => { %indents },
214 fill_in_placeholders => 1,
215 placeholder_surround => ['<span class="placeholder">', '</span>'],
216 indent_string => ' ',
218 newline => "<br />\n",
220 select => ['<span class="select">' , '</span>'],
221 'insert into' => ['<span class="insert-into">' , '</span>'],
222 update => ['<span class="select">' , '</span>'],
223 'delete from' => ['<span class="delete-from">' , '</span>'],
225 set => ['<span class="set">', '</span>'],
226 from => ['<span class="from">' , '</span>'],
228 where => ['<span class="where">' , '</span>'],
229 values => ['<span class="values">', '</span>'],
231 join => ['<span class="join">' , '</span>'],
232 'left join' => ['<span class="left-join">','</span>'],
233 on => ['<span class="on">' , '</span>'],
235 'group by' => ['<span class="group-by">', '</span>'],
236 'order by' => ['<span class="order-by">', '</span>'],
238 skip => ['<span class="skip">', '</span>'],
239 first => ['<span class="first">', '</span>'],
240 limit => ['<span class="limit">', '</span>'],
241 offset => ['<span class="offset">', '</span>'],
243 indentmap => { %indents },
253 my $args = shift || {};
255 my $profile = delete $args->{profile} || 'none';
256 my $data = $merger->merge( $profiles{$profile}, $args );
264 # tokenize string, and remove all optional whitespace
266 foreach my $token (split $tokenizer_re, $s) {
267 push @$tokens, $token if (
275 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
279 my ($self, $tokens, $state) = @_;
282 while (1) { # left-associative parsing
284 my $lookahead = $tokens->[0];
285 if ( not defined($lookahead)
287 ($state == PARSE_IN_PARENS && $lookahead eq ')')
289 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
291 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
293 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
298 my $token = shift @$tokens;
300 # nested expression in ()
301 if ($token eq '(' ) {
302 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
303 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
304 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
306 $left = $left ? [$left, [PAREN => [$right||()] ]]
307 : [PAREN => [$right||()] ];
309 # AND/OR and LIST (,)
310 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
311 my $op = ($token eq ',') ? 'LIST' : uc $token;
313 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
315 # Merge chunks if logic matches
316 if (ref $right and $op eq $right->[0]) {
317 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
320 $left = [$op => [ $left||(), $right||() ]];
323 # binary operator keywords
324 elsif ( $token =~ /^ $binary_op_re $ /x ) {
326 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
328 # A between with a simple LITERAL for a 1st RHS argument needs a
329 # rerun of the search to (hopefully) find the proper AND construct
330 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
331 unshift @$tokens, $right->[1][0];
332 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
335 $left = [$op => [$left, $right] ];
337 # expression terminator keywords (as they start a new expression)
338 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
340 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
341 $left = $left ? [ $left, [$op => [$right||()] ]]
342 : [ $op => [$right||()] ];
345 elsif ( $token =~ /^ NOT $/ix ) {
347 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
348 $left = $left ? [ @$left, [$op => [$right] ]]
349 : [ $op => [$right] ];
352 elsif ( $token =~ $placeholder_re) {
353 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
354 : [ PLACEHOLDER => [ $token ] ];
356 # we're now in "unknown token" land - start eating tokens until
357 # we see something familiar
361 # check if the current token is an unknown op-start
362 if (@$tokens and $tokens->[0] =~ $func_start_re) {
363 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
366 $right = [ LITERAL => [ $token ] ];
369 $left = $left ? [ $left, $right ]
376 my ($self, $keyword) = @_;
378 if (my $around = $self->colormap->{lc $keyword}) {
379 $keyword = "$around->[0]$keyword$around->[1]";
393 my ($self, $keyword, $depth) = @_;
396 if (defined $self->indentmap->{lc $keyword}) {
397 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
399 $before = '' if $depth == 0 and defined $starters{lc $keyword};
400 return [$before, ''];
403 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
406 my ($self, $tree) = @_;
407 $tree = $tree->[0] while ref $tree;
409 defined $tree && defined $self->indentmap->{lc $tree};
412 sub fill_in_placeholder {
413 my ($self, $bindargs) = @_;
415 if ($self->fill_in_placeholders) {
416 my $val = shift @{$bindargs} || '';
417 my ($left, $right) = @{$self->placeholder_surround};
420 return qq($left$val$right)
425 # FIXME - terrible name for a user facing API
427 my ($self, $tree, $bindargs) = @_;
428 $self->_unparse($tree, [@{$bindargs||[]}], 0);
432 my ($self, $tree, $bindargs, $depth) = @_;
434 if (not $tree or not @$tree) {
438 my ($car, $cdr) = @{$tree}[0,1];
440 if (! defined $car or (! ref $car and ! defined $cdr) ) {
441 require Data::Dumper;
442 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
443 Data::Dumper::Dumper($tree)
448 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
450 elsif ($car eq 'LITERAL') {
453 elsif ($car eq 'PLACEHOLDER') {
454 return $self->fill_in_placeholder($bindargs);
456 elsif ($car eq 'PAREN') {
457 return sprintf ('(%s)',
458 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
460 ($self->_is_key($cdr)
461 ? ( $self->newline||'' ) . $self->indent($depth + 1)
466 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
467 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
469 elsif ($car eq 'LIST' ) {
470 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
473 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
474 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->_unparse($cdr, $bindargs, $depth);
478 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
486 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
488 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
498 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
501 profile => 'console', # predefined profile to use (default: 'none')
502 fill_in_placeholders => 1, # true for placeholder population
503 placeholder_surround => # The strings that will be wrapped around
504 [GREEN, RESET], # populated placeholders if the above is set
505 indent_string => ' ', # the string used when indenting
506 indent_amount => 2, # how many of above string to use for a single
508 newline => "\n", # string for newline
510 select => [RED, RESET], # a pair of strings defining what to surround
511 # the keyword with for colorization
515 select => 0, # A zero means that the keyword will start on
517 from => 1, # Any other positive integer means that after
518 on => 2, # said newline it will get that many indents
523 Returns a new SQL::Abstract::Tree object. All arguments are optional.
527 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
528 and C<html>. Typically a user will probably just use C<console> or
529 C<console_monochrome>, but if something about a profile bothers you, merely
530 use the profile and override the parts that you don't like.
534 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
536 Takes C<$sql> and C<\@bindargs>.
538 Returns a formatting string based on the string passed in
542 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
544 Returns a "tree" representing passed in SQL. Please do not depend on the
545 structure of the returned tree. It may be stable at some point, but not yet.
549 $sqlat->parse($tree_structure, \@bindargs)
551 Transform "tree" into SQL, applying various transforms on the way.
553 =head2 format_keyword
555 $sqlat->format_keyword('SELECT')
557 Currently this just takes a keyword and puts the C<colormap> stuff around it.
558 Later on it may do more and allow for coderef based transforms.
562 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
564 Returns whitespace to be inserted around a keyword.
566 =head2 fill_in_placeholder
568 my $value = $sqlat->fill_in_placeholder(\@bindargs)
570 Removes last arg from passed arrayref and returns it, surrounded with
571 the values in placeholder_surround, and then surrounded with single quotes.
575 Returns as many indent strings as indent amounts times the first argument.
583 =head2 fill_in_placeholders
603 =head2 placeholder_surround