1 package SQL::Abstract::Tree;
8 use Term::ANSIColor 'color';
9 use base 'Class::Accessor::Grouped';
11 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
12 newline indent_string indent_amount colormap indentmap
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 = (
31 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
32 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
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
57 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
58 my @binary_op_keywords = (
61 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
62 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
64 (qw/< > != <> = <= >=/)
67 { '\b (?: NOT \s+)?' . $_ . '\b' }
72 my $tokenizer_re_str = join("\n\t|\n",
73 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
77 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
79 sub _binary_op_keywords { @binary_op_keywords }
87 select => [color('red'), color('reset')],
88 where => [color('green'), color('reset')],
89 from => [color('cyan'), color('reset')],
104 my ($class, $args) = @_;
106 my $profile = delete $args->{profile} || 'none';
107 my $data = {%{$profiles{$profile}}, %{$args||{}}};
115 # tokenize string, and remove all optional whitespace
117 foreach my $token (split $tokenizer_re, $s) {
118 push @$tokens, $token if (length $token) && ($token =~ /\S/);
121 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
126 my ($self, $tokens, $state) = @_;
129 while (1) { # left-associative parsing
131 my $lookahead = $tokens->[0];
132 if ( not defined($lookahead)
134 ($state == PARSE_IN_PARENS && $lookahead eq ')')
136 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
138 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
143 my $token = shift @$tokens;
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);
151 $left = $left ? [@$left, [PAREN => [$right] ]]
152 : [PAREN => [$right] ];
155 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
157 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
159 # Merge chunks if logic matches
160 if (ref $right and $op eq $right->[0]) {
161 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
164 $left = [$op => [$left, $right]];
167 # binary operator keywords
168 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
170 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
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);
179 $left = [$op => [$left, $right] ];
181 # expression terminator keywords (as they start a new expression)
182 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
184 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
185 $left = $left ? [ $left, [$op => [$right] ]]
186 : [ $op => [$right] ];
188 # NOT (last as to allow all other NOT X pieces first)
189 elsif ( $token =~ /^ not $/ix ) {
191 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
192 $left = $left ? [ @$left, [$op => [$right] ]]
193 : [ $op => [$right] ];
196 # literal (eat everything on the right until RHS termination)
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)||()] ];
206 my ($self, $keyword) = @_;
208 if (my $around = $self->colormap->{lc $keyword}) {
209 $keyword = "$around->[0]$keyword$around->[1]";
216 my ($self, $keyword, $depth) = @_;
220 if (defined $self->indentmap->{lc $keyword}) {
221 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
223 $before = '' if $depth == 0 and lc $keyword eq 'select';
224 return [$before, $after];
227 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
231 $tree = $tree->[0] while ref $tree;
233 defined $tree && lc $tree eq 'select';
237 my ($self, $tree, $depth) = @_;
245 my $car = $tree->[0];
246 my $cdr = $tree->[1];
249 return join ('', map $self->unparse($_, $depth), @$tree);
251 elsif ($car eq 'LITERAL') {
254 elsif ($car eq 'PAREN') {
257 map $self->unparse($_, $depth + 2), @{$cdr}) .
258 (_is_select($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ')';
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});
264 my ($l, $r) = @{$self->whitespace($car, $depth)};
265 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
269 sub format { my $self = shift; $self->unparse($self->parse(@_)) }