add more keywords, colors, and indentation rules
[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
8 use base 'Class::Accessor::Grouped';
9
10 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
11    newline indent_string indent_amount colormap indentmap
12 );
13
14 # Parser states for _recurse_parse()
15 use constant PARSE_TOP_LEVEL => 0;
16 use constant PARSE_IN_EXPR => 1;
17 use constant PARSE_IN_PARENS => 2;
18 use constant PARSE_RHS => 3;
19
20 # These SQL keywords always signal end of the current expression (except inside
21 # of a parenthesized subexpression).
22 # Format: A list of strings that will be compiled to extended syntax (ie.
23 # /.../x) regexes, without capturing parentheses. They will be automatically
24 # anchored to word boundaries to match the whole token).
25 my @expression_terminator_sql_keywords = (
26   'SELECT',
27   'UPDATE',
28   'INSERT \s+ INTO',
29   'DELETE \s+ FROM',
30   'SET',
31   '(?:
32     (?:
33         (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
34         (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
35     )?
36     JOIN
37   )',
38   'ON',
39   'WHERE',
40   'VALUES',
41   'EXISTS',
42   'GROUP \s+ BY',
43   'HAVING',
44   'ORDER \s+ BY',
45   'LIMIT',
46   'OFFSET',
47   'FOR',
48   'UNION',
49   'INTERSECT',
50   'EXCEPT',
51   'RETURNING',
52   'ROW_NUMBER \s* \( \s* \) \s+ OVER',
53 );
54
55 # These are binary operator keywords always a single LHS and RHS
56 # * AND/OR are handled separately as they are N-ary
57 # * so is NOT as being unary
58 # * BETWEEN without paranthesis around the ANDed arguments (which
59 #   makes it a non-binary op) is detected and accomodated in
60 #   _recurse_parse()
61 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
62 my @binary_op_keywords = (
63   ( map
64     {
65       ' ^ '  . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
66       " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
67     }
68     (qw/< > != <> = <= >=/)
69   ),
70   ( map
71     { '\b (?: NOT \s+)?' . $_ . '\b' }
72     (qw/IN BETWEEN LIKE/)
73   ),
74 );
75
76 my $tokenizer_re_str = join("\n\t|\n",
77   ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
78   @binary_op_keywords,
79 );
80
81 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
82
83 sub _binary_op_keywords { @binary_op_keywords }
84
85 my %indents = (
86    select        => 0,
87    update        => 0,
88    'insert into' => 0,
89    'delete from' => 0,
90    where         => 1,
91    join          => 1,
92    'left join'   => 1,
93    on            => 2,
94    'group by'    => 1,
95    'order by'    => 1,
96    set           => 1,
97    into          => 1,
98    values        => 2,
99 );
100
101 my %profiles = (
102    console => {
103       indent_string => ' ',
104       indent_amount => 2,
105       newline       => "\n",
106       colormap      => {},
107       indentmap     => { %indents },
108    },
109    console_monochrome => {
110       indent_string => ' ',
111       indent_amount => 2,
112       newline       => "\n",
113       colormap      => {},
114       indentmap     => { %indents },
115    },
116    html => {
117       indent_string => '&nbsp;',
118       indent_amount => 2,
119       newline       => "<br />\n",
120       colormap      => {
121          select        => ['<span class="select">'  , '</span>'],
122          'insert into' => ['<span class="insert-into">'  , '</span>'],
123          update        => ['<span class="select">'  , '</span>'],
124          'delete from' => ['<span class="delete-from">'  , '</span>'],
125          where         => ['<span class="where">'   , '</span>'],
126          from          => ['<span class="from">'    , '</span>'],
127          join          => ['<span class="join">'    , '</span>'],
128          on            => ['<span class="on">'      , '</span>'],
129          'group by'    => ['<span class="group-by">', '</span>'],
130          'order by'    => ['<span class="order-by">', '</span>'],
131          set           => ['<span class="set">', '</span>'],
132          into          => ['<span class="into">', '</span>'],
133          values        => ['<span class="values">', '</span>'],
134       },
135       indentmap     => { %indents },
136    },
137    none => {
138       colormap      => {},
139       indentmap     => {},
140    },
141 );
142
143 eval {
144    require Term::ANSIColor;
145    $profiles{console}->{colormap} = {
146       select        => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
147       'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
148       update        => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
149       'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
150
151       set           => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
152
153       where         => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
154       values        => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
155
156       join          => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
157       'left join'   => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
158       on            => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
159
160       'group by'    => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
161       'order by'    => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
162    };
163 };
164
165 sub new {
166    my ($class, $args) = @_;
167
168    my $profile = delete $args->{profile} || 'none';
169    my $data = {%{$profiles{$profile}}, %{$args||{}}};
170
171    bless $data, $class
172 }
173
174 sub parse {
175   my ($self, $s) = @_;
176
177   # tokenize string, and remove all optional whitespace
178   my $tokens = [];
179   foreach my $token (split $tokenizer_re, $s) {
180     push @$tokens, $token if (length $token) && ($token =~ /\S/);
181   }
182
183   my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
184   return $tree;
185 }
186
187 sub _recurse_parse {
188   my ($self, $tokens, $state) = @_;
189
190   my $left;
191   while (1) { # left-associative parsing
192
193     my $lookahead = $tokens->[0];
194     if ( not defined($lookahead)
195           or
196         ($state == PARSE_IN_PARENS && $lookahead eq ')')
197           or
198         ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
199           or
200         ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
201     ) {
202       return $left;
203     }
204
205     my $token = shift @$tokens;
206
207     # nested expression in ()
208     if ($token eq '(' ) {
209       my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
210       $token = shift @$tokens   or croak "missing closing ')' around block " . $self->unparse($right);
211       $token eq ')'             or croak "unexpected token '$token' terminating block " . $self->unparse($right);
212
213       $left = $left ? [@$left, [PAREN => [$right] ]]
214                     : [PAREN  => [$right] ];
215     }
216     # AND/OR
217     elsif ($token =~ /^ (?: OR | AND ) $/xi )  {
218       my $op = uc $token;
219       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
220
221       # Merge chunks if logic matches
222       if (ref $right and $op eq $right->[0]) {
223         $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
224       }
225       else {
226        $left = [$op => [$left, $right]];
227       }
228     }
229     # binary operator keywords
230     elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
231       my $op = uc $token;
232       my $right = $self->_recurse_parse($tokens, PARSE_RHS);
233
234       # A between with a simple LITERAL for a 1st RHS argument needs a
235       # rerun of the search to (hopefully) find the proper AND construct
236       if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
237         unshift @$tokens, $right->[1][0];
238         $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
239       }
240
241       $left = [$op => [$left, $right] ];
242     }
243     # expression terminator keywords (as they start a new expression)
244     elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
245       my $op = uc $token;
246       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
247       $left = $left ? [ $left,  [$op => [$right] ]]
248                     : [ $op => [$right] ];
249     }
250     # NOT (last as to allow all other NOT X pieces first)
251     elsif ( $token =~ /^ not $/ix ) {
252       my $op = uc $token;
253       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
254       $left = $left ? [ @$left, [$op => [$right] ]]
255                     : [ $op => [$right] ];
256
257     }
258     # literal (eat everything on the right until RHS termination)
259     else {
260       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
261       $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
262                     : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
263     }
264   }
265 }
266
267 sub format_keyword {
268   my ($self, $keyword) = @_;
269
270   if (my $around = $self->colormap->{lc $keyword}) {
271      $keyword = "$around->[0]$keyword$around->[1]";
272   }
273
274   return $keyword
275 }
276
277 sub whitespace {
278    my ($self, $keyword, $depth) = @_;
279
280    my $before = '';
281    if (defined $self->indentmap->{lc $keyword}) {
282       $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
283    }
284    $before = '' if $depth == 0 and lc $keyword eq 'select';
285    return [$before, ' '];
286 }
287
288 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
289
290 sub _is_select {
291    my $tree = shift;
292    $tree = $tree->[0] while ref $tree;
293
294    defined $tree && lc $tree eq 'select';
295 }
296
297 sub unparse {
298   my ($self, $tree, $depth) = @_;
299
300   $depth ||= 0;
301
302   if (not $tree ) {
303     return '';
304   }
305
306   my $car = $tree->[0];
307   my $cdr = $tree->[1];
308
309   if (ref $car) {
310     return join ('', map $self->unparse($_, $depth), @$tree);
311   }
312   elsif ($car eq 'LITERAL') {
313     return $cdr->[0];
314   }
315   elsif ($car eq 'PAREN') {
316     return '(' .
317       join(' ',
318         map $self->unparse($_, $depth + 2), @{$cdr}) .
319     (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
320   }
321   elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
322     return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
323   }
324   else {
325     my ($l, $r) = @{$self->whitespace($car, $depth)};
326     return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
327   }
328 }
329
330 sub format { my $self = shift; $self->unparse($self->parse(@_)) }
331
332 1;
333
334 =pod
335
336 =head1 SYNOPSIS
337
338  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
339
340  print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
341
342  # SELECT *
343  #   FROM foo
344  #   WHERE foo.a > 2
345