1 package SQL::Abstract::Tree;
8 use Hash::Merge 'merge';
10 Hash::Merge::specify_behavior({
12 SCALAR => sub { $_[1] },
13 ARRAY => sub { [ $_[0], @{$_[1]} ] },
14 HASH => sub { $_[1] },
17 SCALAR => sub { $_[1] },
18 ARRAY => sub { $_[1] },
19 HASH => sub { $_[1] },
22 SCALAR => sub { $_[1] },
23 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
24 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
28 use base 'Class::Accessor::Grouped';
30 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
31 newline indent_string indent_amount colormap indentmap fill_in_placeholders
34 # Parser states for _recurse_parse()
35 use constant PARSE_TOP_LEVEL => 0;
36 use constant PARSE_IN_EXPR => 1;
37 use constant PARSE_IN_PARENS => 2;
38 use constant PARSE_RHS => 3;
40 # These SQL keywords always signal end of the current expression (except inside
41 # of a parenthesized subexpression).
42 # Format: A list of strings that will be compiled to extended syntax (ie.
43 # /.../x) regexes, without capturing parentheses. They will be automatically
44 # anchored to word boundaries to match the whole token).
45 my @expression_terminator_sql_keywords = (
54 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
55 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
73 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
76 # These are binary operator keywords always a single LHS and RHS
77 # * AND/OR are handled separately as they are N-ary
78 # * so is NOT as being unary
79 # * BETWEEN without paranthesis around the ANDed arguments (which
80 # makes it a non-binary op) is detected and accomodated in
82 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
83 my @binary_op_keywords = (
86 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
87 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
89 (qw/< > != <> = <= >=/)
92 { '\b (?: NOT \s+)?' . $_ . '\b' }
97 my $tokenizer_re_str = join("\n\t|\n",
98 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
102 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
104 sub _binary_op_keywords { @binary_op_keywords }
125 fill_in_placeholders => 1,
126 indent_string => ' ',
130 indentmap => { %indents },
132 console_monochrome => {
133 fill_in_placeholders => 1,
134 indent_string => ' ',
138 indentmap => { %indents },
141 fill_in_placeholders => 1,
142 indent_string => ' ',
144 newline => "<br />\n",
146 select => ['<span class="select">' , '</span>'],
147 'insert into' => ['<span class="insert-into">' , '</span>'],
148 update => ['<span class="select">' , '</span>'],
149 'delete from' => ['<span class="delete-from">' , '</span>'],
150 where => ['<span class="where">' , '</span>'],
151 from => ['<span class="from">' , '</span>'],
152 join => ['<span class="join">' , '</span>'],
153 on => ['<span class="on">' , '</span>'],
154 'group by' => ['<span class="group-by">', '</span>'],
155 'order by' => ['<span class="order-by">', '</span>'],
156 set => ['<span class="set">', '</span>'],
157 into => ['<span class="into">', '</span>'],
158 values => ['<span class="values">', '</span>'],
160 indentmap => { %indents },
169 require Term::ANSIColor;
170 $profiles{console}->{colormap} = {
171 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
172 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
173 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
174 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
176 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
177 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
179 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
180 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
182 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
183 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
184 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
186 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
187 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
193 my $args = shift || {};
195 my $profile = delete $args->{profile} || 'none';
196 my $data = merge( $profiles{$profile}, $args );
204 # tokenize string, and remove all optional whitespace
206 foreach my $token (split $tokenizer_re, $s) {
207 push @$tokens, $token if (length $token) && ($token =~ /\S/);
210 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
215 my ($self, $tokens, $state) = @_;
218 while (1) { # left-associative parsing
220 my $lookahead = $tokens->[0];
221 if ( not defined($lookahead)
223 ($state == PARSE_IN_PARENS && $lookahead eq ')')
225 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
227 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
232 my $token = shift @$tokens;
234 # nested expression in ()
235 if ($token eq '(' ) {
236 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
237 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
238 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
240 $left = $left ? [@$left, [PAREN => [$right] ]]
241 : [PAREN => [$right] ];
244 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
246 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
248 # Merge chunks if logic matches
249 if (ref $right and $op eq $right->[0]) {
250 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
253 $left = [$op => [$left, $right]];
256 # binary operator keywords
257 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
259 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
261 # A between with a simple LITERAL for a 1st RHS argument needs a
262 # rerun of the search to (hopefully) find the proper AND construct
263 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
264 unshift @$tokens, $right->[1][0];
265 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
268 $left = [$op => [$left, $right] ];
270 # expression terminator keywords (as they start a new expression)
271 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
273 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
274 $left = $left ? [ $left, [$op => [$right] ]]
275 : [ $op => [$right] ];
277 # NOT (last as to allow all other NOT X pieces first)
278 elsif ( $token =~ /^ not $/ix ) {
280 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
281 $left = $left ? [ @$left, [$op => [$right] ]]
282 : [ $op => [$right] ];
285 # literal (eat everything on the right until RHS termination)
287 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
288 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
289 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
295 my ($self, $keyword) = @_;
297 if (my $around = $self->colormap->{lc $keyword}) {
298 $keyword = "$around->[0]$keyword$around->[1]";
312 my ($self, $keyword, $depth) = @_;
315 if (defined $self->indentmap->{lc $keyword}) {
316 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
318 $before = '' if $depth == 0 and defined $starters{lc $keyword};
319 return [$before, ' '];
322 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
325 my ($self, $tree) = @_;
326 $tree = $tree->[0] while ref $tree;
328 defined $tree && defined $self->indentmap->{lc $tree};
331 sub _fill_in_placeholder {
332 my ($self, $bindargs) = @_;
334 if ($self->fill_in_placeholders) {
335 my $val = pop @{$bindargs};
344 my ($self, $tree, $bindargs, $depth) = @_;
352 my $car = $tree->[0];
353 my $cdr = $tree->[1];
356 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
358 elsif ($car eq 'LITERAL') {
359 if ($cdr->[0] eq '?') {
360 return $self->_fill_in_placeholder($bindargs)
364 elsif ($car eq 'PAREN') {
367 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
368 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
370 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
371 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
374 my ($l, $r) = @{$self->whitespace($car, $depth)};
375 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
379 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
387 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
389 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
399 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
403 $sqlat->format('SELECT * FROM bar')
405 Returns a formatting string based on wthe string passed in