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