1 package SQL::Abstract::Tree;
10 my $merger = Hash::Merge->new;
12 $merger->specify_behavior({
14 SCALAR => sub { $_[1] },
15 ARRAY => sub { [ $_[0], @{$_[1]} ] },
16 HASH => sub { $_[1] },
19 SCALAR => sub { $_[1] },
20 ARRAY => sub { $_[1] },
21 HASH => sub { $_[1] },
24 SCALAR => sub { $_[1] },
25 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
26 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
30 use base 'Class::Accessor::Grouped';
32 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
33 newline indent_string indent_amount colormap indentmap fill_in_placeholders
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;
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 word boundaries to match the whole token).
48 my @expression_terminator_sql_keywords = (
57 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
58 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
76 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
79 # These are binary operator keywords always a single LHS and RHS
80 # * AND/OR are handled separately as they are N-ary
81 # * so is NOT as being unary
82 # * BETWEEN without paranthesis around the ANDed arguments (which
83 # makes it a non-binary op) is detected and accomodated in
85 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
86 my @binary_op_keywords = (
89 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
90 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
92 (qw/< > != <> = <= >=/)
95 { '\b (?: NOT \s+)?' . $_ . '\b' }
100 my $tokenizer_re_str = join("\n\t|\n",
101 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
105 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
107 sub _binary_op_keywords { @binary_op_keywords }
128 fill_in_placeholders => 1,
129 placeholder_surround => ['?/', ''],
130 indent_string => ' ',
134 indentmap => { %indents },
136 console_monochrome => {
137 fill_in_placeholders => 1,
138 placeholder_surround => ['?/', ''],
139 indent_string => ' ',
143 indentmap => { %indents },
146 fill_in_placeholders => 1,
147 placeholder_surround => ['<span class="placeholder">', '</span>'],
148 indent_string => ' ',
150 newline => "<br />\n",
152 select => ['<span class="select">' , '</span>'],
153 'insert into' => ['<span class="insert-into">' , '</span>'],
154 update => ['<span class="select">' , '</span>'],
155 'delete from' => ['<span class="delete-from">' , '</span>'],
156 where => ['<span class="where">' , '</span>'],
157 from => ['<span class="from">' , '</span>'],
158 join => ['<span class="join">' , '</span>'],
159 on => ['<span class="on">' , '</span>'],
160 'group by' => ['<span class="group-by">', '</span>'],
161 'order by' => ['<span class="order-by">', '</span>'],
162 set => ['<span class="set">', '</span>'],
163 into => ['<span class="into">', '</span>'],
164 values => ['<span class="values">', '</span>'],
166 indentmap => { %indents },
175 require Term::ANSIColor;
177 $profiles{console}->{placeholder_surround} =
178 [Term::ANSIColor::color('black on_cyan'), Term::ANSIColor::color('reset')];
180 $profiles{console}->{colormap} = {
181 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
182 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
183 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
184 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
186 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
187 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
189 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
190 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
192 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
193 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
194 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
196 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
197 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
203 my $args = shift || {};
205 my $profile = delete $args->{profile} || 'none';
206 my $data = $merger->merge( $profiles{$profile}, $args );
214 # tokenize string, and remove all optional whitespace
216 foreach my $token (split $tokenizer_re, $s) {
217 push @$tokens, $token if (length $token) && ($token =~ /\S/);
220 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
225 my ($self, $tokens, $state) = @_;
228 while (1) { # left-associative parsing
230 my $lookahead = $tokens->[0];
231 if ( not defined($lookahead)
233 ($state == PARSE_IN_PARENS && $lookahead eq ')')
235 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
237 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
242 my $token = shift @$tokens;
244 # nested expression in ()
245 if ($token eq '(' ) {
246 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
247 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
248 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
250 $left = $left ? [@$left, [PAREN => [$right] ]]
251 : [PAREN => [$right] ];
254 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
256 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
258 # Merge chunks if logic matches
259 if (ref $right and $op eq $right->[0]) {
260 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
263 $left = [$op => [$left, $right]];
266 # binary operator keywords
267 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
269 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
271 # A between with a simple LITERAL for a 1st RHS argument needs a
272 # rerun of the search to (hopefully) find the proper AND construct
273 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
274 unshift @$tokens, $right->[1][0];
275 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
278 $left = [$op => [$left, $right] ];
280 # expression terminator keywords (as they start a new expression)
281 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
283 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
284 $left = $left ? [ $left, [$op => [$right] ]]
285 : [ $op => [$right] ];
287 # NOT (last as to allow all other NOT X pieces first)
288 elsif ( $token =~ /^ not $/ix ) {
290 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
291 $left = $left ? [ @$left, [$op => [$right] ]]
292 : [ $op => [$right] ];
295 # literal (eat everything on the right until RHS termination)
297 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
298 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
299 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
305 my ($self, $keyword) = @_;
307 if (my $around = $self->colormap->{lc $keyword}) {
308 $keyword = "$around->[0]$keyword$around->[1]";
322 my ($self, $keyword, $depth) = @_;
325 if (defined $self->indentmap->{lc $keyword}) {
326 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
328 $before = '' if $depth == 0 and defined $starters{lc $keyword};
329 return [$before, ' '];
332 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
335 my ($self, $tree) = @_;
336 $tree = $tree->[0] while ref $tree;
338 defined $tree && defined $self->indentmap->{lc $tree};
341 sub fill_in_placeholder {
342 my ($self, $bindargs) = @_;
344 if ($self->fill_in_placeholders) {
345 my $val = pop @{$bindargs} || '';
346 my ($left, $right) = @{$self->placeholder_surround};
349 return qq('$left$val$right')
355 my ($self, $tree, $bindargs, $depth) = @_;
363 my $car = $tree->[0];
364 my $cdr = $tree->[1];
367 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
369 elsif ($car eq 'LITERAL') {
370 if ($cdr->[0] eq '?') {
371 return $self->fill_in_placeholder($bindargs)
375 elsif ($car eq 'PAREN') {
378 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
379 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
381 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
382 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
385 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
386 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
390 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
398 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
400 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
410 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
413 profile => 'console', # predefined profile to use (default: 'none')
414 fill_in_placeholders => 1, # true for placeholder population
415 placeholder_surround => # The strings that will be wrapped around
416 [GREEN, RESET], # populated placeholders if the above is set
417 indent_string => ' ', # the string used when indenting
418 indent_amount => 2, # how many of above string to use for a single
420 newline => "\n", # string for newline
422 select => [RED, RESET], # a pair of strings defining what to surround
423 # the keyword with for colorization
427 select => 0, # A zero means that the keyword will start on
429 from => 1, # Any other positive integer means that after
430 on => 2, # said newline it will get that many indents
435 Returns a new SQL::Abstract::Tree object. All arguments are optional.
439 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
440 and C<html>. Typically a user will probably just use C<console> or
441 C<console_monochrome>, but if something about a profile bothers you, merely
442 use the profile and override the parts that you don't like.
446 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
448 Takes C<$sql> and C<\@bindargs>.
450 Returns a formatting string based on the string passed in
454 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
456 Returns a "tree" representing passed in SQL. Please do not depend on the
457 structure of the returned tree. It may be stable at some point, but not yet.
461 $sqlat->parse($tree_structure, \@bindargs)
463 Transform "tree" into SQL, applying various transforms on the way.
465 =head2 format_keyword
467 $sqlat->format_keyword('SELECT')
469 Currently this just takes a keyword and puts the C<colormap> stuff around it.
470 Later on it may do more and allow for coderef based transforms.
474 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
476 Returns whitespace to be inserted around a keyword.
478 =head2 fill_in_placeholder
480 my $value = $sqlat->fill_in_placeholder(\@bindargs)
482 Removes last arg from passed arrayref and returns it, surrounded with
483 the values in placeholder_surround, and then surrounded with single quotes.
487 Returns as many indent strings as indent amounts times the first argument.
495 =head2 fill_in_placeholders
515 =head2 placeholder_surround