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