use object interface to Hash::Merge
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
1 package SQL::Abstract::Tree;
2
3 use strict;
4 use warnings;
5 use Carp;
6
7 use List::Util;
8 use Hash::Merge;
9
10 my $merger = Hash::Merge->new;
11
12 $merger->specify_behavior({
13    SCALAR => {
14       SCALAR => sub { $_[1] },
15       ARRAY  => sub { [ $_[0], @{$_[1]} ] },
16       HASH   => sub { $_[1] },
17    },
18    ARRAY => {
19       SCALAR => sub { $_[1] },
20       ARRAY  => sub { $_[1] },
21       HASH   => sub { $_[1] },
22    },
23    HASH => {
24       SCALAR => sub { $_[1] },
25       ARRAY  => sub { [ values %{$_[0]}, @{$_[1]} ] },
26       HASH   => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
27    },
28 }, 'My Behavior' );
29
30 use base 'Class::Accessor::Grouped';
31
32 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
33    newline indent_string indent_amount colormap indentmap fill_in_placeholders
34 );
35
36 # Parser states for _recurse_parse()
37 use constant PARSE_TOP_LEVEL => 0;
38 use constant PARSE_IN_EXPR => 1;
39 use constant PARSE_IN_PARENS => 2;
40 use constant PARSE_RHS => 3;
41
42 # These SQL keywords always signal end of the current expression (except inside
43 # of a parenthesized subexpression).
44 # Format: A list of strings that will be compiled to extended syntax (ie.
45 # /.../x) regexes, without capturing parentheses. They will be automatically
46 # anchored to word boundaries to match the whole token).
47 my @expression_terminator_sql_keywords = (
48   'SELECT',
49   'UPDATE',
50   'INSERT \s+ INTO',
51   'DELETE \s+ FROM',
52   'FROM',
53   'SET',
54   '(?:
55     (?:
56         (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
57         (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
58     )?
59     JOIN
60   )',
61   'ON',
62   'WHERE',
63   'VALUES',
64   'EXISTS',
65   'GROUP \s+ BY',
66   'HAVING',
67   'ORDER \s+ BY',
68   'LIMIT',
69   'OFFSET',
70   'FOR',
71   'UNION',
72   'INTERSECT',
73   'EXCEPT',
74   'RETURNING',
75   'ROW_NUMBER \s* \( \s* \) \s+ OVER',
76 );
77
78 # These are binary operator keywords always a single LHS and RHS
79 # * AND/OR are handled separately as they are N-ary
80 # * so is NOT as being unary
81 # * BETWEEN without paranthesis around the ANDed arguments (which
82 #   makes it a non-binary op) is detected and accomodated in
83 #   _recurse_parse()
84 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
85 my @binary_op_keywords = (
86   ( map
87     {
88       ' ^ '  . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
89       " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
90     }
91     (qw/< > != <> = <= >=/)
92   ),
93   ( map
94     { '\b (?: NOT \s+)?' . $_ . '\b' }
95     (qw/IN BETWEEN LIKE/)
96   ),
97 );
98
99 my $tokenizer_re_str = join("\n\t|\n",
100   ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
101   @binary_op_keywords,
102 );
103
104 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
105
106 sub _binary_op_keywords { @binary_op_keywords }
107
108 my %indents = (
109    select        => 0,
110    update        => 0,
111    'insert into' => 0,
112    'delete from' => 0,
113    from          => 1,
114    where         => 0,
115    join          => 1,
116    'left join'   => 1,
117    on            => 2,
118    'group by'    => 0,
119    'order by'    => 0,
120    set           => 1,
121    into          => 1,
122    values        => 1,
123 );
124
125 my %profiles = (
126    console => {
127       fill_in_placeholders => 1,
128       indent_string => ' ',
129       indent_amount => 2,
130       newline       => "\n",
131       colormap      => {},
132       indentmap     => { %indents },
133    },
134    console_monochrome => {
135       fill_in_placeholders => 1,
136       indent_string => ' ',
137       indent_amount => 2,
138       newline       => "\n",
139       colormap      => {},
140       indentmap     => { %indents },
141    },
142    html => {
143       fill_in_placeholders => 1,
144       indent_string => '&nbsp;',
145       indent_amount => 2,
146       newline       => "<br />\n",
147       colormap      => {
148          select        => ['<span class="select">'  , '</span>'],
149          'insert into' => ['<span class="insert-into">'  , '</span>'],
150          update        => ['<span class="select">'  , '</span>'],
151          'delete from' => ['<span class="delete-from">'  , '</span>'],
152          where         => ['<span class="where">'   , '</span>'],
153          from          => ['<span class="from">'    , '</span>'],
154          join          => ['<span class="join">'    , '</span>'],
155          on            => ['<span class="on">'      , '</span>'],
156          'group by'    => ['<span class="group-by">', '</span>'],
157          'order by'    => ['<span class="order-by">', '</span>'],
158          set           => ['<span class="set">', '</span>'],
159          into          => ['<span class="into">', '</span>'],
160          values        => ['<span class="values">', '</span>'],
161       },
162       indentmap     => { %indents },
163    },
164    none => {
165       colormap      => {},
166       indentmap     => {},
167    },
168 );
169
170 eval {
171    require Term::ANSIColor;
172    $profiles{console}->{colormap} = {
173       select        => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
174       'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
175       update        => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
176       'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
177
178       set           => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
179       from          => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
180
181       where         => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
182       values        => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
183
184       join          => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
185       'left join'   => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
186       on            => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
187
188       'group by'    => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
189       'order by'    => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
190    };
191 };
192
193 sub new {
194    my $class = shift;
195    my $args  = shift || {};
196
197    my $profile = delete $args->{profile} || 'none';
198    my $data = $merger->merge( $profiles{$profile}, $args );
199
200    bless $data, $class
201 }
202
203 sub parse {
204   my ($self, $s) = @_;
205
206   # tokenize string, and remove all optional whitespace
207   my $tokens = [];
208   foreach my $token (split $tokenizer_re, $s) {
209     push @$tokens, $token if (length $token) && ($token =~ /\S/);
210   }
211
212   my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
213   return $tree;
214 }
215
216 sub _recurse_parse {
217   my ($self, $tokens, $state) = @_;
218
219   my $left;
220   while (1) { # left-associative parsing
221
222     my $lookahead = $tokens->[0];
223     if ( not defined($lookahead)
224           or
225         ($state == PARSE_IN_PARENS && $lookahead eq ')')
226           or
227         ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
228           or
229         ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
230     ) {
231       return $left;
232     }
233
234     my $token = shift @$tokens;
235
236     # nested expression in ()
237     if ($token eq '(' ) {
238       my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
239       $token = shift @$tokens   or croak "missing closing ')' around block " . $self->unparse($right);
240       $token eq ')'             or croak "unexpected token '$token' terminating block " . $self->unparse($right);
241
242       $left = $left ? [@$left, [PAREN => [$right] ]]
243                     : [PAREN  => [$right] ];
244     }
245     # AND/OR
246     elsif ($token =~ /^ (?: OR | AND ) $/xi )  {
247       my $op = uc $token;
248       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
249
250       # Merge chunks if logic matches
251       if (ref $right and $op eq $right->[0]) {
252         $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
253       }
254       else {
255        $left = [$op => [$left, $right]];
256       }
257     }
258     # binary operator keywords
259     elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
260       my $op = uc $token;
261       my $right = $self->_recurse_parse($tokens, PARSE_RHS);
262
263       # A between with a simple LITERAL for a 1st RHS argument needs a
264       # rerun of the search to (hopefully) find the proper AND construct
265       if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
266         unshift @$tokens, $right->[1][0];
267         $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
268       }
269
270       $left = [$op => [$left, $right] ];
271     }
272     # expression terminator keywords (as they start a new expression)
273     elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
274       my $op = uc $token;
275       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
276       $left = $left ? [ $left,  [$op => [$right] ]]
277                     : [ $op => [$right] ];
278     }
279     # NOT (last as to allow all other NOT X pieces first)
280     elsif ( $token =~ /^ not $/ix ) {
281       my $op = uc $token;
282       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
283       $left = $left ? [ @$left, [$op => [$right] ]]
284                     : [ $op => [$right] ];
285
286     }
287     # literal (eat everything on the right until RHS termination)
288     else {
289       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
290       $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
291                     : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
292     }
293   }
294 }
295
296 sub format_keyword {
297   my ($self, $keyword) = @_;
298
299   if (my $around = $self->colormap->{lc $keyword}) {
300      $keyword = "$around->[0]$keyword$around->[1]";
301   }
302
303   return $keyword
304 }
305
306 my %starters = (
307    select        => 1,
308    update        => 1,
309    'insert into' => 1,
310    'delete from' => 1,
311 );
312
313 sub whitespace {
314    my ($self, $keyword, $depth) = @_;
315
316    my $before = '';
317    if (defined $self->indentmap->{lc $keyword}) {
318       $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
319    }
320    $before = '' if $depth == 0 and defined $starters{lc $keyword};
321    return [$before, ' '];
322 }
323
324 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
325
326 sub _is_key {
327    my ($self, $tree) = @_;
328    $tree = $tree->[0] while ref $tree;
329
330    defined $tree && defined $self->indentmap->{lc $tree};
331 }
332
333 sub _fill_in_placeholder {
334    my ($self, $bindargs) = @_;
335
336    if ($self->fill_in_placeholders) {
337       my $val = pop @{$bindargs} || '';
338       $val =~ s/\\/\\\\/g;
339       $val =~ s/'/\\'/g;
340       return qq('$val')
341    }
342    return '?'
343 }
344
345 sub unparse {
346   my ($self, $tree, $bindargs, $depth) = @_;
347
348   $depth ||= 0;
349
350   if (not $tree ) {
351     return '';
352   }
353
354   my $car = $tree->[0];
355   my $cdr = $tree->[1];
356
357   if (ref $car) {
358     return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
359   }
360   elsif ($car eq 'LITERAL') {
361     if ($cdr->[0] eq '?') {
362       return $self->_fill_in_placeholder($bindargs)
363     }
364     return $cdr->[0];
365   }
366   elsif ($car eq 'PAREN') {
367     return '(' .
368       join(' ',
369         map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
370     ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
371   }
372   elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
373     return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
374   }
375   else {
376     my ($l, $r) = @{$self->whitespace($car, $depth)};
377     return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
378   }
379 }
380
381 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
382
383 1;
384
385 =pod
386
387 =head1 SYNOPSIS
388
389  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
390
391  print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
392
393  # SELECT *
394  #   FROM foo
395  #   WHERE foo.a > 2
396
397 =head1 METHODS
398
399 =head2 new
400
401  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
402
403  $args = {
404    profile => 'console',      # predefined profile to use (default: 'none')
405    fill_in_placeholders => 1, # true for placeholder population
406    indent_string => ' ',      # the string used when indenting
407    indent_amount => 2,        # how many of above string to use for a single
408                               # indent level
409    newline       => "\n",     # string for newline
410    colormap      => {
411      select => [RED, RESET], # a pair of strings defining what to surround
412                              # the keyword with for colorization
413      # ...
414    },
415    indentmap     => {
416      select        => 0,     # A zero means that the keyword will start on
417                              # a new line
418      from          => 1,     # Any other positive integer means that after
419      on            => 2,     # said newline it will get that many indents
420      # ...
421    },
422  }
423
424 Returns a new SQL::Abstract::Tree object.  All arguments are optional.
425
426 =head3 profiles
427
428 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
429 and C<html>.  Typically a user will probably just use C<console> or
430 C<console_monochrome>, but if something about a profile bothers you, merely
431 use the profile and override the parts that you don't like.
432
433 =head2 format
434
435  $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
436
437 Takes C<$sql> and C<\@bindargs>.
438
439 Returns a formatting string based on the string passed in