Commit | Line | Data |
01dd4e4f |
1 | package SQL::Abstract::Tree; |
2 | |
3 | use strict; |
4 | use warnings; |
5 | use Carp; |
6 | |
1536de15 |
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 | |
01dd4e4f |
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 | |
75c3a063 |
81 | my %profiles = ( |
82 | console => { |
1536de15 |
83 | indent_string => ' ', |
75c3a063 |
84 | indent_amount => 2, |
1536de15 |
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 | }, |
75c3a063 |
96 | }, |
97 | none => { |
1536de15 |
98 | colormap => {}, |
99 | indentmap => {}, |
75c3a063 |
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 | } |
d695b0ad |
111 | |
01dd4e4f |
112 | sub parse { |
d695b0ad |
113 | my ($self, $s) = @_; |
01dd4e4f |
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 | |
d695b0ad |
121 | my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL); |
01dd4e4f |
122 | return $tree; |
123 | } |
124 | |
125 | sub _recurse_parse { |
d695b0ad |
126 | my ($self, $tokens, $state) = @_; |
01dd4e4f |
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 '(' ) { |
d695b0ad |
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); |
01dd4e4f |
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; |
d695b0ad |
157 | my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
01dd4e4f |
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; |
d695b0ad |
170 | my $right = $self->_recurse_parse($tokens, PARSE_RHS); |
01dd4e4f |
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]; |
d695b0ad |
176 | $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
01dd4e4f |
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; |
d695b0ad |
184 | my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR); |
01dd4e4f |
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; |
d695b0ad |
191 | my $right = $self->_recurse_parse ($tokens, PARSE_RHS); |
01dd4e4f |
192 | $left = $left ? [ @$left, [$op => [$right] ]] |
193 | : [ $op => [$right] ]; |
194 | |
195 | } |
196 | # literal (eat everything on the right until RHS termination) |
197 | else { |
d695b0ad |
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)||()] ]; |
01dd4e4f |
201 | } |
202 | } |
203 | } |
204 | |
d695b0ad |
205 | sub format_keyword { |
206 | my ($self, $keyword) = @_; |
207 | |
1536de15 |
208 | if (my $around = $self->colormap->{lc $keyword}) { |
d695b0ad |
209 | $keyword = "$around->[0]$keyword$around->[1]"; |
210 | } |
211 | |
212 | return $keyword |
213 | } |
214 | |
a24cc3a0 |
215 | sub whitespace { |
216 | my ($self, $keyword, $depth) = @_; |
e171c446 |
217 | |
218 | my $before = ''; |
1536de15 |
219 | my $after = ' '; |
220 | if (defined $self->indentmap->{lc $keyword}) { |
221 | $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword}); |
a24cc3a0 |
222 | } |
1a67e3a0 |
223 | $before = '' if $depth == 0 and lc $keyword eq 'select'; |
e171c446 |
224 | return [$before, $after]; |
a24cc3a0 |
225 | } |
226 | |
1536de15 |
227 | sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) } |
a24cc3a0 |
228 | |
0569a14f |
229 | sub _is_select { |
230 | my $tree = shift; |
231 | $tree = $tree->[0] while ref $tree; |
232 | |
ca8aec12 |
233 | defined $tree && lc $tree eq 'select'; |
0569a14f |
234 | } |
235 | |
01dd4e4f |
236 | sub unparse { |
a24cc3a0 |
237 | my ($self, $tree, $depth) = @_; |
238 | |
e171c446 |
239 | $depth ||= 0; |
01dd4e4f |
240 | |
241 | if (not $tree ) { |
242 | return ''; |
243 | } |
a24cc3a0 |
244 | |
245 | my $car = $tree->[0]; |
246 | my $cdr = $tree->[1]; |
247 | |
248 | if (ref $car) { |
e171c446 |
249 | return join ('', map $self->unparse($_, $depth), @$tree); |
01dd4e4f |
250 | } |
a24cc3a0 |
251 | elsif ($car eq 'LITERAL') { |
252 | return $cdr->[0]; |
01dd4e4f |
253 | } |
a24cc3a0 |
254 | elsif ($car eq 'PAREN') { |
e171c446 |
255 | return '(' . |
a24cc3a0 |
256 | join(' ', |
0569a14f |
257 | map $self->unparse($_, $depth + 2), @{$cdr}) . |
1536de15 |
258 | (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ')'; |
01dd4e4f |
259 | } |
a24cc3a0 |
260 | elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) { |
e171c446 |
261 | return join (" $car ", map $self->unparse($_, $depth), @{$cdr}); |
01dd4e4f |
262 | } |
263 | else { |
a24cc3a0 |
264 | my ($l, $r) = @{$self->whitespace($car, $depth)}; |
e171c446 |
265 | return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth); |
01dd4e4f |
266 | } |
267 | } |
268 | |
d695b0ad |
269 | sub format { my $self = shift; $self->unparse($self->parse(@_)) } |
01dd4e4f |
270 | |
271 | 1; |
272 | |