1 package SQL::Abstract::Tree;
9 use base 'Class::Accessor::Grouped';
11 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
12 newline indent_string indent_amount colormap indentmap fill_in_placeholders
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;
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 = (
35 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
36 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
54 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
57 # These are binary operator keywords always a single LHS and RHS
58 # * AND/OR are handled separately as they are N-ary
59 # * so is NOT as being unary
60 # * BETWEEN without paranthesis around the ANDed arguments (which
61 # makes it a non-binary op) is detected and accomodated in
63 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
64 my @binary_op_keywords = (
67 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
68 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
70 (qw/< > != <> = <= >=/)
73 { '\b (?: NOT \s+)?' . $_ . '\b' }
78 my $tokenizer_re_str = join("\n\t|\n",
79 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
83 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
85 sub _binary_op_keywords { @binary_op_keywords }
106 fill_in_placeholders => 1,
107 indent_string => ' ',
111 indentmap => { %indents },
113 console_monochrome => {
114 fill_in_placeholders => 1,
115 indent_string => ' ',
119 indentmap => { %indents },
122 fill_in_placeholders => 1,
123 indent_string => ' ',
125 newline => "<br />\n",
127 select => ['<span class="select">' , '</span>'],
128 'insert into' => ['<span class="insert-into">' , '</span>'],
129 update => ['<span class="select">' , '</span>'],
130 'delete from' => ['<span class="delete-from">' , '</span>'],
131 where => ['<span class="where">' , '</span>'],
132 from => ['<span class="from">' , '</span>'],
133 join => ['<span class="join">' , '</span>'],
134 on => ['<span class="on">' , '</span>'],
135 'group by' => ['<span class="group-by">', '</span>'],
136 'order by' => ['<span class="order-by">', '</span>'],
137 set => ['<span class="set">', '</span>'],
138 into => ['<span class="into">', '</span>'],
139 values => ['<span class="values">', '</span>'],
141 indentmap => { %indents },
150 require Term::ANSIColor;
151 $profiles{console}->{colormap} = {
152 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
153 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
154 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
155 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
157 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
158 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
160 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
161 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
163 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
164 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
165 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
167 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
168 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
173 my ($class, $args) = @_;
175 my $profile = delete $args->{profile} || 'none';
176 my $data = {%{$profiles{$profile}}, %{$args||{}}};
184 # tokenize string, and remove all optional whitespace
186 foreach my $token (split $tokenizer_re, $s) {
187 push @$tokens, $token if (length $token) && ($token =~ /\S/);
190 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
195 my ($self, $tokens, $state) = @_;
198 while (1) { # left-associative parsing
200 my $lookahead = $tokens->[0];
201 if ( not defined($lookahead)
203 ($state == PARSE_IN_PARENS && $lookahead eq ')')
205 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
207 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
212 my $token = shift @$tokens;
214 # nested expression in ()
215 if ($token eq '(' ) {
216 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
217 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
218 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
220 $left = $left ? [@$left, [PAREN => [$right] ]]
221 : [PAREN => [$right] ];
224 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
226 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
228 # Merge chunks if logic matches
229 if (ref $right and $op eq $right->[0]) {
230 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
233 $left = [$op => [$left, $right]];
236 # binary operator keywords
237 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
239 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
241 # A between with a simple LITERAL for a 1st RHS argument needs a
242 # rerun of the search to (hopefully) find the proper AND construct
243 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
244 unshift @$tokens, $right->[1][0];
245 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
248 $left = [$op => [$left, $right] ];
250 # expression terminator keywords (as they start a new expression)
251 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
253 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
254 $left = $left ? [ $left, [$op => [$right] ]]
255 : [ $op => [$right] ];
257 # NOT (last as to allow all other NOT X pieces first)
258 elsif ( $token =~ /^ not $/ix ) {
260 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
261 $left = $left ? [ @$left, [$op => [$right] ]]
262 : [ $op => [$right] ];
265 # literal (eat everything on the right until RHS termination)
267 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
268 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
269 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
275 my ($self, $keyword) = @_;
277 if (my $around = $self->colormap->{lc $keyword}) {
278 $keyword = "$around->[0]$keyword$around->[1]";
293 my ($self, $keyword, $depth) = @_;
296 if (defined $self->indentmap->{lc $keyword}) {
297 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
299 $before = '' if $depth == 0 and defined $starters{lc $keyword};
300 return [$before, ' '];
303 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
306 my ($self, $tree) = @_;
307 $tree = $tree->[0] while ref $tree;
309 defined $tree && defined $self->indentmap->{lc $tree};
312 sub _fill_in_placeholder {
313 my ($self, $bindargs) = @_;
315 if ($self->fill_in_placeholders) {
316 my $val = pop @{$bindargs};
325 my ($self, $tree, $bindargs, $depth) = @_;
333 my $car = $tree->[0];
334 my $cdr = $tree->[1];
337 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
339 elsif ($car eq 'LITERAL') {
340 if ($cdr->[0] eq '?') {
341 return $self->_fill_in_placeholder($bindargs)
345 elsif ($car eq 'PAREN') {
348 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
349 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
351 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
352 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
355 my ($l, $r) = @{$self->whitespace($car, $depth)};
356 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
360 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
368 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
370 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
380 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
384 $sqlat->format('SELECT * FROM bar')
386 Returns a formatting string based on wthe string passed in