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