Massively refactor arbitrary sql parser code
[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
12__PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
13 newline indent_string indent_amount colormap indentmap fill_in_placeholders
14 placeholder_surround
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
94# * BETWEEN without paranthesis around the ANDed arguments (which
95# makes it a non-binary op) is detected and accomodated in
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
100# testing as one is tighter than the other, plus mathops have different look
101# ahead/behind (e.g. "x"="y" )
102my @math_op_keywords = (qw/ < > != <> = <= >= /);
103my $math_re = join ("\n\t|\n", map
104 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
105 @math_op_keywords
01dd4e4f 106);
b7b0f832 107$math_re = qr/$math_re/x;
0769ac0e 108
109sub _math_op_re { $math_re }
110
111
112my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
b3b79607 113$binary_op_re = join "\n\t|\n",
6c4d8eb8 114 "$op_look_behind (?i: $binary_op_re | AS ) $op_look_ahead",
b3b79607 115 $math_re,
116 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
117;
b7b0f832 118$binary_op_re = qr/$binary_op_re/x;
0769ac0e 119
120sub _binary_op_re { $binary_op_re }
121
6f2a5b66 122my $unary_op_re = '(?: NOT \s+ EXISTS | NOT )';
123$unary_op_re = join "\n\t|\n",
124 "$op_look_behind (?i: $unary_op_re ) $op_look_ahead",
125;
126$unary_op_re = qr/$unary_op_re/x;
127
128sub _unary_op_re { $unary_op_re }
129
b3b79607 130my $all_known_re = join("\n\t|\n",
131 $expr_start_re,
0769ac0e 132 $binary_op_re,
6f2a5b66 133 $unary_op_re,
134 "$op_look_behind (?i: AND|OR|\\* ) $op_look_ahead",
257ecc8a 135 (map { quotemeta $_ } qw/, ( )/),
4e914a7c 136 $placeholder_re,
0769ac0e 137);
01dd4e4f 138
b3b79607 139$all_known_re = qr/$all_known_re/x;
140
141#this one *is* capturing for the split below
142# splits on whitespace if all else fails
143my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
144
145# Parser states for _recurse_parse()
146use constant PARSE_TOP_LEVEL => 0;
147use constant PARSE_IN_EXPR => 1;
148use constant PARSE_IN_PARENS => 2;
149use constant PARSE_IN_FUNC => 3;
150use constant PARSE_RHS => 4;
6f2a5b66 151use constant PARSE_LIST_ELT => 5;
b3b79607 152
6f2a5b66 153my $asc_desc_re = qr/^ (?: ASC | DESC ) $/xi;
b3b79607 154my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
6f2a5b66 155my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | $unary_op_re | $asc_desc_re | (?i: AND | OR | \, ) ) $/x;
156my $common_single_args_re = qr/ ^ (?: \* | $placeholder_re ) $/x;
157my $all_std_keywords_re = qr/^ (?: $rhs_term_re | \( | $common_single_args_re ) $/x;
158
01dd4e4f 159
7e5600e9 160my %indents = (
7853a177 161 select => 0,
162 update => 0,
163 'insert into' => 0,
164 'delete from' => 0,
3d910890 165 from => 1,
91916220 166 where => 0,
7853a177 167 join => 1,
168 'left join' => 1,
169 on => 2,
2867f4f5 170 having => 0,
91916220 171 'group by' => 0,
172 'order by' => 0,
7853a177 173 set => 1,
174 into => 1,
91916220 175 values => 1,
c0eaa9fd 176 limit => 1,
177 offset => 1,
178 skip => 1,
179 first => 1,
7e5600e9 180);
181
75c3a063 182my %profiles = (
183 console => {
84c65032 184 fill_in_placeholders => 1,
9d11f0d4 185 placeholder_surround => ['?/', ''],
1536de15 186 indent_string => ' ',
75c3a063 187 indent_amount => 2,
1536de15 188 newline => "\n",
3be357b0 189 colormap => {},
6d388c84 190 indentmap => \%indents,
aafbf833 191
192 eval { require Term::ANSIColor }
193 ? do {
194 my $c = \&Term::ANSIColor::color;
6d388c84 195
196 my $red = [$c->('red') , $c->('reset')];
197 my $cyan = [$c->('cyan') , $c->('reset')];
198 my $green = [$c->('green') , $c->('reset')];
199 my $yellow = [$c->('yellow') , $c->('reset')];
200 my $blue = [$c->('blue') , $c->('reset')];
201 my $magenta = [$c->('magenta'), $c->('reset')];
202 my $b_o_w = [$c->('black on_white'), $c->('reset')];
aafbf833 203 (
fb98df48 204 placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
aafbf833 205 colormap => {
6d388c84 206 'begin work' => $b_o_w,
207 commit => $b_o_w,
208 rollback => $b_o_w,
209 savepoint => $b_o_w,
210 'rollback to savepoint' => $b_o_w,
211 'release savepoint' => $b_o_w,
212
213 select => $red,
214 'insert into' => $red,
215 update => $red,
216 'delete from' => $red,
217
218 set => $cyan,
219 from => $cyan,
220
221 where => $green,
222 values => $yellow,
223
224 join => $magenta,
225 'left join' => $magenta,
226 on => $blue,
227
228 'group by' => $yellow,
2867f4f5 229 having => $yellow,
6d388c84 230 'order by' => $yellow,
231
232 skip => $green,
233 first => $green,
234 limit => $green,
235 offset => $green,
aafbf833 236 }
237 );
238 } : (),
3be357b0 239 },
240 console_monochrome => {
84c65032 241 fill_in_placeholders => 1,
9d11f0d4 242 placeholder_surround => ['?/', ''],
3be357b0 243 indent_string => ' ',
244 indent_amount => 2,
245 newline => "\n",
246 colormap => {},
6d388c84 247 indentmap => \%indents,
7e5600e9 248 },
249 html => {
84c65032 250 fill_in_placeholders => 1,
9d11f0d4 251 placeholder_surround => ['<span class="placeholder">', '</span>'],
7e5600e9 252 indent_string => '&nbsp;',
253 indent_amount => 2,
254 newline => "<br />\n",
255 colormap => {
7853a177 256 select => ['<span class="select">' , '</span>'],
257 'insert into' => ['<span class="insert-into">' , '</span>'],
258 update => ['<span class="select">' , '</span>'],
259 'delete from' => ['<span class="delete-from">' , '</span>'],
c0eaa9fd 260
261 set => ['<span class="set">', '</span>'],
7853a177 262 from => ['<span class="from">' , '</span>'],
c0eaa9fd 263
264 where => ['<span class="where">' , '</span>'],
265 values => ['<span class="values">', '</span>'],
266
7853a177 267 join => ['<span class="join">' , '</span>'],
c0eaa9fd 268 'left join' => ['<span class="left-join">','</span>'],
7853a177 269 on => ['<span class="on">' , '</span>'],
c0eaa9fd 270
7853a177 271 'group by' => ['<span class="group-by">', '</span>'],
2867f4f5 272 having => ['<span class="having">', '</span>'],
7853a177 273 'order by' => ['<span class="order-by">', '</span>'],
c0eaa9fd 274
275 skip => ['<span class="skip">', '</span>'],
276 first => ['<span class="first">', '</span>'],
277 limit => ['<span class="limit">', '</span>'],
278 offset => ['<span class="offset">', '</span>'],
820bb1f5 279
280 'begin work' => ['<span class="begin-work">', '</span>'],
281 commit => ['<span class="commit">', '</span>'],
282 rollback => ['<span class="rollback">', '</span>'],
283 savepoint => ['<span class="savepoint">', '</span>'],
284 'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
285 'release savepoint' => ['<span class="release-savepoint">', '</span>'],
1536de15 286 },
6d388c84 287 indentmap => \%indents,
75c3a063 288 },
289 none => {
1536de15 290 colormap => {},
291 indentmap => {},
75c3a063 292 },
293);
294
295sub new {
2fed0b4b 296 my $class = shift;
297 my $args = shift || {};
75c3a063 298
299 my $profile = delete $args->{profile} || 'none';
1c33db5d 300
301 die "No such profile '$profile'!" unless exists $profiles{$profile};
302
bc482085 303 my $data = $merger->merge( $profiles{$profile}, $args );
75c3a063 304
305 bless $data, $class
306}
d695b0ad 307
01dd4e4f 308sub parse {
d695b0ad 309 my ($self, $s) = @_;
01dd4e4f 310
311 # tokenize string, and remove all optional whitespace
312 my $tokens = [];
313 foreach my $token (split $tokenizer_re, $s) {
b3b79607 314 push @$tokens, $token if (
315 defined $token
316 and
317 length $token
09931431 318 and
b3b79607 319 $token =~ /\S/
320 );
01dd4e4f 321 }
6f2a5b66 322
323 return [ $self->_recurse_parse($tokens, PARSE_TOP_LEVEL) ];
01dd4e4f 324}
325
326sub _recurse_parse {
d695b0ad 327 my ($self, $tokens, $state) = @_;
01dd4e4f 328
6f2a5b66 329 my @left;
01dd4e4f 330 while (1) { # left-associative parsing
331
6f2a5b66 332 if ( ! @$tokens
01dd4e4f 333 or
6f2a5b66 334 ($state == PARSE_IN_PARENS && $tokens->[0] eq ')')
01dd4e4f 335 or
6f2a5b66 336 ($state == PARSE_IN_EXPR && $tokens->[0] =~ $expr_term_re )
0769ac0e 337 or
6f2a5b66 338 ($state == PARSE_RHS && $tokens->[0] =~ $rhs_term_re )
01dd4e4f 339 or
6f2a5b66 340 ($state == PARSE_LIST_ELT && $tokens->[0] =~ qr/^ (?: $expr_term_re | \, ) $/x)
01dd4e4f 341 ) {
6f2a5b66 342 return @left;
01dd4e4f 343 }
344
345 my $token = shift @$tokens;
346
347 # nested expression in ()
348 if ($token eq '(' ) {
6f2a5b66 349 my @right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
350 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse(\@right);
351 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse(\@right);
352
353 push @left, [ '-PAREN' => \@right ];
354 }
355
356 # AND/OR
357 elsif ($token =~ /^ (?: OR | AND ) $/ix ) {
358 my $op = uc $token;
01dd4e4f 359
6f2a5b66 360 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
361
362 # Merge chunks if "logic" matches
363 @left = [ $op => [ @left, (@right and $op eq $right[0][0])
364 ? @{ $right[0][1] }
365 : @right
366 ] ];
01dd4e4f 367 }
b3b79607 368
6f2a5b66 369 # LIST (,)
370 elsif ($token eq ',') {
371
372 my @right = $self->_recurse_parse($tokens, PARSE_LIST_ELT);
373
374 # deal with malformed lists ( foo, bar, , baz )
375 @right = [] unless @right;
01dd4e4f 376
6f2a5b66 377 @right = [ -MISC => [ @right ] ] if @right > 1;
378
379 if (!@left) {
380 @left = [ -LIST => [ [], @right ] ];
381 }
382 elsif ($left[0][0] eq '-LIST') {
383 push @{$left[0][1]}, (@{$right[0]} and $right[0][0] eq '-LIST')
384 ? @{$right[0][1]}
385 : @right
386 ;
01dd4e4f 387 }
388 else {
6f2a5b66 389 @left = [ -LIST => [ @left, @right ] ];
01dd4e4f 390 }
391 }
6f2a5b66 392
01dd4e4f 393 # binary operator keywords
6f2a5b66 394 elsif ($token =~ $binary_op_re) {
01dd4e4f 395 my $op = uc $token;
6f2a5b66 396
397 my @right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 398
399 # A between with a simple LITERAL for a 1st RHS argument needs a
400 # rerun of the search to (hopefully) find the proper AND construct
6f2a5b66 401 if ($op eq 'BETWEEN' and $right[0] eq '-LITERAL') {
402 unshift @$tokens, $right[1][0];
403 @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 404 }
405
6f2a5b66 406 @left = [$op => [ @left, @right ]];
01dd4e4f 407 }
6f2a5b66 408
409 # unary op keywords
410 elsif ( $token =~ $unary_op_re ) {
01dd4e4f 411 my $op = uc $token;
6f2a5b66 412 my @right = $self->_recurse_parse ($tokens, PARSE_RHS);
413
414 push @left, [ $op => \@right ];
01dd4e4f 415 }
6f2a5b66 416
417 # expression terminator keywords
418 elsif ( $token =~ $expr_start_re ) {
01dd4e4f 419 my $op = uc $token;
6f2a5b66 420 my @right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 421
6f2a5b66 422 push @left, [ $op => \@right ];
01dd4e4f 423 }
6f2a5b66 424
425 # a '?'
4e914a7c 426 elsif ( $token =~ $placeholder_re) {
6f2a5b66 427 push @left, [ -PLACEHOLDER => [ $token ] ];
428 }
429
430 # check if the current token is an unknown op-start
431 elsif (@$tokens and $tokens->[0] =~ qr/^ (?: \( | $common_single_args_re ) $/x ) {
432 push @left, [ $token => [ $self->_recurse_parse($tokens, PARSE_RHS) ] ];
4e914a7c 433 }
6f2a5b66 434
b3b79607 435 # we're now in "unknown token" land - start eating tokens until
436 # we see something familiar
01dd4e4f 437 else {
6f2a5b66 438 my @lits = [ -LITERAL => [$token] ];
b3b79607 439
6f2a5b66 440 while (@$tokens and $tokens->[0] !~ $all_std_keywords_re) {
441 push @lits, [ -LITERAL => [ shift @$tokens ] ];
442 }
443
444 if (@left == 1) {
445 unshift @lits, pop @left;
446 }
447
448 @lits = [ -MISC => [ @lits ] ] if @lits > 1;
449
450 push @left, @lits;
451 }
b3b79607 452
6f2a5b66 453 # deal with post-fix operators (only when sql is sane - i.e. we have one element to apply to)
454 if (@left == 1 and @$tokens) {
455
456 # asc/desc
457 if ($tokens->[0] =~ $asc_desc_re) {
458 my $op = shift @$tokens;
459
460 # if -MISC - this is a literal collection, do not promote asc/desc to an op
461 if ($left[0][0] eq '-MISC') {
462 push @{$left[0][1]}, [ -LITERAL => [ $op ] ];
463 }
464 else {
465 @left = [ ('-' . uc ($op)) => [ @left ] ];
466 }
467 }
01dd4e4f 468 }
469 }
470}
471
d695b0ad 472sub format_keyword {
473 my ($self, $keyword) = @_;
474
1536de15 475 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 476 $keyword = "$around->[0]$keyword$around->[1]";
477 }
478
479 return $keyword
480}
481
728f26a2 482my %starters = (
483 select => 1,
484 update => 1,
485 'insert into' => 1,
486 'delete from' => 1,
487);
488
f2ab166a 489sub pad_keyword {
a24cc3a0 490 my ($self, $keyword, $depth) = @_;
e171c446 491
492 my $before = '';
1536de15 493 if (defined $self->indentmap->{lc $keyword}) {
494 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 495 }
728f26a2 496 $before = '' if $depth == 0 and defined $starters{lc $keyword};
e4570c8e 497 return [$before, ''];
a24cc3a0 498}
499
1536de15 500sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 501
a97eb57c 502sub _is_key {
503 my ($self, $tree) = @_;
0569a14f 504 $tree = $tree->[0] while ref $tree;
505
a97eb57c 506 defined $tree && defined $self->indentmap->{lc $tree};
0569a14f 507}
508
9d11f0d4 509sub fill_in_placeholder {
fb272e73 510 my ($self, $bindargs) = @_;
511
512 if ($self->fill_in_placeholders) {
ad46269d 513 my $val = shift @{$bindargs} || '';
4712657d 514 my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
9d11f0d4 515 my ($left, $right) = @{$self->placeholder_surround};
fb272e73 516 $val =~ s/\\/\\\\/g;
517 $val =~ s/'/\\'/g;
4712657d 518 $val = qq('$val') if $quoted;
519 return qq($left$val$right)
fb272e73 520 }
521 return '?'
522}
523
3a247d23 524# FIXME - terrible name for a user facing API
01dd4e4f 525sub unparse {
3a247d23 526 my ($self, $tree, $bindargs) = @_;
527 $self->_unparse($tree, [@{$bindargs||[]}], 0);
528}
a24cc3a0 529
3a247d23 530sub _unparse {
531 my ($self, $tree, $bindargs, $depth) = @_;
01dd4e4f 532
0769ac0e 533 if (not $tree or not @$tree) {
01dd4e4f 534 return '';
535 }
a24cc3a0 536
007f0853 537 # FIXME - needs a config switch to disable
c01ac648 538 $self->_parenthesis_unroll($tree);
007f0853 539
6f2a5b66 540 my ($op, $args) = @{$tree}[0,1];
0769ac0e 541
6f2a5b66 542 if (! defined $op or (! ref $op and ! defined $args) ) {
0769ac0e 543 require Data::Dumper;
544 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
545 Data::Dumper::Dumper($tree)
546 ) );
547 }
a24cc3a0 548
6f2a5b66 549 if (ref $op) {
3a247d23 550 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
01dd4e4f 551 }
6f2a5b66 552 elsif ($op eq '-LITERAL') { # literal has different sig
553 return $args->[0];
01dd4e4f 554 }
6f2a5b66 555 elsif ($op eq '-PLACEHOLDER') {
4e914a7c 556 return $self->fill_in_placeholder($bindargs);
557 }
6f2a5b66 558 elsif ($op eq '-PAREN') {
c4d7cfcf 559 return sprintf ('( %s )',
6f2a5b66 560 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$args} )
e4570c8e 561 .
6f2a5b66 562 ($self->_is_key($args)
e4570c8e 563 ? ( $self->newline||'' ) . $self->indent($depth + 1)
564 : ''
565 )
566 );
01dd4e4f 567 }
6f2a5b66 568 elsif ($op eq 'AND' or $op eq 'OR' or $op =~ / ^ $binary_op_re $ /x ) {
569 return join (" $op ", map $self->_unparse($_, $bindargs, $depth), @{$args});
570 }
571 elsif ($op eq '-LIST' ) {
572 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$args});
01dd4e4f 573 }
6f2a5b66 574 elsif ($op eq '-MISC' ) {
575 return join (' ', map $self->_unparse($_, $bindargs, $depth), @{$args});
b3b79607 576 }
01dd4e4f 577 else {
6f2a5b66 578 my ($l, $r) = @{$self->pad_keyword($op, $depth)};
c4d7cfcf 579 return sprintf "$l%s%s%s$r",
6f2a5b66 580 $self->format_keyword($op),
581 ( ref $args eq 'ARRAY' and @{$args} == 1 and $args->[0][0] eq '-PAREN' )
c4d7cfcf 582 ? '' # mysql--
583 : ' '
584 ,
6f2a5b66 585 $self->_unparse($args, $bindargs, $depth),
c4d7cfcf 586 ;
01dd4e4f 587 }
588}
589
bb54fcb4 590# All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
591my @unrollable_ops = (
592 'ON',
593 'WHERE',
594 'GROUP \s+ BY',
595 'HAVING',
596 'ORDER \s+ BY',
6e9a377b 597 'I?LIKE',
bb54fcb4 598);
599my $unrollable_ops_re = join ' | ', @unrollable_ops;
600$unrollable_ops_re = qr/$unrollable_ops_re/xi;
601
602sub _parenthesis_unroll {
603 my $self = shift;
604 my $ast = shift;
605
bb54fcb4 606 return unless (ref $ast and ref $ast->[1]);
607
608 my $changes;
609 do {
610 my @children;
611 $changes = 0;
612
613 for my $child (@{$ast->[1]}) {
007f0853 614
bb54fcb4 615 # the current node in this loop is *always* a PAREN
6f2a5b66 616 if (! ref $child or ! @$child or $child->[0] ne '-PAREN') {
bb54fcb4 617 push @children, $child;
618 next;
619 }
620
621 # unroll nested parenthesis
6f2a5b66 622 while ( @{$child->[1]} == 1 and $child->[1][0][0] eq '-PAREN') {
bb54fcb4 623 $child = $child->[1][0];
624 $changes++;
625 }
626
6f2a5b66 627 # if the parent operator explcitly allows it nuke the parenthesis
628 if ( $ast->[0] =~ $unrollable_ops_re ) {
629 push @children, @{$child->[1]};
630 $changes++;
631 }
632
bb54fcb4 633 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
6f2a5b66 634 elsif (
635 @{$child->[1]} == 1
636 and
bb54fcb4 637 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
638 and
6f2a5b66 639 $child->[1][0][0] eq $ast->[0]
bb54fcb4 640 ) {
641 push @children, @{$child->[1][0][1]};
642 $changes++;
643 }
644
bb54fcb4 645 # only *ONE* LITERAL or placeholder element
6e9a377b 646 # as an AND/OR/NOT argument
bb54fcb4 647 elsif (
648 @{$child->[1]} == 1 && (
6f2a5b66 649 $child->[1][0][0] eq '-LITERAL'
bb54fcb4 650 or
6f2a5b66 651 $child->[1][0][0] eq '-PLACEHOLDER'
6e9a377b 652 ) && (
653 $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
bb54fcb4 654 )
655 ) {
6f2a5b66 656 push @children, @{$child->[1]};
bb54fcb4 657 $changes++;
658 }
659
007f0853 660 # an AND/OR expression with only one binop in the parenthesis
661 # with exactly two grandchildren
bb54fcb4 662 # the only time when we can *not* unroll this is when both
663 # the parent and the child are mathops (in which case we'll
664 # break precedence) or when the child is BETWEEN (special
665 # case)
666 elsif (
667 @{$child->[1]} == 1
668 and
007f0853 669 ($ast->[0] eq 'AND' or $ast->[0] eq 'OR')
670 and
bb54fcb4 671 $child->[1][0][0] =~ SQL::Abstract::Tree::_binary_op_re()
672 and
673 $child->[1][0][0] ne 'BETWEEN'
674 and
675 @{$child->[1][0][1]} == 2
676 and
677 ! (
678 $child->[1][0][0] =~ SQL::Abstract::Tree::_math_op_re()
679 and
680 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
681 )
682 ) {
6f2a5b66 683 push @children, @{$child->[1]};
bb54fcb4 684 $changes++;
685 }
686
687 # a function binds tighter than a mathop - see if our ancestor is a
688 # mathop, and our content is:
689 # a single non-mathop child with a single PAREN grandchild which
690 # would indicate mathop ( nonmathop ( ... ) )
691 # or a single non-mathop with a single LITERAL ( nonmathop foo )
692 # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
693 elsif (
694 @{$child->[1]} == 1
695 and
696 @{$child->[1][0][1]} == 1
697 and
698 $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
699 and
700 $child->[1][0][0] !~ SQL::Abstract::Tree::_math_op_re
701 and
702 (
6f2a5b66 703 $child->[1][0][1][0][0] eq '-PAREN'
bb54fcb4 704 or
6f2a5b66 705 $child->[1][0][1][0][0] eq '-LITERAL'
bb54fcb4 706 or
6f2a5b66 707 $child->[1][0][1][0][0] eq '-PLACEHOLDER'
bb54fcb4 708 )
709 ) {
6f2a5b66 710 push @children, @{$child->[1]};
bb54fcb4 711 $changes++;
712 }
713
714
715 # otherwise no more mucking for this pass
716 else {
717 push @children, $child;
718 }
719 }
720
721 $ast->[1] = \@children;
722
723 } while ($changes);
bb54fcb4 724}
725
fb272e73 726sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
01dd4e4f 727
7281;
729
3be357b0 730=pod
731
b912ee1e 732=head1 NAME
733
734SQL::Abstract::Tree - Represent SQL as an AST
735
3be357b0 736=head1 SYNOPSIS
737
738 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
739
740 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
741
742 # SELECT *
743 # FROM foo
744 # WHERE foo.a > 2
745
6b1bf9f8 746=head1 METHODS
747
748=head2 new
749
750 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
751
c22f502d 752 $args = {
753 profile => 'console', # predefined profile to use (default: 'none')
754 fill_in_placeholders => 1, # true for placeholder population
9d11f0d4 755 placeholder_surround => # The strings that will be wrapped around
756 [GREEN, RESET], # populated placeholders if the above is set
c22f502d 757 indent_string => ' ', # the string used when indenting
758 indent_amount => 2, # how many of above string to use for a single
759 # indent level
760 newline => "\n", # string for newline
761 colormap => {
762 select => [RED, RESET], # a pair of strings defining what to surround
763 # the keyword with for colorization
764 # ...
765 },
766 indentmap => {
767 select => 0, # A zero means that the keyword will start on
768 # a new line
769 from => 1, # Any other positive integer means that after
770 on => 2, # said newline it will get that many indents
771 # ...
772 },
773 }
774
775Returns a new SQL::Abstract::Tree object. All arguments are optional.
776
777=head3 profiles
778
779There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
780and C<html>. Typically a user will probably just use C<console> or
781C<console_monochrome>, but if something about a profile bothers you, merely
782use the profile and override the parts that you don't like.
783
6b1bf9f8 784=head2 format
785
c22f502d 786 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
787
788Takes C<$sql> and C<\@bindargs>.
6b1bf9f8 789
1a3cc911 790Returns a formatting string based on the string passed in
ee4227a7 791
792=head2 parse
793
794 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
795
796Returns a "tree" representing passed in SQL. Please do not depend on the
797structure of the returned tree. It may be stable at some point, but not yet.
798
799=head2 unparse
800
801 $sqlat->parse($tree_structure, \@bindargs)
802
803Transform "tree" into SQL, applying various transforms on the way.
804
805=head2 format_keyword
806
807 $sqlat->format_keyword('SELECT')
808
809Currently this just takes a keyword and puts the C<colormap> stuff around it.
810Later on it may do more and allow for coderef based transforms.
811
f2ab166a 812=head2 pad_keyword
ee4227a7 813
f2ab166a 814 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
ee4227a7 815
816Returns whitespace to be inserted around a keyword.
9d11f0d4 817
818=head2 fill_in_placeholder
819
820 my $value = $sqlat->fill_in_placeholder(\@bindargs)
821
822Removes last arg from passed arrayref and returns it, surrounded with
823the values in placeholder_surround, and then surrounded with single quotes.
f2ab166a 824
825=head2 indent
826
827Returns as many indent strings as indent amounts times the first argument.
828
829=head1 ACCESSORS
830
831=head2 colormap
832
833See L</new>
834
835=head2 fill_in_placeholders
836
837See L</new>
838
839=head2 indent_amount
840
841See L</new>
842
843=head2 indent_string
844
845See L</new>
846
847=head2 indentmap
848
849See L</new>
850
851=head2 newline
852
853See L</new>
854
855=head2 placeholder_surround
856
857See L</new>
858