1 package SQL::Abstract::Tree;
8 use base 'Class::Accessor::Grouped';
10 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
11 newline indent_string indent_amount colormap indentmap
14 # Parser states for _recurse_parse()
15 use constant PARSE_TOP_LEVEL => 0;
16 use constant PARSE_IN_EXPR => 1;
17 use constant PARSE_IN_PARENS => 2;
18 use constant PARSE_RHS => 3;
20 # These SQL keywords always signal end of the current expression (except inside
21 # of a parenthesized subexpression).
22 # Format: A list of strings that will be compiled to extended syntax (ie.
23 # /.../x) regexes, without capturing parentheses. They will be automatically
24 # anchored to word boundaries to match the whole token).
25 my @expression_terminator_sql_keywords = (
30 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
31 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
50 # These are binary operator keywords always a single LHS and RHS
51 # * AND/OR are handled separately as they are N-ary
52 # * so is NOT as being unary
53 # * BETWEEN without paranthesis around the ANDed arguments (which
54 # makes it a non-binary op) is detected and accomodated in
56 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
57 my @binary_op_keywords = (
60 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
61 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
63 (qw/< > != <> = <= >=/)
66 { '\b (?: NOT \s+)?' . $_ . '\b' }
71 my $tokenizer_re_str = join("\n\t|\n",
72 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
76 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
78 sub _binary_op_keywords { @binary_op_keywords }
95 indentmap => { %indents },
97 console_monochrome => {
102 indentmap => { %indents },
105 indent_string => ' ',
107 newline => "<br />\n",
109 select => ['<span class="select">' , '</span>'],
110 where => ['<span class="where">' , '</span>'],
111 from => ['<span class="from">' , '</span>'],
112 join => ['<span class="join">' , '</span>'],
113 on => ['<span class="on">' , '</span>'],
114 'group by' => ['<span class="group-by">', '</span>'],
116 indentmap => { %indents },
125 require Term::ANSIColor;
126 $profiles{console}->{colormap} = {
127 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
128 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
129 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
134 my ($class, $args) = @_;
136 my $profile = delete $args->{profile} || 'none';
137 my $data = {%{$profiles{$profile}}, %{$args||{}}};
145 # tokenize string, and remove all optional whitespace
147 foreach my $token (split $tokenizer_re, $s) {
148 push @$tokens, $token if (length $token) && ($token =~ /\S/);
151 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
156 my ($self, $tokens, $state) = @_;
159 while (1) { # left-associative parsing
161 my $lookahead = $tokens->[0];
162 if ( not defined($lookahead)
164 ($state == PARSE_IN_PARENS && $lookahead eq ')')
166 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
168 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
173 my $token = shift @$tokens;
175 # nested expression in ()
176 if ($token eq '(' ) {
177 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
178 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
179 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
181 $left = $left ? [@$left, [PAREN => [$right] ]]
182 : [PAREN => [$right] ];
185 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
187 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
189 # Merge chunks if logic matches
190 if (ref $right and $op eq $right->[0]) {
191 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
194 $left = [$op => [$left, $right]];
197 # binary operator keywords
198 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
200 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
202 # A between with a simple LITERAL for a 1st RHS argument needs a
203 # rerun of the search to (hopefully) find the proper AND construct
204 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
205 unshift @$tokens, $right->[1][0];
206 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
209 $left = [$op => [$left, $right] ];
211 # expression terminator keywords (as they start a new expression)
212 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
214 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
215 $left = $left ? [ $left, [$op => [$right] ]]
216 : [ $op => [$right] ];
218 # NOT (last as to allow all other NOT X pieces first)
219 elsif ( $token =~ /^ not $/ix ) {
221 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
222 $left = $left ? [ @$left, [$op => [$right] ]]
223 : [ $op => [$right] ];
226 # literal (eat everything on the right until RHS termination)
228 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
229 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
230 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
236 my ($self, $keyword) = @_;
238 if (my $around = $self->colormap->{lc $keyword}) {
239 $keyword = "$around->[0]$keyword$around->[1]";
246 my ($self, $keyword, $depth) = @_;
250 if (defined $self->indentmap->{lc $keyword}) {
251 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
253 $before = '' if $depth == 0 and lc $keyword eq 'select';
254 return [$before, $after];
257 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
261 $tree = $tree->[0] while ref $tree;
263 defined $tree && lc $tree eq 'select';
267 my ($self, $tree, $depth) = @_;
275 my $car = $tree->[0];
276 my $cdr = $tree->[1];
279 return join ('', map $self->unparse($_, $depth), @$tree);
281 elsif ($car eq 'LITERAL') {
284 elsif ($car eq 'PAREN') {
287 map $self->unparse($_, $depth + 2), @{$cdr}) .
288 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ')';
290 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
291 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
294 my ($l, $r) = @{$self->whitespace($car, $depth)};
295 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
299 sub format { my $self = shift; $self->unparse($self->parse(@_)) }
307 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
309 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');