1 package SQL::Abstract::Tree;
7 # Parser states for _recurse_parse()
8 use constant PARSE_TOP_LEVEL => 0;
9 use constant PARSE_IN_EXPR => 1;
10 use constant PARSE_IN_PARENS => 2;
11 use constant PARSE_RHS => 3;
13 # These SQL keywords always signal end of the current expression (except inside
14 # of a parenthesized subexpression).
15 # Format: A list of strings that will be compiled to extended syntax (ie.
16 # /.../x) regexes, without capturing parentheses. They will be automatically
17 # anchored to word boundaries to match the whole token).
18 my @expression_terminator_sql_keywords = (
23 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
24 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
43 # These are binary operator keywords always a single LHS and RHS
44 # * AND/OR are handled separately as they are N-ary
45 # * so is NOT as being unary
46 # * BETWEEN without paranthesis around the ANDed arguments (which
47 # makes it a non-binary op) is detected and accomodated in
49 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
50 my @binary_op_keywords = (
53 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
54 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
56 (qw/< > != <> = <= >=/)
59 { '\b (?: NOT \s+)?' . $_ . '\b' }
64 my $tokenizer_re_str = join("\n\t|\n",
65 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
69 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
71 sub _binary_op_keywords { @binary_op_keywords }
73 sub new { bless sub {}, shift }
78 # tokenize string, and remove all optional whitespace
80 foreach my $token (split $tokenizer_re, $s) {
81 push @$tokens, $token if (length $token) && ($token =~ /\S/);
84 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
89 my ($self, $tokens, $state) = @_;
92 while (1) { # left-associative parsing
94 my $lookahead = $tokens->[0];
95 if ( not defined($lookahead)
97 ($state == PARSE_IN_PARENS && $lookahead eq ')')
99 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
101 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
106 my $token = shift @$tokens;
108 # nested expression in ()
109 if ($token eq '(' ) {
110 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
111 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
112 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
114 $left = $left ? [@$left, [PAREN => [$right] ]]
115 : [PAREN => [$right] ];
118 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
120 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
122 # Merge chunks if logic matches
123 if (ref $right and $op eq $right->[0]) {
124 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
127 $left = [$op => [$left, $right]];
130 # binary operator keywords
131 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
133 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
135 # A between with a simple LITERAL for a 1st RHS argument needs a
136 # rerun of the search to (hopefully) find the proper AND construct
137 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
138 unshift @$tokens, $right->[1][0];
139 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
142 $left = [$op => [$left, $right] ];
144 # expression terminator keywords (as they start a new expression)
145 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
147 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
148 $left = $left ? [ $left, [$op => [$right] ]]
149 : [ $op => [$right] ];
151 # NOT (last as to allow all other NOT X pieces first)
152 elsif ( $token =~ /^ not $/ix ) {
154 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
155 $left = $left ? [ @$left, [$op => [$right] ]]
156 : [ $op => [$right] ];
159 # literal (eat everything on the right until RHS termination)
161 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
162 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
163 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
168 use Term::ANSIColor 'color';
170 my %ghetto_colormap = (
171 select => [color('red'), color('reset')],
172 where => [color('green'), color('reset')],
173 from => [color('cyan'), color('reset')],
177 my ($self, $keyword) = @_;
179 if (my $around = $ghetto_colormap{lc $keyword}) {
180 $keyword = "$around->[0]$keyword$around->[1]";
187 my %ghetto_whitespacemap = (
194 my ($self, $keyword, $depth) = @_;
198 if (defined $ghetto_whitespacemap{lc $keyword}) {
199 $before = $self->newline . $self->indent($depth + $ghetto_whitespacemap{lc $keyword});
201 $before = '' if $depth == 0 and lc $keyword eq 'select';
202 return [$before, $after];
207 sub indent { ' ' x $_[1] }
211 $tree = $tree->[0] while ref $tree;
213 defined $tree && lc $tree eq 'select';
217 my ($self, $tree, $depth) = @_;
225 my $car = $tree->[0];
226 my $cdr = $tree->[1];
229 return join ('', map $self->unparse($_, $depth), @$tree);
231 elsif ($car eq 'LITERAL') {
234 elsif ($car eq 'PAREN') {
237 map $self->unparse($_, $depth + 2), @{$cdr}) .
238 (_is_select($cdr)?$self->newline.$self->indent($depth + 1):'') . ')';
240 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
241 return join (" $car ", map $self->unparse($_, $depth), @{$cdr});
244 my ($l, $r) = @{$self->whitespace($car, $depth)};
245 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $depth);
249 sub format { my $self = shift; $self->unparse($self->parse(@_)) }