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