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