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