Add list support, and various mini-fixes
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
1 package SQL::Abstract::Tree;
2
3 use strict;
4 use warnings;
5 no warnings 'qw';
6 use Carp;
7
8 use Hash::Merge qw//;
9
10 use 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 );
16
17 my $merger = Hash::Merge->new;
18
19 $merger->specify_behavior({
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    },
35 }, 'SQLA::Tree Behavior' );
36
37 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
38 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
39
40 my $quote_left = qr/[\`\'\"\[]/;
41 my $quote_right = qr/[\`\'\"\]]/;
42
43 # These SQL keywords always signal end of the current expression (except inside
44 # of a parenthesized subexpression).
45 # Format: A list of strings that will be compiled to extended syntax ie.
46 # /.../x) regexes, without capturing parentheses. They will be automatically
47 # anchored to op boundaries (excluding quotes) to match the whole token.
48 my @expression_start_keywords = (
49   'SELECT',
50   'UPDATE',
51   'INSERT \s+ INTO',
52   'DELETE \s+ FROM',
53   'FROM',
54   'SET',
55   '(?:
56     (?:
57         (?: (?: LEFT | RIGHT | FULL ) \s+ )?
58         (?: (?: CROSS | INNER | OUTER ) \s+ )?
59     )?
60     JOIN
61   )',
62   'ON',
63   'WHERE',
64   'VALUES',
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',
76   'ROW_NUMBER \s* \( \s* \) \s+ OVER',
77 );
78
79 my $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;
81
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()
88
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" )
92 my @math_op_keywords = (qw/ < > != <> = <= >= /);
93 my $math_re = join ("\n\t|\n", map
94   { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )"  . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
95   @math_op_keywords
96 );
97 $math_re = qr/$math_re/x;
98
99 sub _math_op_re { $math_re }
100
101
102 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
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 ;
108 $binary_op_re = qr/$binary_op_re/x;
109
110 sub _binary_op_re { $binary_op_re }
111
112 my $all_known_re = join("\n\t|\n",
113   $expr_start_re,
114   $binary_op_re,
115   "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
116   (map { quotemeta $_ } qw/, ( ) */),
117 );
118
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
123 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
124
125 # Parser states for _recurse_parse()
126 use constant PARSE_TOP_LEVEL => 0;
127 use constant PARSE_IN_EXPR => 1;
128 use constant PARSE_IN_PARENS => 2;
129 use constant PARSE_IN_FUNC => 3;
130 use constant PARSE_RHS => 4;
131
132 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
133 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
134 my $func_start_re = qr/^ (?: \? | \$\d+ | \( ) $/x;
135
136 my %indents = (
137    select        => 0,
138    update        => 0,
139    'insert into' => 0,
140    'delete from' => 0,
141    from          => 1,
142    where         => 0,
143    join          => 1,
144    'left join'   => 1,
145    on            => 2,
146    'group by'    => 0,
147    'order by'    => 0,
148    set           => 1,
149    into          => 1,
150    values        => 1,
151 );
152
153 my %profiles = (
154    console => {
155       fill_in_placeholders => 1,
156       placeholder_surround => ['?/', ''],
157       indent_string => ' ',
158       indent_amount => 2,
159       newline       => "\n",
160       colormap      => {},
161       indentmap     => { %indents },
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         } : (),
189    },
190    console_monochrome => {
191       fill_in_placeholders => 1,
192       placeholder_surround => ['?/', ''],
193       indent_string => ' ',
194       indent_amount => 2,
195       newline       => "\n",
196       colormap      => {},
197       indentmap     => { %indents },
198    },
199    html => {
200       fill_in_placeholders => 1,
201       placeholder_surround => ['<span class="placeholder">', '</span>'],
202       indent_string => '&nbsp;',
203       indent_amount => 2,
204       newline       => "<br />\n",
205       colormap      => {
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>'],
219       },
220       indentmap     => { %indents },
221    },
222    none => {
223       colormap      => {},
224       indentmap     => {},
225    },
226 );
227
228 sub new {
229    my $class = shift;
230    my $args  = shift || {};
231
232    my $profile = delete $args->{profile} || 'none';
233    my $data = $merger->merge( $profiles{$profile}, $args );
234
235    bless $data, $class
236 }
237
238 sub parse {
239   my ($self, $s) = @_;
240
241   # tokenize string, and remove all optional whitespace
242   my $tokens = [];
243   foreach my $token (split $tokenizer_re, $s) {
244     push @$tokens, $token if (
245       defined $token
246         and
247       length $token
248         and 
249       $token =~ /\S/
250     );
251   }
252   $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
253 }
254
255 sub _recurse_parse {
256   my ($self, $tokens, $state) = @_;
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
266         ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
267           or
268         ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
269           or
270         ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
271     ) {
272       return $left||();
273     }
274
275     my $token = shift @$tokens;
276
277     # nested expression in ()
278     if ($token eq '(' ) {
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);
282
283       $left = $left ? [$left, [PAREN => [$right||()] ]]
284                     : [PAREN  => [$right||()] ];
285     }
286     # AND/OR and LIST (,)
287     elsif ($token =~ /^ (?: OR | AND | \, ) $/xi )  {
288       my $op = ($token eq ',') ? 'LIST' : uc $token;
289
290       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
291
292       # Merge chunks if logic matches
293       if (ref $right and $op eq $right->[0]) {
294         $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
295       }
296       else {
297         $left = [$op => [ $left||(), $right||() ]];
298       }
299     }
300     # binary operator keywords
301     elsif ( $token =~ /^ $binary_op_re $ /x ) {
302       my $op = uc $token;
303       my $right = $self->_recurse_parse($tokens, PARSE_RHS);
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];
309         $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
310       }
311
312       $left = [$op => [$left, $right] ];
313     }
314     # expression terminator keywords (as they start a new expression)
315     elsif ( $token =~ / ^ $expr_start_re $ /x ) {
316       my $op = uc $token;
317       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
318       $left = $left ? [ $left,  [$op => [$right] ]]
319                    : [ $op => [$right] ];
320     }
321     # NOT
322     elsif ( $token =~ /^ NOT $/ix ) {
323       my $op = uc $token;
324       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
325       $left = $left ? [ @$left, [$op => [$right] ]]
326                     : [ $op => [$right] ];
327
328     }
329     # we're now in "unknown token" land - start eating tokens until
330     # we see something familiar
331     else {
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;
344     }
345   }
346 }
347
348 sub format_keyword {
349   my ($self, $keyword) = @_;
350
351   if (my $around = $self->colormap->{lc $keyword}) {
352      $keyword = "$around->[0]$keyword$around->[1]";
353   }
354
355   return $keyword
356 }
357
358 my %starters = (
359    select        => 1,
360    update        => 1,
361    'insert into' => 1,
362    'delete from' => 1,
363 );
364
365 sub pad_keyword {
366    my ($self, $keyword, $depth) = @_;
367
368    my $before = '';
369    if (defined $self->indentmap->{lc $keyword}) {
370       $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
371    }
372    $before = '' if $depth == 0 and defined $starters{lc $keyword};
373    return [$before, ' '];
374 }
375
376 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
377
378 sub _is_key {
379    my ($self, $tree) = @_;
380    $tree = $tree->[0] while ref $tree;
381
382    defined $tree && defined $self->indentmap->{lc $tree};
383 }
384
385 sub fill_in_placeholder {
386    my ($self, $bindargs) = @_;
387
388    if ($self->fill_in_placeholders) {
389       my $val = shift @{$bindargs} || '';
390       my ($left, $right) = @{$self->placeholder_surround};
391       $val =~ s/\\/\\\\/g;
392       $val =~ s/'/\\'/g;
393       return qq($left$val$right)
394    }
395    return '?'
396 }
397
398 sub unparse {
399   my ($self, $tree, $bindargs, $depth) = @_;
400
401   $depth ||= 0;
402
403   if (not $tree or not @$tree) {
404     return '';
405   }
406
407   my ($car, $cdr) = @{$tree}[0,1];
408
409   if (! defined $car or (! ref $car and ! defined $cdr) ) {
410     require Data::Dumper;
411     Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
412       Data::Dumper::Dumper($tree)
413     ) );
414   }
415
416   if (ref $car) {
417     return join (' ', map $self->unparse($_, $bindargs, $depth), @$tree);
418   }
419   elsif ($car eq 'LITERAL') {
420     if ($cdr->[0] eq '?') {
421       return $self->fill_in_placeholder($bindargs)
422     }
423     return $cdr->[0];
424   }
425   elsif ($car eq 'PAREN') {
426     return '(' .
427       join(' ',
428         map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
429     ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
430   }
431   elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
432     return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
433   }
434   elsif ($car eq 'LIST' ) {
435     return join (', ', map $self->unparse($_, $bindargs, $depth), @{$cdr});
436   }
437   else {
438     my ($l, $r) = @{$self->pad_keyword($car, $depth)};
439     return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
440   }
441 }
442
443 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
444
445 1;
446
447 =pod
448
449 =head1 SYNOPSIS
450
451  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
452
453  print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
454
455  # SELECT *
456  #   FROM foo
457  #   WHERE foo.a > 2
458
459 =head1 METHODS
460
461 =head2 new
462
463  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
464
465  $args = {
466    profile => 'console',      # predefined profile to use (default: 'none')
467    fill_in_placeholders => 1, # true for placeholder population
468    placeholder_surround =>    # The strings that will be wrapped around
469               [GREEN, RESET], # populated placeholders if the above is set
470    indent_string => ' ',      # the string used when indenting
471    indent_amount => 2,        # how many of above string to use for a single
472                               # indent level
473    newline       => "\n",     # string for newline
474    colormap      => {
475      select => [RED, RESET], # a pair of strings defining what to surround
476                              # the keyword with for colorization
477      # ...
478    },
479    indentmap     => {
480      select        => 0,     # A zero means that the keyword will start on
481                              # a new line
482      from          => 1,     # Any other positive integer means that after
483      on            => 2,     # said newline it will get that many indents
484      # ...
485    },
486  }
487
488 Returns a new SQL::Abstract::Tree object.  All arguments are optional.
489
490 =head3 profiles
491
492 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
493 and C<html>.  Typically a user will probably just use C<console> or
494 C<console_monochrome>, but if something about a profile bothers you, merely
495 use the profile and override the parts that you don't like.
496
497 =head2 format
498
499  $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
500
501 Takes C<$sql> and C<\@bindargs>.
502
503 Returns a formatting string based on the string passed in
504
505 =head2 parse
506
507  $sqlat->parse('SELECT * FROM bar WHERE x = ?')
508
509 Returns a "tree" representing passed in SQL.  Please do not depend on the
510 structure of the returned tree.  It may be stable at some point, but not yet.
511
512 =head2 unparse
513
514  $sqlat->parse($tree_structure, \@bindargs)
515
516 Transform "tree" into SQL, applying various transforms on the way.
517
518 =head2 format_keyword
519
520  $sqlat->format_keyword('SELECT')
521
522 Currently this just takes a keyword and puts the C<colormap> stuff around it.
523 Later on it may do more and allow for coderef based transforms.
524
525 =head2 pad_keyword
526
527  my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
528
529 Returns whitespace to be inserted around a keyword.
530
531 =head2 fill_in_placeholder
532
533  my $value = $sqlat->fill_in_placeholder(\@bindargs)
534
535 Removes last arg from passed arrayref and returns it, surrounded with
536 the values in placeholder_surround, and then surrounded with single quotes.
537
538 =head2 indent
539
540 Returns as many indent strings as indent amounts times the first argument.
541
542 =head1 ACCESSORS
543
544 =head2 colormap
545
546 See L</new>
547
548 =head2 fill_in_placeholders
549
550 See L</new>
551
552 =head2 indent_amount
553
554 See L</new>
555
556 =head2 indent_string
557
558 See L</new>
559
560 =head2 indentmap
561
562 See L</new>
563
564 =head2 newline
565
566 See L</new>
567
568 =head2 placeholder_surround
569
570 See L</new>
571