Commit | Line | Data |
01dd4e4f |
1 | package SQL::Abstract::Tree; |
2 | |
c54740ba |
3 | # DO NOT edit away without talking to riba first, he will just put it back |
4 | # BEGIN pre-Moo2 import block |
5 | BEGIN { |
6 | require warnings; |
7 | my $initial_fatal_bits = (${^WARNING_BITS}||'') & $warnings::DeadBits{all}; |
8 | local $ENV{PERL_STRICTURES_EXTRA} = 0; |
9 | require Moo; Moo->import; |
10 | require Sub::Quote; Sub::Quote->import('quote_sub'); |
11 | ${^WARNING_BITS} &= ( $initial_fatal_bits | ~ $warnings::DeadBits{all} ); |
12 | } |
13 | # END pre-Moo2 import block |
14 | |
01dd4e4f |
15 | use strict; |
16 | use warnings; |
b3b79607 |
17 | no warnings 'qw'; |
01dd4e4f |
18 | |
c54740ba |
19 | use Carp; |
1536de15 |
20 | |
0769ac0e |
21 | my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)'; |
b3b79607 |
22 | my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )'; |
23 | |
0769ac0e |
24 | my $quote_left = qr/[\`\'\"\[]/; |
25 | my $quote_right = qr/[\`\'\"\]]/; |
01dd4e4f |
26 | |
4e914a7c |
27 | my $placeholder_re = qr/(?: \? | \$\d+ )/x; |
28 | |
01dd4e4f |
29 | # These SQL keywords always signal end of the current expression (except inside |
30 | # of a parenthesized subexpression). |
0769ac0e |
31 | # Format: A list of strings that will be compiled to extended syntax ie. |
01dd4e4f |
32 | # /.../x) regexes, without capturing parentheses. They will be automatically |
0769ac0e |
33 | # anchored to op boundaries (excluding quotes) to match the whole token. |
34 | my @expression_start_keywords = ( |
01dd4e4f |
35 | 'SELECT', |
7853a177 |
36 | 'UPDATE', |
6c4d8eb8 |
37 | 'SET', |
7853a177 |
38 | 'INSERT \s+ INTO', |
39 | 'DELETE \s+ FROM', |
3d910890 |
40 | 'FROM', |
01dd4e4f |
41 | '(?: |
42 | (?: |
0769ac0e |
43 | (?: (?: LEFT | RIGHT | FULL ) \s+ )? |
44 | (?: (?: CROSS | INNER | OUTER ) \s+ )? |
01dd4e4f |
45 | )? |
46 | JOIN |
47 | )', |
48 | 'ON', |
49 | 'WHERE', |
efc991a0 |
50 | '(?: DEFAULT \s+ )? VALUES', |
01dd4e4f |
51 | 'GROUP \s+ BY', |
52 | 'HAVING', |
53 | 'ORDER \s+ BY', |
c0eaa9fd |
54 | 'SKIP', |
81b3e585 |
55 | 'FETCH', |
c0eaa9fd |
56 | 'FIRST', |
01dd4e4f |
57 | 'LIMIT', |
58 | 'OFFSET', |
59 | 'FOR', |
60 | 'UNION', |
61 | 'INTERSECT', |
62 | 'EXCEPT', |
820bb1f5 |
63 | 'BEGIN \s+ WORK', |
64 | 'COMMIT', |
65 | 'ROLLBACK \s+ TO \s+ SAVEPOINT', |
66 | 'ROLLBACK', |
67 | 'SAVEPOINT', |
68 | 'RELEASE \s+ SAVEPOINT', |
01dd4e4f |
69 | 'RETURNING', |
70 | ); |
71 | |
b3b79607 |
72 | my $expr_start_re = join ("\n\t|\n", @expression_start_keywords ); |
73 | $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x; |
0769ac0e |
74 | |
01dd4e4f |
75 | # These are binary operator keywords always a single LHS and RHS |
76 | # * AND/OR are handled separately as they are N-ary |
77 | # * so is NOT as being unary |
3af02ccb |
78 | # * BETWEEN without parentheses around the ANDed arguments (which |
79 | # makes it a non-binary op) is detected and accommodated in |
01dd4e4f |
80 | # _recurse_parse() |
6c4d8eb8 |
81 | # * AS is not really an operator but is handled here as it's also LHS/RHS |
01dd4e4f |
82 | |
0769ac0e |
83 | # this will be included in the $binary_op_re, the distinction is interesting during |
1ec9b9e3 |
84 | # testing as one is tighter than the other, plus alphanum cmp ops have different |
85 | # look ahead/behind (e.g. "x"="y" ) |
86 | my @alphanum_cmp_op_keywords = (qw/< > != <> = <= >= /); |
87 | my $alphanum_cmp_op_re = join ("\n\t|\n", map |
0769ac0e |
88 | { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" } |
1ec9b9e3 |
89 | @alphanum_cmp_op_keywords |
01dd4e4f |
90 | ); |
1ec9b9e3 |
91 | $alphanum_cmp_op_re = qr/$alphanum_cmp_op_re/x; |
0769ac0e |
92 | |
93 | my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')'; |
b3b79607 |
94 | $binary_op_re = join "\n\t|\n", |
6c4d8eb8 |
95 | "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead", |
1ec9b9e3 |
96 | $alphanum_cmp_op_re, |
b3b79607 |
97 | $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )", |
98 | ; |
b7b0f832 |
99 | $binary_op_re = qr/$binary_op_re/x; |
0769ac0e |
100 | |
4247c384 |
101 | my $rno_re = qr/ROW_NUMBER \s* \( \s* \) \s+ OVER/ix; |
102 | |
103 | my $unary_op_re = 'NOT \s+ EXISTS | NOT | ' . $rno_re; |
6f2a5b66 |
104 | $unary_op_re = join "\n\t|\n", |
105 | "$op_look_behind (?i: $unary_op_re ) $op_look_ahead", |
106 | ; |
107 | $unary_op_re = qr/$unary_op_re/x; |
108 | |
ad591616 |
109 | my $asc_desc_re = qr/$op_look_behind (?i: ASC | DESC ) $op_look_ahead /x; |
110 | my $and_or_re = qr/$op_look_behind (?i: AND | OR ) $op_look_ahead /x; |
6f2a5b66 |
111 | |
ad591616 |
112 | my $tokenizer_re = join("\n\t|\n", |
b3b79607 |
113 | $expr_start_re, |
0769ac0e |
114 | $binary_op_re, |
6f2a5b66 |
115 | $unary_op_re, |
ad591616 |
116 | $asc_desc_re, |
117 | $and_or_re, |
1ec9b9e3 |
118 | $op_look_behind . ' \* ' . $op_look_ahead, |
257ecc8a |
119 | (map { quotemeta $_ } qw/, ( )/), |
4e914a7c |
120 | $placeholder_re, |
0769ac0e |
121 | ); |
01dd4e4f |
122 | |
ad591616 |
123 | # this one *is* capturing for the split below |
b3b79607 |
124 | # splits on whitespace if all else fails |
3af02ccb |
125 | # has to happen before the composing qr's are anchored (below) |
ad591616 |
126 | $tokenizer_re = qr/ \s* ( $tokenizer_re ) \s* | \s+ /x; |
b3b79607 |
127 | |
128 | # Parser states for _recurse_parse() |
129 | use constant PARSE_TOP_LEVEL => 0; |
130 | use constant PARSE_IN_EXPR => 1; |
131 | use constant PARSE_IN_PARENS => 2; |
132 | use constant PARSE_IN_FUNC => 3; |
133 | use constant PARSE_RHS => 4; |
6f2a5b66 |
134 | use constant PARSE_LIST_ELT => 5; |
b3b79607 |
135 | |
ad591616 |
136 | my $expr_term_re = qr/$expr_start_re | \)/x; |
137 | my $rhs_term_re = qr/ $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | $and_or_re | \, /x; |
1ec9b9e3 |
138 | my $all_std_keywords_re = qr/ $rhs_term_re | \( | $placeholder_re /x; |
ad591616 |
139 | |
140 | # anchor everything - even though keywords are separated by the tokenizer, leakage may occur |
141 | for ( |
142 | $quote_left, |
143 | $quote_right, |
144 | $placeholder_re, |
145 | $expr_start_re, |
1ec9b9e3 |
146 | $alphanum_cmp_op_re, |
ad591616 |
147 | $binary_op_re, |
148 | $unary_op_re, |
149 | $asc_desc_re, |
150 | $and_or_re, |
151 | $expr_term_re, |
152 | $rhs_term_re, |
ad591616 |
153 | $all_std_keywords_re, |
154 | ) { |
155 | $_ = qr/ \A $_ \z /x; |
156 | } |
157 | |
b4085a1a |
158 | # what can be bunched together under one MISC in an AST |
159 | my $compressable_node_re = qr/^ \- (?: MISC | LITERAL | PLACEHOLDER ) $/x; |
01dd4e4f |
160 | |
7e5600e9 |
161 | my %indents = ( |
7853a177 |
162 | select => 0, |
163 | update => 0, |
164 | 'insert into' => 0, |
165 | 'delete from' => 0, |
3d910890 |
166 | from => 1, |
91916220 |
167 | where => 0, |
7853a177 |
168 | join => 1, |
169 | 'left join' => 1, |
170 | on => 2, |
2867f4f5 |
171 | having => 0, |
91916220 |
172 | 'group by' => 0, |
173 | 'order by' => 0, |
7853a177 |
174 | set => 1, |
175 | into => 1, |
91916220 |
176 | values => 1, |
c0eaa9fd |
177 | limit => 1, |
178 | offset => 1, |
179 | skip => 1, |
180 | first => 1, |
7e5600e9 |
181 | ); |
182 | |
c54740ba |
183 | |
184 | has [qw( |
185 | newline indent_string indent_amount fill_in_placeholders placeholder_surround |
186 | )] => (is => 'ro'); |
187 | |
188 | has [qw( indentmap colormap )] => ( is => 'ro', default => quote_sub('{}') ); |
189 | |
190 | # class global is in fact desired |
191 | my $merger; |
192 | |
193 | sub BUILDARGS { |
194 | my $class = shift; |
195 | my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_}; |
196 | |
197 | if (my $p = delete $args->{profile}) { |
198 | my %extra_args; |
199 | if ($p eq 'console') { |
200 | %extra_args = ( |
201 | fill_in_placeholders => 1, |
202 | placeholder_surround => ['?/', ''], |
203 | indent_string => ' ', |
204 | indent_amount => 2, |
205 | newline => "\n", |
206 | colormap => {}, |
207 | indentmap => \%indents, |
208 | |
209 | ! ( eval { require Term::ANSIColor } ) ? () : do { |
aafbf833 |
210 | my $c = \&Term::ANSIColor::color; |
6d388c84 |
211 | |
212 | my $red = [$c->('red') , $c->('reset')]; |
213 | my $cyan = [$c->('cyan') , $c->('reset')]; |
214 | my $green = [$c->('green') , $c->('reset')]; |
215 | my $yellow = [$c->('yellow') , $c->('reset')]; |
216 | my $blue = [$c->('blue') , $c->('reset')]; |
217 | my $magenta = [$c->('magenta'), $c->('reset')]; |
218 | my $b_o_w = [$c->('black on_white'), $c->('reset')]; |
aafbf833 |
219 | ( |
fb98df48 |
220 | placeholder_surround => [$c->('black on_magenta'), $c->('reset')], |
aafbf833 |
221 | colormap => { |
6d388c84 |
222 | 'begin work' => $b_o_w, |
223 | commit => $b_o_w, |
224 | rollback => $b_o_w, |
225 | savepoint => $b_o_w, |
226 | 'rollback to savepoint' => $b_o_w, |
227 | 'release savepoint' => $b_o_w, |
228 | |
229 | select => $red, |
230 | 'insert into' => $red, |
231 | update => $red, |
232 | 'delete from' => $red, |
233 | |
234 | set => $cyan, |
235 | from => $cyan, |
236 | |
237 | where => $green, |
238 | values => $yellow, |
239 | |
240 | join => $magenta, |
241 | 'left join' => $magenta, |
242 | on => $blue, |
243 | |
244 | 'group by' => $yellow, |
2867f4f5 |
245 | having => $yellow, |
6d388c84 |
246 | 'order by' => $yellow, |
247 | |
248 | skip => $green, |
249 | first => $green, |
250 | limit => $green, |
251 | offset => $green, |
aafbf833 |
252 | } |
253 | ); |
c54740ba |
254 | }, |
255 | ); |
256 | } |
257 | elsif ($p eq 'console_monochrome') { |
258 | %extra_args = ( |
259 | fill_in_placeholders => 1, |
260 | placeholder_surround => ['?/', ''], |
261 | indent_string => ' ', |
262 | indent_amount => 2, |
263 | newline => "\n", |
264 | indentmap => \%indents, |
265 | ); |
266 | } |
267 | elsif ($p eq 'html') { |
268 | %extra_args = ( |
269 | fill_in_placeholders => 1, |
270 | placeholder_surround => ['<span class="placeholder">', '</span>'], |
271 | indent_string => ' ', |
272 | indent_amount => 2, |
273 | newline => "<br />\n", |
274 | colormap => { map { |
275 | (my $class = $_) =~ s/\s+/-/g; |
276 | ( $_ => [ qq|<span class="$class">|, '</span>' ] ) |
277 | } ( |
278 | keys %indents, |
279 | qw(commit rollback savepoint), |
280 | 'begin work', 'rollback to savepoint', 'release savepoint', |
281 | ) }, |
282 | indentmap => \%indents, |
283 | ); |
284 | } |
285 | elsif ($p eq 'none') { |
286 | # nada |
287 | } |
288 | else { |
289 | croak "No such profile '$p'"; |
290 | } |
291 | |
292 | # see if we got any duplicates and merge if needed |
293 | if (scalar grep { exists $args->{$_} } keys %extra_args) { |
294 | # heavy-duty merge |
295 | $args = ($merger ||= do { |
296 | require Hash::Merge; |
297 | my $m = Hash::Merge->new; |
298 | |
299 | $m->specify_behavior({ |
300 | SCALAR => { |
301 | SCALAR => sub { $_[1] }, |
302 | ARRAY => sub { [ $_[0], @{$_[1]} ] }, |
303 | HASH => sub { $_[1] }, |
304 | }, |
305 | ARRAY => { |
306 | SCALAR => sub { $_[1] }, |
307 | ARRAY => sub { $_[1] }, |
308 | HASH => sub { $_[1] }, |
309 | }, |
310 | HASH => { |
311 | SCALAR => sub { $_[1] }, |
312 | ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] }, |
313 | HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) }, |
314 | }, |
315 | }, 'SQLA::Tree Behavior' ); |
316 | |
317 | $m; |
318 | })->merge(\%extra_args, $args ); |
319 | |
320 | } |
321 | else { |
322 | $args = { %extra_args, %$args }; |
323 | } |
324 | } |
325 | |
326 | $args; |
75c3a063 |
327 | } |
d695b0ad |
328 | |
01dd4e4f |
329 | sub parse { |
d695b0ad |
330 | my ($self, $s) = @_; |
01dd4e4f |
331 | |
70c6f0e9 |
332 | return [] unless defined $s; |
333 | |
01dd4e4f |
334 | # tokenize string, and remove all optional whitespace |
335 | my $tokens = []; |
336 | foreach my $token (split $tokenizer_re, $s) { |
b3b79607 |
337 | push @$tokens, $token if ( |
338 | defined $token |
339 | and |
340 | length $token |
09931431 |
341 | and |
b3b79607 |
342 | $token =~ /\S/ |
343 | ); |
01dd4e4f |
344 | } |
6f2a5b66 |
345 | |
346 | return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ]; |
01dd4e4f |
347 | } |
348 | |
349 | sub _recurse_parse { |
d695b0ad |
350 | my ($self, $tokens, $state) = @_; |
01dd4e4f |
351 | |
6f2a5b66 |
352 | my @left; |
01dd4e4f |
353 | while (1) { # left-associative parsing |
354 | |
6f2a5b66 |
355 | if ( ! @$tokens |
01dd4e4f |
356 | or |
6f2a5b66 |
357 | ($state == PARSE_IN_PARENS && $tokens->[0] eq ')') |
01dd4e4f |
358 | or |
6f2a5b66 |
359 | ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re ) |
0769ac0e |
360 | or |
6f2a5b66 |
361 | ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re ) |
01dd4e4f |
362 | or |
ad591616 |
363 | ($state == PARSE_LIST_ELT && ( $tokens->[0] eq ',' or $tokens->[0] =~ $expr_term_re ) ) |
01dd4e4f |
364 | ) { |
6f2a5b66 |
365 | return @left; |
01dd4e4f |
366 | } |
367 | |
368 | my $token = shift @$tokens; |
369 | |
370 | # nested expression in () |
371 | if ($token eq '(' ) { |
6f2a5b66 |
372 | my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS); |
373 | $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right); |
374 | $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right); |
375 | |
376 | push @left, [ '-PAREN' => \@right ]; |
377 | } |
378 | |
379 | # AND/OR |
ad591616 |
380 | elsif ($token =~ $and_or_re) { |
6f2a5b66 |
381 | my $op = uc $token; |
01dd4e4f |
382 | |
6f2a5b66 |
383 | my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
384 | |
385 | # Merge chunks if "logic" matches |
386 | @left = [ $op => [ @left, (@right and $op eq $right[0][0]) |
387 | ? @{ $right[0][1] } |
388 | : @right |
389 | ] ]; |
01dd4e4f |
390 | } |
b3b79607 |
391 | |
6f2a5b66 |
392 | # LIST (,) |
393 | elsif ($token eq ',') { |
394 | |
395 | my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT); |
396 | |
397 | # deal with malformed lists ( foo, bar, , baz ) |
398 | @right = [] unless @right; |
01dd4e4f |
399 | |
6f2a5b66 |
400 | @right = [ -MISC => [ @right ] ] if @right > 1; |
401 | |
402 | if (!@left) { |
403 | @left = [ -LIST => [ [], @right ] ]; |
404 | } |
405 | elsif ($left[0][0] eq '-LIST') { |
406 | push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST') |
407 | ? @{$right[0][1]} |
408 | : @right |
409 | ; |
01dd4e4f |
410 | } |
411 | else { |
6f2a5b66 |
412 | @left = [ -LIST => [ @left, @right ] ]; |
01dd4e4f |
413 | } |
414 | } |
6f2a5b66 |
415 | |
01dd4e4f |
416 | # binary operator keywords |
6f2a5b66 |
417 | elsif ($token =~ $binary_op_re) { |
01dd4e4f |
418 | my $op = uc $token; |
6f2a5b66 |
419 | |
420 | my @right = $self->_recurse_parse($tokens, PARSE_RHS); |
01dd4e4f |
421 | |
422 | # A between with a simple LITERAL for a 1st RHS argument needs a |
423 | # rerun of the search to (hopefully) find the proper AND construct |
6f2a5b66 |
424 | if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') { |
425 | unshift @$tokens, $right[1][0]; |
426 | @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
01dd4e4f |
427 | } |
428 | |
08e16360 |
429 | push @left, [$op => [ (@left ? pop @left : ''), @right ]]; |
01dd4e4f |
430 | } |
6f2a5b66 |
431 | |
432 | # unary op keywords |
433 | elsif ( $token =~ $unary_op_re ) { |
01dd4e4f |
434 | my $op = uc $token; |
4247c384 |
435 | |
436 | # normalize RNO explicitly |
437 | $op = 'ROW_NUMBER() OVER' if $op =~ /^$rno_re$/; |
438 | |
6f2a5b66 |
439 | my @right = $self->_recurse_parse ($tokens, PARSE_RHS); |
440 | |
441 | push @left, [ $op => \@right ]; |
01dd4e4f |
442 | } |
6f2a5b66 |
443 | |
444 | # expression terminator keywords |
445 | elsif ( $token =~ $expr_start_re ) { |
01dd4e4f |
446 | my $op = uc $token; |
6f2a5b66 |
447 | my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
01dd4e4f |
448 | |
6f2a5b66 |
449 | push @left, [ $op => \@right ]; |
01dd4e4f |
450 | } |
6f2a5b66 |
451 | |
452 | # a '?' |
4e914a7c |
453 | elsif ( $token =~ $placeholder_re) { |
6f2a5b66 |
454 | push @left, [ -PLACEHOLDER => [ $token ] ]; |
455 | } |
456 | |
457 | # check if the current token is an unknown op-start |
1ec9b9e3 |
458 | elsif (@$tokens and ($tokens->[0] eq '(' or $tokens->[0] =~ $placeholder_re ) ) { |
6f2a5b66 |
459 | push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ]; |
4e914a7c |
460 | } |
6f2a5b66 |
461 | |
b3b79607 |
462 | # we're now in "unknown token" land - start eating tokens until |
6f30911f |
463 | # we see something familiar, OR in the case of RHS (binop) stop |
464 | # after the first token |
e2a120ce |
465 | # Also stop processing when we could end up with an unknown func |
01dd4e4f |
466 | else { |
6f2a5b66 |
467 | my @lits = [ -LITERAL => [$token] ]; |
b3b79607 |
468 | |
b4085a1a |
469 | unshift @lits, pop @left if @left == 1; |
470 | |
6f30911f |
471 | unless ( $state == PARSE_RHS ) { |
e2a120ce |
472 | while ( |
473 | @$tokens |
474 | and |
475 | $tokens->[0] !~ $all_std_keywords_re |
476 | and |
477 | ! ( @$tokens > 1 and $tokens->[1] eq '(' ) |
478 | ) { |
6f30911f |
479 | push @lits, [ -LITERAL => [ shift @$tokens ] ]; |
b4085a1a |
480 | } |
6f30911f |
481 | } |
6f2a5b66 |
482 | |
6f2a5b66 |
483 | @lits = [ -MISC => [ @lits ] ] if @lits > 1; |
484 | |
485 | push @left, @lits; |
486 | } |
b3b79607 |
487 | |
b4085a1a |
488 | # compress -LITERAL -MISC and -PLACEHOLDER pieces into a single |
489 | # -MISC container |
490 | if (@left > 1) { |
491 | my $i = 0; |
492 | while ($#left > $i) { |
493 | if ($left[$i][0] =~ $compressable_node_re and $left[$i+1][0] =~ $compressable_node_re) { |
494 | splice @left, $i, 2, [ -MISC => [ |
495 | map { $_->[0] eq '-MISC' ? @{$_->[1]} : $_ } (@left[$i, $i+1]) |
496 | ]]; |
497 | } |
498 | else { |
499 | $i++; |
500 | } |
501 | } |
502 | } |
503 | |
504 | return @left if $state == PARSE_RHS; |
6f30911f |
505 | |
b4085a1a |
506 | # deal with post-fix operators |
507 | if (@$tokens) { |
508 | # asc/desc |
6f2a5b66 |
509 | if ($tokens->[0] =~ $asc_desc_re) { |
1ec9b9e3 |
510 | @left = [ ('-' . uc (shift @$tokens)) => [ @left ] ]; |
6f2a5b66 |
511 | } |
01dd4e4f |
512 | } |
513 | } |
514 | } |
515 | |
d695b0ad |
516 | sub format_keyword { |
517 | my ($self, $keyword) = @_; |
518 | |
1536de15 |
519 | if (my $around = $self->colormap->{lc $keyword}) { |
d695b0ad |
520 | $keyword = "$around->[0]$keyword$around->[1]"; |
521 | } |
522 | |
523 | return $keyword |
524 | } |
525 | |
728f26a2 |
526 | my %starters = ( |
527 | select => 1, |
528 | update => 1, |
529 | 'insert into' => 1, |
530 | 'delete from' => 1, |
531 | ); |
532 | |
f2ab166a |
533 | sub pad_keyword { |
a24cc3a0 |
534 | my ($self, $keyword, $depth) = @_; |
e171c446 |
535 | |
536 | my $before = ''; |
1536de15 |
537 | if (defined $self->indentmap->{lc $keyword}) { |
538 | $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword}); |
a24cc3a0 |
539 | } |
728f26a2 |
540 | $before = '' if $depth == 0 and defined $starters{lc $keyword}; |
e4570c8e |
541 | return [$before, '']; |
a24cc3a0 |
542 | } |
543 | |
1536de15 |
544 | sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) } |
a24cc3a0 |
545 | |
a97eb57c |
546 | sub _is_key { |
547 | my ($self, $tree) = @_; |
0569a14f |
548 | $tree = $tree->[0] while ref $tree; |
549 | |
a97eb57c |
550 | defined $tree && defined $self->indentmap->{lc $tree}; |
0569a14f |
551 | } |
552 | |
9d11f0d4 |
553 | sub fill_in_placeholder { |
fb272e73 |
554 | my ($self, $bindargs) = @_; |
555 | |
556 | if ($self->fill_in_placeholders) { |
ad46269d |
557 | my $val = shift @{$bindargs} || ''; |
4712657d |
558 | my $quoted = $val =~ s/^(['"])(.*)\1$/$2/; |
9d11f0d4 |
559 | my ($left, $right) = @{$self->placeholder_surround}; |
fb272e73 |
560 | $val =~ s/\\/\\\\/g; |
561 | $val =~ s/'/\\'/g; |
4712657d |
562 | $val = qq('$val') if $quoted; |
563 | return qq($left$val$right) |
fb272e73 |
564 | } |
565 | return '?' |
566 | } |
567 | |
3a247d23 |
568 | # FIXME - terrible name for a user facing API |
01dd4e4f |
569 | sub unparse { |
3a247d23 |
570 | my ($self, $tree, $bindargs) = @_; |
571 | $self->_unparse($tree, [@{$bindargs||[]}], 0); |
572 | } |
a24cc3a0 |
573 | |
3a247d23 |
574 | sub _unparse { |
575 | my ($self, $tree, $bindargs, $depth) = @_; |
01dd4e4f |
576 | |
0769ac0e |
577 | if (not $tree or not @$tree) { |
01dd4e4f |
578 | return ''; |
579 | } |
a24cc3a0 |
580 | |
007f0853 |
581 | # FIXME - needs a config switch to disable |
c01ac648 |
582 | $self->_parenthesis_unroll($tree); |
007f0853 |
583 | |
6f2a5b66 |
584 | my ($op, $args) = @{$tree}[0,1]; |
0769ac0e |
585 | |
6f2a5b66 |
586 | if (! defined $op or (! ref $op and ! defined $args) ) { |
0769ac0e |
587 | require Data::Dumper; |
588 | Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s", |
589 | Data::Dumper::Dumper($tree) |
590 | ) ); |
591 | } |
a24cc3a0 |
592 | |
6f2a5b66 |
593 | if (ref $op) { |
3a247d23 |
594 | return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree); |
01dd4e4f |
595 | } |
6f2a5b66 |
596 | elsif ($op eq '-LITERAL') { # literal has different sig |
597 | return $args->[0]; |
01dd4e4f |
598 | } |
6f2a5b66 |
599 | elsif ($op eq '-PLACEHOLDER') { |
4e914a7c |
600 | return $self->fill_in_placeholder($bindargs); |
601 | } |
6f2a5b66 |
602 | elsif ($op eq '-PAREN') { |
c4d7cfcf |
603 | return sprintf ('( %s )', |
6f2a5b66 |
604 | join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} ) |
e4570c8e |
605 | . |
6f2a5b66 |
606 | ($self->_is_key($args) |
e4570c8e |
607 | ? ( $self->newline||'' ) . $self->indent($depth + 1) |
608 | : '' |
609 | ) |
610 | ); |
01dd4e4f |
611 | } |
ad591616 |
612 | elsif ($op eq 'AND' or $op eq 'OR' or $op =~ $binary_op_re ) { |
6f2a5b66 |
613 | return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args}); |
614 | } |
615 | elsif ($op eq '-LIST' ) { |
616 | return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args}); |
01dd4e4f |
617 | } |
6f2a5b66 |
618 | elsif ($op eq '-MISC' ) { |
619 | return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args}); |
b3b79607 |
620 | } |
73835ff0 |
621 | elsif ($op =~ qr/^-(ASC|DESC)$/ ) { |
622 | my $dir = $1; |
623 | return join (' ', (map $self->_unparse($_, $bindargs, $depth), @{$args}), $dir); |
624 | } |
01dd4e4f |
625 | else { |
6f2a5b66 |
626 | my ($l, $r) = @{$self->pad_keyword($op, $depth)}; |
87abf9bc |
627 | |
628 | my $rhs = $self->_unparse($args, $bindargs, $depth); |
629 | |
630 | return sprintf "$l%s$r", join( |
6f2a5b66 |
631 | ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' ) |
c4d7cfcf |
632 | ? '' # mysql-- |
633 | : ' ' |
634 | , |
87abf9bc |
635 | $self->format_keyword($op), |
636 | (length $rhs ? $rhs : () ), |
637 | ); |
01dd4e4f |
638 | } |
639 | } |
640 | |
bb54fcb4 |
641 | # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics |
642 | my @unrollable_ops = ( |
643 | 'ON', |
644 | 'WHERE', |
645 | 'GROUP \s+ BY', |
646 | 'HAVING', |
647 | 'ORDER \s+ BY', |
6e9a377b |
648 | 'I?LIKE', |
bb54fcb4 |
649 | ); |
650 | my $unrollable_ops_re = join ' | ', @unrollable_ops; |
651 | $unrollable_ops_re = qr/$unrollable_ops_re/xi; |
652 | |
653 | sub _parenthesis_unroll { |
654 | my $self = shift; |
655 | my $ast = shift; |
656 | |
bb54fcb4 |
657 | return unless (ref $ast and ref $ast->[1]); |
658 | |
659 | my $changes; |
660 | do { |
661 | my @children; |
662 | $changes = 0; |
663 | |
664 | for my $child (@{$ast->[1]}) { |
007f0853 |
665 | |
bb54fcb4 |
666 | # the current node in this loop is *always* a PAREN |
6f2a5b66 |
667 | if (! ref $child or ! @$child or $child->[0] ne '-PAREN') { |
bb54fcb4 |
668 | push @children, $child; |
669 | next; |
670 | } |
671 | |
a4d17ff1 |
672 | my $parent_op = $ast->[0]; |
673 | |
bb54fcb4 |
674 | # unroll nested parenthesis |
a4d17ff1 |
675 | while ( $parent_op ne 'IN' and @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') { |
bb54fcb4 |
676 | $child = $child->[1][0]; |
677 | $changes++; |
678 | } |
679 | |
a4d17ff1 |
680 | # set to CHILD in the case of PARENT ( CHILD ) |
681 | # but NOT in the case of PARENT( CHILD1, CHILD2 ) |
682 | my $single_child_op = (@{$child->[1]} == 1) ? $child->[1][0][0] : ''; |
683 | |
684 | my $child_op_argc = $single_child_op ? scalar @{$child->[1][0][1]} : undef; |
685 | |
686 | my $single_grandchild_op |
687 | = ( $child_op_argc||0 == 1 and ref $child->[1][0][1][0] eq 'ARRAY' ) |
688 | ? $child->[1][0][1][0][0] |
689 | : '' |
690 | ; |
691 | |
0ec2e265 |
692 | # if the parent operator explicitly allows it AND the child isn't a subselect |
693 | # nuke the parenthesis |
a4d17ff1 |
694 | if ($parent_op =~ $unrollable_ops_re and $single_child_op ne 'SELECT') { |
6f2a5b66 |
695 | push @children, @{$child->[1]}; |
696 | $changes++; |
697 | } |
698 | |
bb54fcb4 |
699 | # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list |
6f2a5b66 |
700 | elsif ( |
a4d17ff1 |
701 | $single_child_op eq $parent_op |
702 | and |
703 | ( $parent_op eq 'AND' or $parent_op eq 'OR') |
bb54fcb4 |
704 | ) { |
705 | push @children, @{$child->[1][0][1]}; |
706 | $changes++; |
707 | } |
708 | |
bb54fcb4 |
709 | # only *ONE* LITERAL or placeholder element |
6e9a377b |
710 | # as an AND/OR/NOT argument |
bb54fcb4 |
711 | elsif ( |
a4d17ff1 |
712 | ( $single_child_op eq '-LITERAL' or $single_child_op eq '-PLACEHOLDER' ) |
713 | and |
714 | ( $parent_op eq 'AND' or $parent_op eq 'OR' or $parent_op eq 'NOT' ) |
bb54fcb4 |
715 | ) { |
6f2a5b66 |
716 | push @children, @{$child->[1]}; |
bb54fcb4 |
717 | $changes++; |
718 | } |
719 | |
007f0853 |
720 | # an AND/OR expression with only one binop in the parenthesis |
721 | # with exactly two grandchildren |
bb54fcb4 |
722 | # the only time when we can *not* unroll this is when both |
723 | # the parent and the child are mathops (in which case we'll |
724 | # break precedence) or when the child is BETWEEN (special |
725 | # case) |
726 | elsif ( |
a4d17ff1 |
727 | ($parent_op eq 'AND' or $parent_op eq 'OR') |
007f0853 |
728 | and |
a4d17ff1 |
729 | $single_child_op =~ $binary_op_re |
bb54fcb4 |
730 | and |
a4d17ff1 |
731 | $single_child_op ne 'BETWEEN' |
bb54fcb4 |
732 | and |
a4d17ff1 |
733 | $child_op_argc == 2 |
bb54fcb4 |
734 | and |
735 | ! ( |
a4d17ff1 |
736 | $single_child_op =~ $alphanum_cmp_op_re |
bb54fcb4 |
737 | and |
a4d17ff1 |
738 | $parent_op =~ $alphanum_cmp_op_re |
bb54fcb4 |
739 | ) |
740 | ) { |
6f2a5b66 |
741 | push @children, @{$child->[1]}; |
bb54fcb4 |
742 | $changes++; |
743 | } |
744 | |
745 | # a function binds tighter than a mathop - see if our ancestor is a |
746 | # mathop, and our content is: |
747 | # a single non-mathop child with a single PAREN grandchild which |
748 | # would indicate mathop ( nonmathop ( ... ) ) |
749 | # or a single non-mathop with a single LITERAL ( nonmathop foo ) |
750 | # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? ) |
751 | elsif ( |
a4d17ff1 |
752 | $single_child_op |
bb54fcb4 |
753 | and |
a4d17ff1 |
754 | $parent_op =~ $alphanum_cmp_op_re |
bb54fcb4 |
755 | and |
a4d17ff1 |
756 | $single_child_op !~ $alphanum_cmp_op_re |
bb54fcb4 |
757 | and |
a4d17ff1 |
758 | $child_op_argc == 1 |
bb54fcb4 |
759 | and |
760 | ( |
a4d17ff1 |
761 | $single_grandchild_op eq '-PAREN' |
bb54fcb4 |
762 | or |
a4d17ff1 |
763 | $single_grandchild_op eq '-LITERAL' |
bb54fcb4 |
764 | or |
a4d17ff1 |
765 | $single_grandchild_op eq '-PLACEHOLDER' |
bb54fcb4 |
766 | ) |
767 | ) { |
6f2a5b66 |
768 | push @children, @{$child->[1]}; |
bb54fcb4 |
769 | $changes++; |
770 | } |
771 | |
1de1d085 |
772 | # a construct of ... ( somefunc ( ... ) ) ... can safely lose the outer parens |
773 | # except for the case of ( NOT ( ... ) ) which has already been handled earlier |
0ec2e265 |
774 | # and except for the case of RNO, where the double are explicit syntax |
1de1d085 |
775 | elsif ( |
a4d17ff1 |
776 | $parent_op ne 'ROW_NUMBER() OVER' |
1de1d085 |
777 | and |
a4d17ff1 |
778 | $single_child_op |
1de1d085 |
779 | and |
a4d17ff1 |
780 | $single_child_op ne 'NOT' |
1de1d085 |
781 | and |
a4d17ff1 |
782 | $child_op_argc == 1 |
1de1d085 |
783 | and |
a4d17ff1 |
784 | $single_grandchild_op eq '-PAREN' |
1de1d085 |
785 | ) { |
786 | push @children, @{$child->[1]}; |
787 | $changes++; |
788 | } |
789 | |
bb54fcb4 |
790 | |
791 | # otherwise no more mucking for this pass |
792 | else { |
793 | push @children, $child; |
794 | } |
795 | } |
796 | |
797 | $ast->[1] = \@children; |
798 | |
799 | } while ($changes); |
bb54fcb4 |
800 | } |
801 | |
0c2de280 |
802 | sub _strip_asc_from_order_by { |
803 | my ($self, $ast) = @_; |
804 | |
805 | return $ast if ( |
806 | ref $ast ne 'ARRAY' |
807 | or |
808 | $ast->[0] ne 'ORDER BY' |
809 | ); |
810 | |
811 | |
812 | my $to_replace; |
813 | |
814 | if (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-ASC') { |
815 | $to_replace = [ $ast->[1][0] ]; |
816 | } |
817 | elsif (@{$ast->[1]} == 1 and $ast->[1][0][0] eq '-LIST') { |
818 | $to_replace = [ grep { $_->[0] eq '-ASC' } @{$ast->[1][0][1]} ]; |
819 | } |
820 | |
821 | @$_ = @{$_->[1][0]} for @$to_replace; |
822 | |
823 | $ast; |
824 | } |
825 | |
fb272e73 |
826 | sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) } |
01dd4e4f |
827 | |
828 | 1; |
829 | |
3be357b0 |
830 | =pod |
831 | |
b912ee1e |
832 | =head1 NAME |
833 | |
834 | SQL::Abstract::Tree - Represent SQL as an AST |
835 | |
3be357b0 |
836 | =head1 SYNOPSIS |
837 | |
838 | my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' }); |
839 | |
840 | print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2'); |
841 | |
842 | # SELECT * |
843 | # FROM foo |
844 | # WHERE foo.a > 2 |
845 | |
6b1bf9f8 |
846 | =head1 METHODS |
847 | |
848 | =head2 new |
849 | |
850 | my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' }); |
851 | |
c22f502d |
852 | $args = { |
853 | profile => 'console', # predefined profile to use (default: 'none') |
854 | fill_in_placeholders => 1, # true for placeholder population |
9d11f0d4 |
855 | placeholder_surround => # The strings that will be wrapped around |
856 | [GREEN, RESET], # populated placeholders if the above is set |
c22f502d |
857 | indent_string => ' ', # the string used when indenting |
858 | indent_amount => 2, # how many of above string to use for a single |
859 | # indent level |
860 | newline => "\n", # string for newline |
861 | colormap => { |
862 | select => [RED, RESET], # a pair of strings defining what to surround |
863 | # the keyword with for colorization |
864 | # ... |
865 | }, |
866 | indentmap => { |
867 | select => 0, # A zero means that the keyword will start on |
868 | # a new line |
869 | from => 1, # Any other positive integer means that after |
870 | on => 2, # said newline it will get that many indents |
871 | # ... |
872 | }, |
873 | } |
874 | |
875 | Returns a new SQL::Abstract::Tree object. All arguments are optional. |
876 | |
877 | =head3 profiles |
878 | |
879 | There are four predefined profiles, C<none>, C<console>, C<console_monochrome>, |
880 | and C<html>. Typically a user will probably just use C<console> or |
881 | C<console_monochrome>, but if something about a profile bothers you, merely |
882 | use the profile and override the parts that you don't like. |
883 | |
6b1bf9f8 |
884 | =head2 format |
885 | |
c22f502d |
886 | $sqlat->format('SELECT * FROM bar WHERE x = ?', [1]) |
887 | |
888 | Takes C<$sql> and C<\@bindargs>. |
6b1bf9f8 |
889 | |
1a3cc911 |
890 | Returns a formatting string based on the string passed in |
ee4227a7 |
891 | |
892 | =head2 parse |
893 | |
894 | $sqlat->parse('SELECT * FROM bar WHERE x = ?') |
895 | |
896 | Returns a "tree" representing passed in SQL. Please do not depend on the |
897 | structure of the returned tree. It may be stable at some point, but not yet. |
898 | |
899 | =head2 unparse |
900 | |
90d0250b |
901 | $sqlat->unparse($tree_structure, \@bindargs) |
ee4227a7 |
902 | |
903 | Transform "tree" into SQL, applying various transforms on the way. |
904 | |
905 | =head2 format_keyword |
906 | |
907 | $sqlat->format_keyword('SELECT') |
908 | |
909 | Currently this just takes a keyword and puts the C<colormap> stuff around it. |
910 | Later on it may do more and allow for coderef based transforms. |
911 | |
f2ab166a |
912 | =head2 pad_keyword |
ee4227a7 |
913 | |
f2ab166a |
914 | my ($before, $after) = @{$sqlat->pad_keyword('SELECT')}; |
ee4227a7 |
915 | |
916 | Returns whitespace to be inserted around a keyword. |
9d11f0d4 |
917 | |
918 | =head2 fill_in_placeholder |
919 | |
920 | my $value = $sqlat->fill_in_placeholder(\@bindargs) |
921 | |
922 | Removes last arg from passed arrayref and returns it, surrounded with |
923 | the values in placeholder_surround, and then surrounded with single quotes. |
f2ab166a |
924 | |
925 | =head2 indent |
926 | |
927 | Returns as many indent strings as indent amounts times the first argument. |
928 | |
929 | =head1 ACCESSORS |
930 | |
931 | =head2 colormap |
932 | |
933 | See L</new> |
934 | |
935 | =head2 fill_in_placeholders |
936 | |
937 | See L</new> |
938 | |
939 | =head2 indent_amount |
940 | |
941 | See L</new> |
942 | |
943 | =head2 indent_string |
944 | |
945 | See L</new> |
946 | |
947 | =head2 indentmap |
948 | |
949 | See L</new> |
950 | |
951 | =head2 newline |
952 | |
953 | See L</new> |
954 | |
955 | =head2 placeholder_surround |
956 | |
957 | See L</new> |
958 | |