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 = (
33 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
34 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
52 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
55 # These are binary operator keywords always a single LHS and RHS
56 # * AND/OR are handled separately as they are N-ary
57 # * so is NOT as being unary
58 # * BETWEEN without paranthesis around the ANDed arguments (which
59 # makes it a non-binary op) is detected and accomodated in
61 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
62 my @binary_op_keywords = (
65 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
66 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
68 (qw/< > != <> = <= >=/)
71 { '\b (?: NOT \s+)?' . $_ . '\b' }
76 my $tokenizer_re_str = join("\n\t|\n",
77 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
81 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
83 sub _binary_op_keywords { @binary_op_keywords }
103 indent_string => ' ',
107 indentmap => { %indents },
109 console_monochrome => {
110 indent_string => ' ',
114 indentmap => { %indents },
117 indent_string => ' ',
119 newline => "<br />\n",
121 select => ['<span class="select">' , '</span>'],
122 'insert into' => ['<span class="insert-into">' , '</span>'],
123 update => ['<span class="select">' , '</span>'],
124 'delete from' => ['<span class="delete-from">' , '</span>'],
125 where => ['<span class="where">' , '</span>'],
126 from => ['<span class="from">' , '</span>'],
127 join => ['<span class="join">' , '</span>'],
128 on => ['<span class="on">' , '</span>'],
129 'group by' => ['<span class="group-by">', '</span>'],
130 'order by' => ['<span class="order-by">', '</span>'],
131 set => ['<span class="set">', '</span>'],
132 into => ['<span class="into">', '</span>'],
133 values => ['<span class="values">', '</span>'],
135 indentmap => { %indents },
144 require Term::ANSIColor;
145 $profiles{console}->{colormap} = {
146 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
147 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
148 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
149 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
151 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
153 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
154 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
156 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
157 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
158 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
160 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
161 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
166 my ($class, $args) = @_;
168 my $profile = delete $args->{profile} || 'none';
169 my $data = {%{$profiles{$profile}}, %{$args||{}}};
177 # tokenize string, and remove all optional whitespace
179 foreach my $token (split $tokenizer_re, $s) {
180 push @$tokens, $token if (length $token) && ($token =~ /\S/);
183 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
188 my ($self, $tokens, $state) = @_;
191 while (1) { # left-associative parsing
193 my $lookahead = $tokens->[0];
194 if ( not defined($lookahead)
196 ($state == PARSE_IN_PARENS && $lookahead eq ')')
198 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
200 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
205 my $token = shift @$tokens;
207 # nested expression in ()
208 if ($token eq '(' ) {
209 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
210 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
211 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
213 $left = $left ? [@$left, [PAREN => [$right] ]]
214 : [PAREN => [$right] ];
217 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
219 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
221 # Merge chunks if logic matches
222 if (ref $right and $op eq $right->[0]) {
223 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
226 $left = [$op => [$left, $right]];
229 # binary operator keywords
230 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
232 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
234 # A between with a simple LITERAL for a 1st RHS argument needs a
235 # rerun of the search to (hopefully) find the proper AND construct
236 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
237 unshift @$tokens, $right->[1][0];
238 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
241 $left = [$op => [$left, $right] ];
243 # expression terminator keywords (as they start a new expression)
244 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
246 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
247 $left = $left ? [ $left, [$op => [$right] ]]
248 : [ $op => [$right] ];
250 # NOT (last as to allow all other NOT X pieces first)
251 elsif ( $token =~ /^ not $/ix ) {
253 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
254 $left = $left ? [ @$left, [$op => [$right] ]]
255 : [ $op => [$right] ];
258 # literal (eat everything on the right until RHS termination)
260 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
261 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
262 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
268 my ($self, $keyword) = @_;
270 if (my $around = $self->colormap->{lc $keyword}) {
271 $keyword = "$around->[0]$keyword$around->[1]";
278 my ($self, $keyword, $depth) = @_;
281 if (defined $self->indentmap->{lc $keyword}) {
282 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
284 $before = '' if $depth == 0 and lc $keyword eq 'select';
285 return [$before, ' '];
288 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
292 $tree = $tree->[0] while ref $tree;
294 defined $tree && lc $tree eq 'select';
298 my ($self, $tree, $depth) = @_;
306 my $car = $tree->[0];
307 my $cdr = $tree->[1];
310 return join ('', map $self->unparse($_, $depth), @$tree);
312 elsif ($car eq 'LITERAL') {
315 elsif ($car eq 'PAREN') {
318 map $self->unparse($_, $depth + 2), @{$cdr}) .
319 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
321 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
322 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
325 my ($l, $r) = @{$self->whitespace($car, $depth)};
326 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
330 sub format { my $self = shift; $self->unparse($self->parse(@_)) }
338 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
340 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');