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