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+ )?
48 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
51 # These are binary operator keywords always a single LHS and RHS
52 # * AND/OR are handled separately as they are N-ary
53 # * so is NOT as being unary
54 # * BETWEEN without paranthesis around the ANDed arguments (which
55 # makes it a non-binary op) is detected and accomodated in
57 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
58 my @binary_op_keywords = (
61 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
62 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
64 (qw/< > != <> = <= >=/)
67 { '\b (?: NOT \s+)?' . $_ . '\b' }
72 my $tokenizer_re_str = join("\n\t|\n",
73 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
77 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
79 sub _binary_op_keywords { @binary_op_keywords }
97 indentmap => { %indents },
99 console_monochrome => {
100 indent_string => ' ',
104 indentmap => { %indents },
107 indent_string => ' ',
109 newline => "<br />\n",
111 select => ['<span class="select">' , '</span>'],
112 where => ['<span class="where">' , '</span>'],
113 from => ['<span class="from">' , '</span>'],
114 join => ['<span class="join">' , '</span>'],
115 on => ['<span class="on">' , '</span>'],
116 'group by' => ['<span class="group-by">', '</span>'],
118 indentmap => { %indents },
127 require Term::ANSIColor;
128 $profiles{console}->{colormap} = {
129 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
130 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
131 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
132 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
133 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
134 'group by' => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
135 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
140 my ($class, $args) = @_;
142 my $profile = delete $args->{profile} || 'none';
143 my $data = {%{$profiles{$profile}}, %{$args||{}}};
151 # tokenize string, and remove all optional whitespace
153 foreach my $token (split $tokenizer_re, $s) {
154 push @$tokens, $token if (length $token) && ($token =~ /\S/);
157 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
162 my ($self, $tokens, $state) = @_;
165 while (1) { # left-associative parsing
167 my $lookahead = $tokens->[0];
168 if ( not defined($lookahead)
170 ($state == PARSE_IN_PARENS && $lookahead eq ')')
172 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
174 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
179 my $token = shift @$tokens;
181 # nested expression in ()
182 if ($token eq '(' ) {
183 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
184 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
185 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
187 $left = $left ? [@$left, [PAREN => [$right] ]]
188 : [PAREN => [$right] ];
191 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
193 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
195 # Merge chunks if logic matches
196 if (ref $right and $op eq $right->[0]) {
197 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
200 $left = [$op => [$left, $right]];
203 # binary operator keywords
204 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
206 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
208 # A between with a simple LITERAL for a 1st RHS argument needs a
209 # rerun of the search to (hopefully) find the proper AND construct
210 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
211 unshift @$tokens, $right->[1][0];
212 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
215 $left = [$op => [$left, $right] ];
217 # expression terminator keywords (as they start a new expression)
218 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
220 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
221 $left = $left ? [ $left, [$op => [$right] ]]
222 : [ $op => [$right] ];
224 # NOT (last as to allow all other NOT X pieces first)
225 elsif ( $token =~ /^ not $/ix ) {
227 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
228 $left = $left ? [ @$left, [$op => [$right] ]]
229 : [ $op => [$right] ];
232 # literal (eat everything on the right until RHS termination)
234 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
235 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
236 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
242 my ($self, $keyword) = @_;
244 if (my $around = $self->colormap->{lc $keyword}) {
245 $keyword = "$around->[0]$keyword$around->[1]";
252 my ($self, $keyword, $depth) = @_;
255 if (defined $self->indentmap->{lc $keyword}) {
256 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
258 $before = '' if $depth == 0 and lc $keyword eq 'select';
259 return [$before, ' '];
262 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
266 $tree = $tree->[0] while ref $tree;
268 defined $tree && lc $tree eq 'select';
272 my ($self, $tree, $depth) = @_;
280 my $car = $tree->[0];
281 my $cdr = $tree->[1];
284 return join ('', map $self->unparse($_, $depth), @$tree);
286 elsif ($car eq 'LITERAL') {
289 elsif ($car eq 'PAREN') {
292 map $self->unparse($_, $depth + 2), @{$cdr}) .
293 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
295 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
296 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
299 my ($l, $r) = @{$self->whitespace($car, $depth)};
300 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
304 sub format { my $self = shift; $self->unparse($self->parse(@_)) }
312 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
314 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');