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