release SQL::Abstract 1.69
[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',
01dd4e4f 67 'EXISTS',
68 'GROUP \s+ BY',
69 'HAVING',
70 'ORDER \s+ BY',
71 'LIMIT',
72 'OFFSET',
73 'FOR',
74 'UNION',
75 'INTERSECT',
76 'EXCEPT',
77 'RETURNING',
8d0dd7dc 78 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
01dd4e4f 79);
80
b3b79607 81my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
82$expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
0769ac0e 83
01dd4e4f 84# These are binary operator keywords always a single LHS and RHS
85# * AND/OR are handled separately as they are N-ary
86# * so is NOT as being unary
87# * BETWEEN without paranthesis around the ANDed arguments (which
88# makes it a non-binary op) is detected and accomodated in
89# _recurse_parse()
01dd4e4f 90
0769ac0e 91# this will be included in the $binary_op_re, the distinction is interesting during
92# testing as one is tighter than the other, plus mathops have different look
93# ahead/behind (e.g. "x"="y" )
94my @math_op_keywords = (qw/ < > != <> = <= >= /);
95my $math_re = join ("\n\t|\n", map
96 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
97 @math_op_keywords
01dd4e4f 98);
b7b0f832 99$math_re = qr/$math_re/x;
0769ac0e 100
101sub _math_op_re { $math_re }
102
103
104my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
b3b79607 105$binary_op_re = join "\n\t|\n",
106 "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
107 $math_re,
108 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
109;
b7b0f832 110$binary_op_re = qr/$binary_op_re/x;
0769ac0e 111
112sub _binary_op_re { $binary_op_re }
113
b3b79607 114my $all_known_re = join("\n\t|\n",
115 $expr_start_re,
0769ac0e 116 $binary_op_re,
117 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
b3b79607 118 (map { quotemeta $_ } qw/, ( ) */),
4e914a7c 119 $placeholder_re,
0769ac0e 120);
01dd4e4f 121
b3b79607 122$all_known_re = qr/$all_known_re/x;
123
124#this one *is* capturing for the split below
125# splits on whitespace if all else fails
126my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
127
128# Parser states for _recurse_parse()
129use constant PARSE_TOP_LEVEL => 0;
130use constant PARSE_IN_EXPR => 1;
131use constant PARSE_IN_PARENS => 2;
132use constant PARSE_IN_FUNC => 3;
133use constant PARSE_RHS => 4;
134
135my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
136my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
4e914a7c 137my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
01dd4e4f 138
7e5600e9 139my %indents = (
7853a177 140 select => 0,
141 update => 0,
142 'insert into' => 0,
143 'delete from' => 0,
3d910890 144 from => 1,
91916220 145 where => 0,
7853a177 146 join => 1,
147 'left join' => 1,
148 on => 2,
91916220 149 'group by' => 0,
150 'order by' => 0,
7853a177 151 set => 1,
152 into => 1,
91916220 153 values => 1,
7e5600e9 154);
155
75c3a063 156my %profiles = (
157 console => {
84c65032 158 fill_in_placeholders => 1,
9d11f0d4 159 placeholder_surround => ['?/', ''],
1536de15 160 indent_string => ' ',
75c3a063 161 indent_amount => 2,
1536de15 162 newline => "\n",
3be357b0 163 colormap => {},
7e5600e9 164 indentmap => { %indents },
aafbf833 165
166 eval { require Term::ANSIColor }
167 ? do {
168 my $c = \&Term::ANSIColor::color;
169 (
170 placeholder_surround => [$c->('black on_cyan'), $c->('reset')],
171 colormap => {
172 select => [$c->('red'), $c->('reset')],
173 'insert into' => [$c->('red'), $c->('reset')],
174 update => [$c->('red'), $c->('reset')],
175 'delete from' => [$c->('red'), $c->('reset')],
176
177 set => [$c->('cyan'), $c->('reset')],
178 from => [$c->('cyan'), $c->('reset')],
179
180 where => [$c->('green'), $c->('reset')],
181 values => [$c->('yellow'), $c->('reset')],
182
183 join => [$c->('magenta'), $c->('reset')],
184 'left join' => [$c->('magenta'), $c->('reset')],
185 on => [$c->('blue'), $c->('reset')],
186
187 'group by' => [$c->('yellow'), $c->('reset')],
188 'order by' => [$c->('yellow'), $c->('reset')],
189 }
190 );
191 } : (),
3be357b0 192 },
193 console_monochrome => {
84c65032 194 fill_in_placeholders => 1,
9d11f0d4 195 placeholder_surround => ['?/', ''],
3be357b0 196 indent_string => ' ',
197 indent_amount => 2,
198 newline => "\n",
199 colormap => {},
7e5600e9 200 indentmap => { %indents },
201 },
202 html => {
84c65032 203 fill_in_placeholders => 1,
9d11f0d4 204 placeholder_surround => ['<span class="placeholder">', '</span>'],
7e5600e9 205 indent_string => '&nbsp;',
206 indent_amount => 2,
207 newline => "<br />\n",
208 colormap => {
7853a177 209 select => ['<span class="select">' , '</span>'],
210 'insert into' => ['<span class="insert-into">' , '</span>'],
211 update => ['<span class="select">' , '</span>'],
212 'delete from' => ['<span class="delete-from">' , '</span>'],
213 where => ['<span class="where">' , '</span>'],
214 from => ['<span class="from">' , '</span>'],
215 join => ['<span class="join">' , '</span>'],
216 on => ['<span class="on">' , '</span>'],
217 'group by' => ['<span class="group-by">', '</span>'],
218 'order by' => ['<span class="order-by">', '</span>'],
219 set => ['<span class="set">', '</span>'],
220 into => ['<span class="into">', '</span>'],
221 values => ['<span class="values">', '</span>'],
1536de15 222 },
7e5600e9 223 indentmap => { %indents },
75c3a063 224 },
225 none => {
1536de15 226 colormap => {},
227 indentmap => {},
75c3a063 228 },
229);
230
231sub new {
2fed0b4b 232 my $class = shift;
233 my $args = shift || {};
75c3a063 234
235 my $profile = delete $args->{profile} || 'none';
bc482085 236 my $data = $merger->merge( $profiles{$profile}, $args );
75c3a063 237
238 bless $data, $class
239}
d695b0ad 240
01dd4e4f 241sub parse {
d695b0ad 242 my ($self, $s) = @_;
01dd4e4f 243
244 # tokenize string, and remove all optional whitespace
245 my $tokens = [];
246 foreach my $token (split $tokenizer_re, $s) {
b3b79607 247 push @$tokens, $token if (
248 defined $token
249 and
250 length $token
251 and
252 $token =~ /\S/
253 );
01dd4e4f 254 }
b3b79607 255 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 256}
257
258sub _recurse_parse {
d695b0ad 259 my ($self, $tokens, $state) = @_;
01dd4e4f 260
261 my $left;
262 while (1) { # left-associative parsing
263
264 my $lookahead = $tokens->[0];
265 if ( not defined($lookahead)
266 or
267 ($state == PARSE_IN_PARENS && $lookahead eq ')')
268 or
b3b79607 269 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
0769ac0e 270 or
b3b79607 271 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
01dd4e4f 272 or
b3b79607 273 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
01dd4e4f 274 ) {
0769ac0e 275 return $left||();
01dd4e4f 276 }
277
278 my $token = shift @$tokens;
279
280 # nested expression in ()
281 if ($token eq '(' ) {
d695b0ad 282 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
283 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
284 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 285
0769ac0e 286 $left = $left ? [$left, [PAREN => [$right||()] ]]
287 : [PAREN => [$right||()] ];
01dd4e4f 288 }
b3b79607 289 # AND/OR and LIST (,)
290 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
291 my $op = ($token eq ',') ? 'LIST' : uc $token;
292
d695b0ad 293 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 294
295 # Merge chunks if logic matches
296 if (ref $right and $op eq $right->[0]) {
b3b79607 297 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
01dd4e4f 298 }
299 else {
b3b79607 300 $left = [$op => [ $left||(), $right||() ]];
01dd4e4f 301 }
302 }
303 # binary operator keywords
a1e204f4 304 elsif ( $token =~ /^ $binary_op_re $ /x ) {
01dd4e4f 305 my $op = uc $token;
d695b0ad 306 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 307
308 # A between with a simple LITERAL for a 1st RHS argument needs a
309 # rerun of the search to (hopefully) find the proper AND construct
310 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
311 unshift @$tokens, $right->[1][0];
d695b0ad 312 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 313 }
314
315 $left = [$op => [$left, $right] ];
316 }
317 # expression terminator keywords (as they start a new expression)
b3b79607 318 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
01dd4e4f 319 my $op = uc $token;
d695b0ad 320 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
efc991a0 321 $left = $left ? [ $left, [$op => [$right||()] ]]
322 : [ $op => [$right||()] ];
01dd4e4f 323 }
0769ac0e 324 # NOT
325 elsif ( $token =~ /^ NOT $/ix ) {
01dd4e4f 326 my $op = uc $token;
d695b0ad 327 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 328 $left = $left ? [ @$left, [$op => [$right] ]]
329 : [ $op => [$right] ];
330
331 }
4e914a7c 332 elsif ( $token =~ $placeholder_re) {
333 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
334 : [ PLACEHOLDER => [ $token ] ];
335 }
b3b79607 336 # we're now in "unknown token" land - start eating tokens until
337 # we see something familiar
01dd4e4f 338 else {
b3b79607 339 my $right;
340
341 # check if the current token is an unknown op-start
342 if (@$tokens and $tokens->[0] =~ $func_start_re) {
343 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
344 }
345 else {
346 $right = [ LITERAL => [ $token ] ];
347 }
348
349 $left = $left ? [ $left, $right ]
350 : $right;
01dd4e4f 351 }
352 }
353}
354
d695b0ad 355sub format_keyword {
356 my ($self, $keyword) = @_;
357
1536de15 358 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 359 $keyword = "$around->[0]$keyword$around->[1]";
360 }
361
362 return $keyword
363}
364
728f26a2 365my %starters = (
366 select => 1,
367 update => 1,
368 'insert into' => 1,
369 'delete from' => 1,
370);
371
f2ab166a 372sub pad_keyword {
a24cc3a0 373 my ($self, $keyword, $depth) = @_;
e171c446 374
375 my $before = '';
1536de15 376 if (defined $self->indentmap->{lc $keyword}) {
377 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 378 }
728f26a2 379 $before = '' if $depth == 0 and defined $starters{lc $keyword};
e4570c8e 380 return [$before, ''];
a24cc3a0 381}
382
1536de15 383sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 384
a97eb57c 385sub _is_key {
386 my ($self, $tree) = @_;
0569a14f 387 $tree = $tree->[0] while ref $tree;
388
a97eb57c 389 defined $tree && defined $self->indentmap->{lc $tree};
0569a14f 390}
391
9d11f0d4 392sub fill_in_placeholder {
fb272e73 393 my ($self, $bindargs) = @_;
394
395 if ($self->fill_in_placeholders) {
ad46269d 396 my $val = shift @{$bindargs} || '';
9d11f0d4 397 my ($left, $right) = @{$self->placeholder_surround};
fb272e73 398 $val =~ s/\\/\\\\/g;
399 $val =~ s/'/\\'/g;
ad46269d 400 return qq($left$val$right)
fb272e73 401 }
402 return '?'
403}
404
3a247d23 405# FIXME - terrible name for a user facing API
01dd4e4f 406sub unparse {
3a247d23 407 my ($self, $tree, $bindargs) = @_;
408 $self->_unparse($tree, [@{$bindargs||[]}], 0);
409}
a24cc3a0 410
3a247d23 411sub _unparse {
412 my ($self, $tree, $bindargs, $depth) = @_;
01dd4e4f 413
0769ac0e 414 if (not $tree or not @$tree) {
01dd4e4f 415 return '';
416 }
a24cc3a0 417
0769ac0e 418 my ($car, $cdr) = @{$tree}[0,1];
419
420 if (! defined $car or (! ref $car and ! defined $cdr) ) {
421 require Data::Dumper;
422 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
423 Data::Dumper::Dumper($tree)
424 ) );
425 }
a24cc3a0 426
427 if (ref $car) {
3a247d23 428 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
01dd4e4f 429 }
a24cc3a0 430 elsif ($car eq 'LITERAL') {
431 return $cdr->[0];
01dd4e4f 432 }
4e914a7c 433 elsif ($car eq 'PLACEHOLDER') {
434 return $self->fill_in_placeholder($bindargs);
435 }
a24cc3a0 436 elsif ($car eq 'PAREN') {
e4570c8e 437 return sprintf ('(%s)',
438 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
439 .
440 ($self->_is_key($cdr)
441 ? ( $self->newline||'' ) . $self->indent($depth + 1)
442 : ''
443 )
444 );
01dd4e4f 445 }
0769ac0e 446 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
3a247d23 447 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
01dd4e4f 448 }
b3b79607 449 elsif ($car eq 'LIST' ) {
3a247d23 450 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
b3b79607 451 }
01dd4e4f 452 else {
f2ab166a 453 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
3a247d23 454 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->_unparse($cdr, $bindargs, $depth);
01dd4e4f 455 }
456}
457
fb272e73 458sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
01dd4e4f 459
4601;
461
3be357b0 462=pod
463
464=head1 SYNOPSIS
465
466 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
467
468 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
469
470 # SELECT *
471 # FROM foo
472 # WHERE foo.a > 2
473
6b1bf9f8 474=head1 METHODS
475
476=head2 new
477
478 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
479
c22f502d 480 $args = {
481 profile => 'console', # predefined profile to use (default: 'none')
482 fill_in_placeholders => 1, # true for placeholder population
9d11f0d4 483 placeholder_surround => # The strings that will be wrapped around
484 [GREEN, RESET], # populated placeholders if the above is set
c22f502d 485 indent_string => ' ', # the string used when indenting
486 indent_amount => 2, # how many of above string to use for a single
487 # indent level
488 newline => "\n", # string for newline
489 colormap => {
490 select => [RED, RESET], # a pair of strings defining what to surround
491 # the keyword with for colorization
492 # ...
493 },
494 indentmap => {
495 select => 0, # A zero means that the keyword will start on
496 # a new line
497 from => 1, # Any other positive integer means that after
498 on => 2, # said newline it will get that many indents
499 # ...
500 },
501 }
502
503Returns a new SQL::Abstract::Tree object. All arguments are optional.
504
505=head3 profiles
506
507There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
508and C<html>. Typically a user will probably just use C<console> or
509C<console_monochrome>, but if something about a profile bothers you, merely
510use the profile and override the parts that you don't like.
511
6b1bf9f8 512=head2 format
513
c22f502d 514 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
515
516Takes C<$sql> and C<\@bindargs>.
6b1bf9f8 517
1a3cc911 518Returns a formatting string based on the string passed in
ee4227a7 519
520=head2 parse
521
522 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
523
524Returns a "tree" representing passed in SQL. Please do not depend on the
525structure of the returned tree. It may be stable at some point, but not yet.
526
527=head2 unparse
528
529 $sqlat->parse($tree_structure, \@bindargs)
530
531Transform "tree" into SQL, applying various transforms on the way.
532
533=head2 format_keyword
534
535 $sqlat->format_keyword('SELECT')
536
537Currently this just takes a keyword and puts the C<colormap> stuff around it.
538Later on it may do more and allow for coderef based transforms.
539
f2ab166a 540=head2 pad_keyword
ee4227a7 541
f2ab166a 542 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
ee4227a7 543
544Returns whitespace to be inserted around a keyword.
9d11f0d4 545
546=head2 fill_in_placeholder
547
548 my $value = $sqlat->fill_in_placeholder(\@bindargs)
549
550Removes last arg from passed arrayref and returns it, surrounded with
551the values in placeholder_surround, and then surrounded with single quotes.
f2ab166a 552
553=head2 indent
554
555Returns as many indent strings as indent amounts times the first argument.
556
557=head1 ACCESSORS
558
559=head2 colormap
560
561See L</new>
562
563=head2 fill_in_placeholders
564
565See L</new>
566
567=head2 indent_amount
568
569See L</new>
570
571=head2 indent_string
572
573See L</new>
574
575=head2 indentmap
576
577See L</new>
578
579=head2 newline
580
581See L</new>
582
583=head2 placeholder_surround
584
585See L</new>
586