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