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
32 include_caller caller_depth
35 # Parser states for _recurse_parse()
36 use constant PARSE_TOP_LEVEL => 0;
37 use constant PARSE_IN_EXPR => 1;
38 use constant PARSE_IN_PARENS => 2;
39 use constant PARSE_RHS => 3;
41 # These SQL keywords always signal end of the current expression (except inside
42 # of a parenthesized subexpression).
43 # Format: A list of strings that will be compiled to extended syntax (ie.
44 # /.../x) regexes, without capturing parentheses. They will be automatically
45 # anchored to word boundaries to match the whole token).
46 my @expression_terminator_sql_keywords = (
55 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
56 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
74 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
77 # These are binary operator keywords always a single LHS and RHS
78 # * AND/OR are handled separately as they are N-ary
79 # * so is NOT as being unary
80 # * BETWEEN without paranthesis around the ANDed arguments (which
81 # makes it a non-binary op) is detected and accomodated in
83 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
84 my @binary_op_keywords = (
87 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
88 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
90 (qw/< > != <> = <= >=/)
93 { '\b (?: NOT \s+)?' . $_ . '\b' }
98 my $tokenizer_re_str = join("\n\t|\n",
99 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
103 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
105 sub _binary_op_keywords { @binary_op_keywords }
127 fill_in_placeholders => 1,
128 indent_string => ' ',
132 indentmap => { %indents },
134 console_monochrome => {
136 fill_in_placeholders => 1,
137 indent_string => ' ',
141 indentmap => { %indents },
145 fill_in_placeholders => 1,
146 indent_string => ' ',
148 newline => "<br />\n",
150 select => ['<span class="select">' , '</span>'],
151 'insert into' => ['<span class="insert-into">' , '</span>'],
152 update => ['<span class="select">' , '</span>'],
153 'delete from' => ['<span class="delete-from">' , '</span>'],
154 where => ['<span class="where">' , '</span>'],
155 from => ['<span class="from">' , '</span>'],
156 join => ['<span class="join">' , '</span>'],
157 on => ['<span class="on">' , '</span>'],
158 'group by' => ['<span class="group-by">', '</span>'],
159 'order by' => ['<span class="order-by">', '</span>'],
160 set => ['<span class="set">', '</span>'],
161 into => ['<span class="into">', '</span>'],
162 values => ['<span class="values">', '</span>'],
164 indentmap => { %indents },
173 require Term::ANSIColor;
174 $profiles{console}->{colormap} = {
175 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
176 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
177 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
178 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
180 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
181 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
183 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
184 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
186 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
187 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
188 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
190 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
191 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
197 my $args = shift || {};
199 my $profile = delete $args->{profile} || 'none';
200 my $data = merge( $profiles{$profile}, $args );
208 # tokenize string, and remove all optional whitespace
210 foreach my $token (split $tokenizer_re, $s) {
211 push @$tokens, $token if (length $token) && ($token =~ /\S/);
214 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
219 my ($self, $tokens, $state) = @_;
222 while (1) { # left-associative parsing
224 my $lookahead = $tokens->[0];
225 if ( not defined($lookahead)
227 ($state == PARSE_IN_PARENS && $lookahead eq ')')
229 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
231 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
236 my $token = shift @$tokens;
238 # nested expression in ()
239 if ($token eq '(' ) {
240 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
241 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
242 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
244 $left = $left ? [@$left, [PAREN => [$right] ]]
245 : [PAREN => [$right] ];
248 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
250 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
252 # Merge chunks if logic matches
253 if (ref $right and $op eq $right->[0]) {
254 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
257 $left = [$op => [$left, $right]];
260 # binary operator keywords
261 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
263 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
265 # A between with a simple LITERAL for a 1st RHS argument needs a
266 # rerun of the search to (hopefully) find the proper AND construct
267 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
268 unshift @$tokens, $right->[1][0];
269 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
272 $left = [$op => [$left, $right] ];
274 # expression terminator keywords (as they start a new expression)
275 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
277 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
278 $left = $left ? [ $left, [$op => [$right] ]]
279 : [ $op => [$right] ];
281 # NOT (last as to allow all other NOT X pieces first)
282 elsif ( $token =~ /^ not $/ix ) {
284 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
285 $left = $left ? [ @$left, [$op => [$right] ]]
286 : [ $op => [$right] ];
289 # literal (eat everything on the right until RHS termination)
291 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
292 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
293 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
299 my ($self, $keyword) = @_;
301 if (my $around = $self->colormap->{lc $keyword}) {
302 $keyword = "$around->[0]$keyword$around->[1]";
316 my ($self, $keyword, $depth) = @_;
319 if (defined $self->indentmap->{lc $keyword}) {
320 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
322 $before = '' if $depth == 0 and defined $starters{lc $keyword};
323 return [$before, ' '];
326 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
329 my ($self, $tree) = @_;
330 $tree = $tree->[0] while ref $tree;
332 defined $tree && defined $self->indentmap->{lc $tree};
335 sub _fill_in_placeholder {
336 my ($self, $bindargs) = @_;
338 if ($self->fill_in_placeholders) {
339 my $val = pop @{$bindargs} || '';
348 my ($self, $depth) = @_;
350 return '' if $depth != 1 or !$self->include_caller;
352 my @caller_info = caller($self->caller_depth + 0);
354 " at $caller_info[1] line $caller_info[2].";
358 my ($self, $tree, $bindargs, $indent, $depth) = @_;
367 my $car = $tree->[0];
368 my $cdr = $tree->[1];
371 return join ('', map $self->unparse($_, $bindargs, $indent, $depth + 1), @$tree);
373 elsif ($car eq 'LITERAL') {
374 if ($cdr->[0] eq '?') {
375 return $self->_fill_in_placeholder($bindargs)
379 elsif ($car eq 'PAREN') {
382 map $self->unparse($_, $bindargs, $indent + 2, $depth + 1), @{$cdr}) .
383 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($indent + 1):'') . ') ';
385 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
386 return join (" $car ", map $self->unparse($_, $bindargs, $indent, $depth + 1), @{$cdr});
389 my ($l, $r) = @{$self->whitespace($car, $indent)};
390 return sprintf "$l%s %s$r%s", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $indent, $depth + 1), $self->_caller_info($depth);
394 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
402 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
404 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
414 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
418 $sqlat->format('SELECT * FROM bar')
420 Returns a formatting string based on wthe string passed in