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
36 # Parser states for _recurse_parse()
37 use constant PARSE_TOP_LEVEL => 0;
38 use constant PARSE_IN_EXPR => 1;
39 use constant PARSE_IN_PARENS => 2;
40 use constant PARSE_RHS => 3;
42 # These SQL keywords always signal end of the current expression (except inside
43 # of a parenthesized subexpression).
44 # Format: A list of strings that will be compiled to extended syntax (ie.
45 # /.../x) regexes, without capturing parentheses. They will be automatically
46 # anchored to word boundaries to match the whole token).
47 my @expression_terminator_sql_keywords = (
56 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
57 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
75 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
78 # These are binary operator keywords always a single LHS and RHS
79 # * AND/OR are handled separately as they are N-ary
80 # * so is NOT as being unary
81 # * BETWEEN without paranthesis around the ANDed arguments (which
82 # makes it a non-binary op) is detected and accomodated in
84 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
85 my @binary_op_keywords = (
88 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
89 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
91 (qw/< > != <> = <= >=/)
94 { '\b (?: NOT \s+)?' . $_ . '\b' }
99 my $tokenizer_re_str = join("\n\t|\n",
100 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
104 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
106 sub _binary_op_keywords { @binary_op_keywords }
127 fill_in_placeholders => 1,
128 indent_string => ' ',
132 indentmap => { %indents },
134 console_monochrome => {
135 fill_in_placeholders => 1,
136 indent_string => ' ',
140 indentmap => { %indents },
143 fill_in_placeholders => 1,
144 indent_string => ' ',
146 newline => "<br />\n",
148 select => ['<span class="select">' , '</span>'],
149 'insert into' => ['<span class="insert-into">' , '</span>'],
150 update => ['<span class="select">' , '</span>'],
151 'delete from' => ['<span class="delete-from">' , '</span>'],
152 where => ['<span class="where">' , '</span>'],
153 from => ['<span class="from">' , '</span>'],
154 join => ['<span class="join">' , '</span>'],
155 on => ['<span class="on">' , '</span>'],
156 'group by' => ['<span class="group-by">', '</span>'],
157 'order by' => ['<span class="order-by">', '</span>'],
158 set => ['<span class="set">', '</span>'],
159 into => ['<span class="into">', '</span>'],
160 values => ['<span class="values">', '</span>'],
162 indentmap => { %indents },
171 require Term::ANSIColor;
172 $profiles{console}->{colormap} = {
173 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
174 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
175 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
176 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
178 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
179 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
181 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
182 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
184 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
185 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
186 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
188 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
189 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
195 my $args = shift || {};
197 my $profile = delete $args->{profile} || 'none';
198 my $data = $merger->merge( $profiles{$profile}, $args );
206 # tokenize string, and remove all optional whitespace
208 foreach my $token (split $tokenizer_re, $s) {
209 push @$tokens, $token if (length $token) && ($token =~ /\S/);
212 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
217 my ($self, $tokens, $state) = @_;
220 while (1) { # left-associative parsing
222 my $lookahead = $tokens->[0];
223 if ( not defined($lookahead)
225 ($state == PARSE_IN_PARENS && $lookahead eq ')')
227 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
229 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
234 my $token = shift @$tokens;
236 # nested expression in ()
237 if ($token eq '(' ) {
238 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
239 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
240 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
242 $left = $left ? [@$left, [PAREN => [$right] ]]
243 : [PAREN => [$right] ];
246 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
248 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
250 # Merge chunks if logic matches
251 if (ref $right and $op eq $right->[0]) {
252 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
255 $left = [$op => [$left, $right]];
258 # binary operator keywords
259 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
261 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
263 # A between with a simple LITERAL for a 1st RHS argument needs a
264 # rerun of the search to (hopefully) find the proper AND construct
265 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
266 unshift @$tokens, $right->[1][0];
267 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
270 $left = [$op => [$left, $right] ];
272 # expression terminator keywords (as they start a new expression)
273 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
275 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
276 $left = $left ? [ $left, [$op => [$right] ]]
277 : [ $op => [$right] ];
279 # NOT (last as to allow all other NOT X pieces first)
280 elsif ( $token =~ /^ not $/ix ) {
282 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
283 $left = $left ? [ @$left, [$op => [$right] ]]
284 : [ $op => [$right] ];
287 # literal (eat everything on the right until RHS termination)
289 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
290 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
291 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
297 my ($self, $keyword) = @_;
299 if (my $around = $self->colormap->{lc $keyword}) {
300 $keyword = "$around->[0]$keyword$around->[1]";
314 my ($self, $keyword, $depth) = @_;
317 if (defined $self->indentmap->{lc $keyword}) {
318 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
320 $before = '' if $depth == 0 and defined $starters{lc $keyword};
321 return [$before, ' '];
324 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
327 my ($self, $tree) = @_;
328 $tree = $tree->[0] while ref $tree;
330 defined $tree && defined $self->indentmap->{lc $tree};
333 sub _fill_in_placeholder {
334 my ($self, $bindargs) = @_;
336 if ($self->fill_in_placeholders) {
337 my $val = pop @{$bindargs} || '';
346 my ($self, $tree, $bindargs, $depth) = @_;
354 my $car = $tree->[0];
355 my $cdr = $tree->[1];
358 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
360 elsif ($car eq 'LITERAL') {
361 if ($cdr->[0] eq '?') {
362 return $self->_fill_in_placeholder($bindargs)
366 elsif ($car eq 'PAREN') {
369 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
370 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
372 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
373 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
376 my ($l, $r) = @{$self->whitespace($car, $depth)};
377 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
381 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
389 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
391 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
401 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
404 profile => 'console', # predefined profile to use (default: 'none')
405 fill_in_placeholders => 1, # true for placeholder population
406 indent_string => ' ', # the string used when indenting
407 indent_amount => 2, # how many of above string to use for a single
409 newline => "\n", # string for newline
411 select => [RED, RESET], # a pair of strings defining what to surround
412 # the keyword with for colorization
416 select => 0, # A zero means that the keyword will start on
418 from => 1, # Any other positive integer means that after
419 on => 2, # said newline it will get that many indents
424 Returns a new SQL::Abstract::Tree object. All arguments are optional.
428 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
429 and C<html>. Typically a user will probably just use C<console> or
430 C<console_monochrome>, but if something about a profile bothers you, merely
431 use the profile and override the parts that you don't like.
435 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
437 Takes C<$sql> and C<\@bindargs>.
439 Returns a formatting string based on the string passed in