whitespace tests
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract / Tree.pm
CommitLineData
01dd4e4f 1package SQL::Abstract::Tree;
2
3use strict;
4use warnings;
5use Carp;
6
1536de15 7
1536de15 8use base 'Class::Accessor::Grouped';
9
10__PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
11 newline indent_string indent_amount colormap indentmap
12);
13
01dd4e4f 14# Parser states for _recurse_parse()
15use constant PARSE_TOP_LEVEL => 0;
16use constant PARSE_IN_EXPR => 1;
17use constant PARSE_IN_PARENS => 2;
18use 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).
25my @expression_terminator_sql_keywords = (
26 'SELECT',
27 'FROM',
28 '(?:
29 (?:
30 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
31 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
32 )?
33 JOIN
34 )',
35 'ON',
36 'WHERE',
37 'EXISTS',
38 'GROUP \s+ BY',
39 'HAVING',
40 'ORDER \s+ BY',
41 'LIMIT',
42 'OFFSET',
43 'FOR',
44 'UNION',
45 'INTERSECT',
46 'EXCEPT',
47 'RETURNING',
8d0dd7dc 48 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
01dd4e4f 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()
57my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
58my @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
72my $tokenizer_re_str = join("\n\t|\n",
73 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
74 @binary_op_keywords,
75);
76
77my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
78
79sub _binary_op_keywords { @binary_op_keywords }
80
7e5600e9 81my %indents = (
1bb3956e 82 select => 0,
83 where => 1,
84 from => 1,
85 join => 1,
86 on => 2,
87 'group by' => 1,
8d0dd7dc 88 'order by' => 1,
7e5600e9 89);
90
75c3a063 91my %profiles = (
92 console => {
1536de15 93 indent_string => ' ',
75c3a063 94 indent_amount => 2,
1536de15 95 newline => "\n",
3be357b0 96 colormap => {},
7e5600e9 97 indentmap => { %indents },
3be357b0 98 },
99 console_monochrome => {
100 indent_string => ' ',
101 indent_amount => 2,
102 newline => "\n",
103 colormap => {},
7e5600e9 104 indentmap => { %indents },
105 },
106 html => {
107 indent_string => '&nbsp;',
108 indent_amount => 2,
109 newline => "<br />\n",
110 colormap => {
1bb3956e 111 select => ['<span class="select">' , '</span>'],
112 where => ['<span class="where">' , '</span>'],
113 from => ['<span class="from">' , '</span>'],
114 join => ['<span class="join">' , '</span>'],
115 on => ['<span class="on">' , '</span>'],
116 'group by' => ['<span class="group-by">', '</span>'],
1536de15 117 },
7e5600e9 118 indentmap => { %indents },
75c3a063 119 },
120 none => {
1536de15 121 colormap => {},
122 indentmap => {},
75c3a063 123 },
124);
125
3be357b0 126eval {
127 require Term::ANSIColor;
128 $profiles{console}->{colormap} = {
8d0dd7dc 129 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
130 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
131 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
132 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
133 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
134 'group by' => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
135 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
3be357b0 136 };
137};
138
75c3a063 139sub new {
140 my ($class, $args) = @_;
141
142 my $profile = delete $args->{profile} || 'none';
143 my $data = {%{$profiles{$profile}}, %{$args||{}}};
144
145 bless $data, $class
146}
d695b0ad 147
01dd4e4f 148sub parse {
d695b0ad 149 my ($self, $s) = @_;
01dd4e4f 150
151 # tokenize string, and remove all optional whitespace
152 my $tokens = [];
153 foreach my $token (split $tokenizer_re, $s) {
154 push @$tokens, $token if (length $token) && ($token =~ /\S/);
155 }
156
d695b0ad 157 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 158 return $tree;
159}
160
161sub _recurse_parse {
d695b0ad 162 my ($self, $tokens, $state) = @_;
01dd4e4f 163
164 my $left;
165 while (1) { # left-associative parsing
166
167 my $lookahead = $tokens->[0];
168 if ( not defined($lookahead)
169 or
170 ($state == PARSE_IN_PARENS && $lookahead eq ')')
171 or
172 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
173 or
174 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
175 ) {
176 return $left;
177 }
178
179 my $token = shift @$tokens;
180
181 # nested expression in ()
182 if ($token eq '(' ) {
d695b0ad 183 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
184 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
185 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 186
187 $left = $left ? [@$left, [PAREN => [$right] ]]
188 : [PAREN => [$right] ];
189 }
190 # AND/OR
191 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
192 my $op = uc $token;
d695b0ad 193 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 194
195 # Merge chunks if logic matches
196 if (ref $right and $op eq $right->[0]) {
197 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
198 }
199 else {
200 $left = [$op => [$left, $right]];
201 }
202 }
203 # binary operator keywords
204 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
205 my $op = uc $token;
d695b0ad 206 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 207
208 # A between with a simple LITERAL for a 1st RHS argument needs a
209 # rerun of the search to (hopefully) find the proper AND construct
210 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
211 unshift @$tokens, $right->[1][0];
d695b0ad 212 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 213 }
214
215 $left = [$op => [$left, $right] ];
216 }
217 # expression terminator keywords (as they start a new expression)
218 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
219 my $op = uc $token;
d695b0ad 220 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 221 $left = $left ? [ $left, [$op => [$right] ]]
222 : [ $op => [$right] ];
223 }
224 # NOT (last as to allow all other NOT X pieces first)
225 elsif ( $token =~ /^ not $/ix ) {
226 my $op = uc $token;
d695b0ad 227 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 228 $left = $left ? [ @$left, [$op => [$right] ]]
229 : [ $op => [$right] ];
230
231 }
232 # literal (eat everything on the right until RHS termination)
233 else {
d695b0ad 234 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
235 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
236 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
01dd4e4f 237 }
238 }
239}
240
d695b0ad 241sub format_keyword {
242 my ($self, $keyword) = @_;
243
1536de15 244 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 245 $keyword = "$around->[0]$keyword$around->[1]";
246 }
247
248 return $keyword
249}
250
a24cc3a0 251sub whitespace {
252 my ($self, $keyword, $depth) = @_;
e171c446 253
254 my $before = '';
1536de15 255 if (defined $self->indentmap->{lc $keyword}) {
256 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 257 }
1a67e3a0 258 $before = '' if $depth == 0 and lc $keyword eq 'select';
b4e0e260 259 return [$before, ' '];
a24cc3a0 260}
261
1536de15 262sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 263
0569a14f 264sub _is_select {
265 my $tree = shift;
266 $tree = $tree->[0] while ref $tree;
267
ca8aec12 268 defined $tree && lc $tree eq 'select';
0569a14f 269}
270
01dd4e4f 271sub unparse {
a24cc3a0 272 my ($self, $tree, $depth) = @_;
273
e171c446 274 $depth ||= 0;
01dd4e4f 275
276 if (not $tree ) {
277 return '';
278 }
a24cc3a0 279
280 my $car = $tree->[0];
281 my $cdr = $tree->[1];
282
283 if (ref $car) {
e171c446 284 return join ('', map $self->unparse($_, $depth), @$tree);
01dd4e4f 285 }
a24cc3a0 286 elsif ($car eq 'LITERAL') {
287 return $cdr->[0];
01dd4e4f 288 }
a24cc3a0 289 elsif ($car eq 'PAREN') {
e171c446 290 return '(' .
a24cc3a0 291 join(' ',
0569a14f 292 map $self->unparse($_, $depth + 2), @{$cdr}) .
f088a68d 293 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
01dd4e4f 294 }
a24cc3a0 295 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
e171c446 296 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
01dd4e4f 297 }
298 else {
a24cc3a0 299 my ($l, $r) = @{$self->whitespace($car, $depth)};
e171c446 300 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
01dd4e4f 301 }
302}
303
d695b0ad 304sub format { my $self = shift; $self->unparse($self->parse(@_)) }
01dd4e4f 305
3061;
307
3be357b0 308=pod
309
310=head1 SYNOPSIS
311
312 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
313
314 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
315
316 # SELECT *
317 # FROM foo
318 # WHERE foo.a > 2
319