add test for somewhat complex sql and add extra config for missing keywords
[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',
48);
49
50# These are binary operator keywords always a single LHS and RHS
51# * AND/OR are handled separately as they are N-ary
52# * so is NOT as being unary
53# * BETWEEN without paranthesis around the ANDed arguments (which
54# makes it a non-binary op) is detected and accomodated in
55# _recurse_parse()
56my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
57my @binary_op_keywords = (
58 ( map
59 {
60 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
61 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
62 }
63 (qw/< > != <> = <= >=/)
64 ),
65 ( map
66 { '\b (?: NOT \s+)?' . $_ . '\b' }
67 (qw/IN BETWEEN LIKE/)
68 ),
69);
70
71my $tokenizer_re_str = join("\n\t|\n",
72 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
73 @binary_op_keywords,
74);
75
76my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
77
78sub _binary_op_keywords { @binary_op_keywords }
79
7e5600e9 80my %indents = (
1bb3956e 81 select => 0,
82 where => 1,
83 from => 1,
84 join => 1,
85 on => 2,
86 'group by' => 1,
7e5600e9 87);
88
75c3a063 89my %profiles = (
90 console => {
1536de15 91 indent_string => ' ',
75c3a063 92 indent_amount => 2,
1536de15 93 newline => "\n",
3be357b0 94 colormap => {},
7e5600e9 95 indentmap => { %indents },
3be357b0 96 },
97 console_monochrome => {
98 indent_string => ' ',
99 indent_amount => 2,
100 newline => "\n",
101 colormap => {},
7e5600e9 102 indentmap => { %indents },
103 },
104 html => {
105 indent_string => '&nbsp;',
106 indent_amount => 2,
107 newline => "<br />\n",
108 colormap => {
1bb3956e 109 select => ['<span class="select">' , '</span>'],
110 where => ['<span class="where">' , '</span>'],
111 from => ['<span class="from">' , '</span>'],
112 join => ['<span class="join">' , '</span>'],
113 on => ['<span class="on">' , '</span>'],
114 'group by' => ['<span class="group-by">', '</span>'],
1536de15 115 },
7e5600e9 116 indentmap => { %indents },
75c3a063 117 },
118 none => {
1536de15 119 colormap => {},
120 indentmap => {},
75c3a063 121 },
122);
123
3be357b0 124eval {
125 require Term::ANSIColor;
126 $profiles{console}->{colormap} = {
127 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
128 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
129 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
130 };
131};
132
75c3a063 133sub new {
134 my ($class, $args) = @_;
135
136 my $profile = delete $args->{profile} || 'none';
137 my $data = {%{$profiles{$profile}}, %{$args||{}}};
138
139 bless $data, $class
140}
d695b0ad 141
01dd4e4f 142sub parse {
d695b0ad 143 my ($self, $s) = @_;
01dd4e4f 144
145 # tokenize string, and remove all optional whitespace
146 my $tokens = [];
147 foreach my $token (split $tokenizer_re, $s) {
148 push @$tokens, $token if (length $token) && ($token =~ /\S/);
149 }
150
d695b0ad 151 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 152 return $tree;
153}
154
155sub _recurse_parse {
d695b0ad 156 my ($self, $tokens, $state) = @_;
01dd4e4f 157
158 my $left;
159 while (1) { # left-associative parsing
160
161 my $lookahead = $tokens->[0];
162 if ( not defined($lookahead)
163 or
164 ($state == PARSE_IN_PARENS && $lookahead eq ')')
165 or
166 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
167 or
168 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
169 ) {
170 return $left;
171 }
172
173 my $token = shift @$tokens;
174
175 # nested expression in ()
176 if ($token eq '(' ) {
d695b0ad 177 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
178 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
179 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 180
181 $left = $left ? [@$left, [PAREN => [$right] ]]
182 : [PAREN => [$right] ];
183 }
184 # AND/OR
185 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
186 my $op = uc $token;
d695b0ad 187 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 188
189 # Merge chunks if logic matches
190 if (ref $right and $op eq $right->[0]) {
191 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
192 }
193 else {
194 $left = [$op => [$left, $right]];
195 }
196 }
197 # binary operator keywords
198 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
199 my $op = uc $token;
d695b0ad 200 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 201
202 # A between with a simple LITERAL for a 1st RHS argument needs a
203 # rerun of the search to (hopefully) find the proper AND construct
204 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
205 unshift @$tokens, $right->[1][0];
d695b0ad 206 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 207 }
208
209 $left = [$op => [$left, $right] ];
210 }
211 # expression terminator keywords (as they start a new expression)
212 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
213 my $op = uc $token;
d695b0ad 214 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 215 $left = $left ? [ $left, [$op => [$right] ]]
216 : [ $op => [$right] ];
217 }
218 # NOT (last as to allow all other NOT X pieces first)
219 elsif ( $token =~ /^ not $/ix ) {
220 my $op = uc $token;
d695b0ad 221 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 222 $left = $left ? [ @$left, [$op => [$right] ]]
223 : [ $op => [$right] ];
224
225 }
226 # literal (eat everything on the right until RHS termination)
227 else {
d695b0ad 228 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
229 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
230 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
01dd4e4f 231 }
232 }
233}
234
d695b0ad 235sub format_keyword {
236 my ($self, $keyword) = @_;
237
1536de15 238 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 239 $keyword = "$around->[0]$keyword$around->[1]";
240 }
241
242 return $keyword
243}
244
a24cc3a0 245sub whitespace {
246 my ($self, $keyword, $depth) = @_;
e171c446 247
248 my $before = '';
1536de15 249 my $after = ' ';
250 if (defined $self->indentmap->{lc $keyword}) {
251 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 252 }
1a67e3a0 253 $before = '' if $depth == 0 and lc $keyword eq 'select';
e171c446 254 return [$before, $after];
a24cc3a0 255}
256
1536de15 257sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 258
0569a14f 259sub _is_select {
260 my $tree = shift;
261 $tree = $tree->[0] while ref $tree;
262
ca8aec12 263 defined $tree && lc $tree eq 'select';
0569a14f 264}
265
01dd4e4f 266sub unparse {
a24cc3a0 267 my ($self, $tree, $depth) = @_;
268
e171c446 269 $depth ||= 0;
01dd4e4f 270
271 if (not $tree ) {
272 return '';
273 }
a24cc3a0 274
275 my $car = $tree->[0];
276 my $cdr = $tree->[1];
277
278 if (ref $car) {
e171c446 279 return join ('', map $self->unparse($_, $depth), @$tree);
01dd4e4f 280 }
a24cc3a0 281 elsif ($car eq 'LITERAL') {
282 return $cdr->[0];
01dd4e4f 283 }
a24cc3a0 284 elsif ($car eq 'PAREN') {
e171c446 285 return '(' .
a24cc3a0 286 join(' ',
0569a14f 287 map $self->unparse($_, $depth + 2), @{$cdr}) .
1536de15 288 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ')';
01dd4e4f 289 }
a24cc3a0 290 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
e171c446 291 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
01dd4e4f 292 }
293 else {
a24cc3a0 294 my ($l, $r) = @{$self->whitespace($car, $depth)};
e171c446 295 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
01dd4e4f 296 }
297}
298
d695b0ad 299sub format { my $self = shift; $self->unparse($self->parse(@_)) }
01dd4e4f 300
3011;
302
3be357b0 303=pod
304
305=head1 SYNOPSIS
306
307 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
308
309 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
310
311 # SELECT *
312 # FROM foo
313 # WHERE foo.a > 2
314