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