fix colors for from
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
CommitLineData
01dd4e4f 1package SQL::Abstract::Tree;
2
3use strict;
4use warnings;
5use Carp;
6
1536de15 7
1536de15 8use base 'Class::Accessor::Grouped';
9
10__PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
11 newline indent_string indent_amount colormap indentmap
12);
13
01dd4e4f 14# Parser states for _recurse_parse()
15use constant PARSE_TOP_LEVEL => 0;
16use constant PARSE_IN_EXPR => 1;
17use constant PARSE_IN_PARENS => 2;
18use constant PARSE_RHS => 3;
19
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).
25my @expression_terminator_sql_keywords = (
26 'SELECT',
7853a177 27 'UPDATE',
28 'INSERT \s+ INTO',
29 'DELETE \s+ FROM',
3d910890 30 'FROM',
7853a177 31 'SET',
01dd4e4f 32 '(?:
33 (?:
34 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
35 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
36 )?
37 JOIN
38 )',
39 'ON',
40 'WHERE',
7853a177 41 'VALUES',
01dd4e4f 42 'EXISTS',
43 'GROUP \s+ BY',
44 'HAVING',
45 'ORDER \s+ BY',
46 'LIMIT',
47 'OFFSET',
48 'FOR',
49 'UNION',
50 'INTERSECT',
51 'EXCEPT',
52 'RETURNING',
8d0dd7dc 53 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
01dd4e4f 54);
55
56# These are binary operator keywords always a single LHS and RHS
57# * AND/OR are handled separately as they are N-ary
58# * so is NOT as being unary
59# * BETWEEN without paranthesis around the ANDed arguments (which
60# makes it a non-binary op) is detected and accomodated in
61# _recurse_parse()
62my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
63my @binary_op_keywords = (
64 ( map
65 {
66 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
67 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
68 }
69 (qw/< > != <> = <= >=/)
70 ),
71 ( map
72 { '\b (?: NOT \s+)?' . $_ . '\b' }
73 (qw/IN BETWEEN LIKE/)
74 ),
75);
76
77my $tokenizer_re_str = join("\n\t|\n",
78 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
79 @binary_op_keywords,
80);
81
82my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
83
84sub _binary_op_keywords { @binary_op_keywords }
85
7e5600e9 86my %indents = (
7853a177 87 select => 0,
88 update => 0,
89 'insert into' => 0,
90 'delete from' => 0,
3d910890 91 from => 1,
7853a177 92 where => 1,
93 join => 1,
94 'left join' => 1,
95 on => 2,
96 'group by' => 1,
97 'order by' => 1,
98 set => 1,
99 into => 1,
100 values => 2,
7e5600e9 101);
102
75c3a063 103my %profiles = (
104 console => {
1536de15 105 indent_string => ' ',
75c3a063 106 indent_amount => 2,
1536de15 107 newline => "\n",
3be357b0 108 colormap => {},
7e5600e9 109 indentmap => { %indents },
3be357b0 110 },
111 console_monochrome => {
112 indent_string => ' ',
113 indent_amount => 2,
114 newline => "\n",
115 colormap => {},
7e5600e9 116 indentmap => { %indents },
117 },
118 html => {
119 indent_string => '&nbsp;',
120 indent_amount => 2,
121 newline => "<br />\n",
122 colormap => {
7853a177 123 select => ['<span class="select">' , '</span>'],
124 'insert into' => ['<span class="insert-into">' , '</span>'],
125 update => ['<span class="select">' , '</span>'],
126 'delete from' => ['<span class="delete-from">' , '</span>'],
127 where => ['<span class="where">' , '</span>'],
128 from => ['<span class="from">' , '</span>'],
129 join => ['<span class="join">' , '</span>'],
130 on => ['<span class="on">' , '</span>'],
131 'group by' => ['<span class="group-by">', '</span>'],
132 'order by' => ['<span class="order-by">', '</span>'],
133 set => ['<span class="set">', '</span>'],
134 into => ['<span class="into">', '</span>'],
135 values => ['<span class="values">', '</span>'],
1536de15 136 },
7e5600e9 137 indentmap => { %indents },
75c3a063 138 },
139 none => {
1536de15 140 colormap => {},
141 indentmap => {},
75c3a063 142 },
143);
144
3be357b0 145eval {
146 require Term::ANSIColor;
147 $profiles{console}->{colormap} = {
7853a177 148 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
149 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
150 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
151 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
152
153 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
c1b89c4f 154 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
7853a177 155
156 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
157 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
158
159 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
160 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
161 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
162
163 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
164 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
3be357b0 165 };
166};
167
75c3a063 168sub new {
169 my ($class, $args) = @_;
170
171 my $profile = delete $args->{profile} || 'none';
172 my $data = {%{$profiles{$profile}}, %{$args||{}}};
173
174 bless $data, $class
175}
d695b0ad 176
01dd4e4f 177sub parse {
d695b0ad 178 my ($self, $s) = @_;
01dd4e4f 179
180 # tokenize string, and remove all optional whitespace
181 my $tokens = [];
182 foreach my $token (split $tokenizer_re, $s) {
183 push @$tokens, $token if (length $token) && ($token =~ /\S/);
184 }
185
d695b0ad 186 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 187 return $tree;
188}
189
190sub _recurse_parse {
d695b0ad 191 my ($self, $tokens, $state) = @_;
01dd4e4f 192
193 my $left;
194 while (1) { # left-associative parsing
195
196 my $lookahead = $tokens->[0];
197 if ( not defined($lookahead)
198 or
199 ($state == PARSE_IN_PARENS && $lookahead eq ')')
200 or
201 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
202 or
203 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
204 ) {
205 return $left;
206 }
207
208 my $token = shift @$tokens;
209
210 # nested expression in ()
211 if ($token eq '(' ) {
d695b0ad 212 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
213 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
214 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 215
216 $left = $left ? [@$left, [PAREN => [$right] ]]
217 : [PAREN => [$right] ];
218 }
219 # AND/OR
220 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
221 my $op = uc $token;
d695b0ad 222 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 223
224 # Merge chunks if logic matches
225 if (ref $right and $op eq $right->[0]) {
226 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
227 }
228 else {
229 $left = [$op => [$left, $right]];
230 }
231 }
232 # binary operator keywords
233 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
234 my $op = uc $token;
d695b0ad 235 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 236
237 # A between with a simple LITERAL for a 1st RHS argument needs a
238 # rerun of the search to (hopefully) find the proper AND construct
239 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
240 unshift @$tokens, $right->[1][0];
d695b0ad 241 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 242 }
243
244 $left = [$op => [$left, $right] ];
245 }
246 # expression terminator keywords (as they start a new expression)
247 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
248 my $op = uc $token;
d695b0ad 249 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 250 $left = $left ? [ $left, [$op => [$right] ]]
251 : [ $op => [$right] ];
252 }
253 # NOT (last as to allow all other NOT X pieces first)
254 elsif ( $token =~ /^ not $/ix ) {
255 my $op = uc $token;
d695b0ad 256 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 257 $left = $left ? [ @$left, [$op => [$right] ]]
258 : [ $op => [$right] ];
259
260 }
261 # literal (eat everything on the right until RHS termination)
262 else {
d695b0ad 263 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
264 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
265 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
01dd4e4f 266 }
267 }
268}
269
d695b0ad 270sub format_keyword {
271 my ($self, $keyword) = @_;
272
1536de15 273 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 274 $keyword = "$around->[0]$keyword$around->[1]";
275 }
276
277 return $keyword
278}
279
a24cc3a0 280sub whitespace {
281 my ($self, $keyword, $depth) = @_;
e171c446 282
283 my $before = '';
1536de15 284 if (defined $self->indentmap->{lc $keyword}) {
285 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 286 }
1a67e3a0 287 $before = '' if $depth == 0 and lc $keyword eq 'select';
b4e0e260 288 return [$before, ' '];
a24cc3a0 289}
290
1536de15 291sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 292
0569a14f 293sub _is_select {
294 my $tree = shift;
295 $tree = $tree->[0] while ref $tree;
296
ca8aec12 297 defined $tree && lc $tree eq 'select';
0569a14f 298}
299
01dd4e4f 300sub unparse {
a24cc3a0 301 my ($self, $tree, $depth) = @_;
302
e171c446 303 $depth ||= 0;
01dd4e4f 304
305 if (not $tree ) {
306 return '';
307 }
a24cc3a0 308
309 my $car = $tree->[0];
310 my $cdr = $tree->[1];
311
312 if (ref $car) {
e171c446 313 return join ('', map $self->unparse($_, $depth), @$tree);
01dd4e4f 314 }
a24cc3a0 315 elsif ($car eq 'LITERAL') {
316 return $cdr->[0];
01dd4e4f 317 }
a24cc3a0 318 elsif ($car eq 'PAREN') {
e171c446 319 return '(' .
a24cc3a0 320 join(' ',
0569a14f 321 map $self->unparse($_, $depth + 2), @{$cdr}) .
f088a68d 322 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
01dd4e4f 323 }
a24cc3a0 324 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
e171c446 325 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
01dd4e4f 326 }
327 else {
a24cc3a0 328 my ($l, $r) = @{$self->whitespace($car, $depth)};
e171c446 329 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
01dd4e4f 330 }
331}
332
d695b0ad 333sub format { my $self = shift; $self->unparse($self->parse(@_)) }
01dd4e4f 334
3351;
336
3be357b0 337=pod
338
339=head1 SYNOPSIS
340
341 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
342
343 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
344
345 # SELECT *
346 # FROM foo
347 # WHERE foo.a > 2
348