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