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