doc additions and a method rename
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
CommitLineData
01dd4e4f 1package SQL::Abstract::Tree;
2
3use strict;
4use warnings;
5use Carp;
6
a97eb57c 7use List::Util;
bc482085 8use Hash::Merge;
2fed0b4b 9
bc482085 10my $merger = Hash::Merge->new;
11
12$merger->specify_behavior({
2fed0b4b 13 SCALAR => {
14 SCALAR => sub { $_[1] },
15 ARRAY => sub { [ $_[0], @{$_[1]} ] },
16 HASH => sub { $_[1] },
17 },
18 ARRAY => {
19 SCALAR => sub { $_[1] },
20 ARRAY => sub { $_[1] },
21 HASH => sub { $_[1] },
22 },
23 HASH => {
24 SCALAR => sub { $_[1] },
25 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
26 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
27 },
28}, 'My Behavior' );
1536de15 29
1536de15 30use base 'Class::Accessor::Grouped';
31
32__PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
fb272e73 33 newline indent_string indent_amount colormap indentmap fill_in_placeholders
1536de15 34);
35
01dd4e4f 36# Parser states for _recurse_parse()
37use constant PARSE_TOP_LEVEL => 0;
38use constant PARSE_IN_EXPR => 1;
39use constant PARSE_IN_PARENS => 2;
40use constant PARSE_RHS => 3;
41
42# These SQL keywords always signal end of the current expression (except inside
43# of a parenthesized subexpression).
44# Format: A list of strings that will be compiled to extended syntax (ie.
45# /.../x) regexes, without capturing parentheses. They will be automatically
46# anchored to word boundaries to match the whole token).
47my @expression_terminator_sql_keywords = (
48 'SELECT',
7853a177 49 'UPDATE',
50 'INSERT \s+ INTO',
51 'DELETE \s+ FROM',
3d910890 52 'FROM',
7853a177 53 'SET',
01dd4e4f 54 '(?:
55 (?:
56 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
57 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
58 )?
59 JOIN
60 )',
61 'ON',
62 'WHERE',
7853a177 63 'VALUES',
01dd4e4f 64 'EXISTS',
65 'GROUP \s+ BY',
66 'HAVING',
67 'ORDER \s+ BY',
68 'LIMIT',
69 'OFFSET',
70 'FOR',
71 'UNION',
72 'INTERSECT',
73 'EXCEPT',
74 'RETURNING',
8d0dd7dc 75 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
01dd4e4f 76);
77
78# These are binary operator keywords always a single LHS and RHS
79# * AND/OR are handled separately as they are N-ary
80# * so is NOT as being unary
81# * BETWEEN without paranthesis around the ANDed arguments (which
82# makes it a non-binary op) is detected and accomodated in
83# _recurse_parse()
84my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
85my @binary_op_keywords = (
86 ( map
87 {
88 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
89 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
90 }
91 (qw/< > != <> = <= >=/)
92 ),
93 ( map
94 { '\b (?: NOT \s+)?' . $_ . '\b' }
95 (qw/IN BETWEEN LIKE/)
96 ),
97);
98
99my $tokenizer_re_str = join("\n\t|\n",
100 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
101 @binary_op_keywords,
102);
103
104my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
105
106sub _binary_op_keywords { @binary_op_keywords }
107
7e5600e9 108my %indents = (
7853a177 109 select => 0,
110 update => 0,
111 'insert into' => 0,
112 'delete from' => 0,
3d910890 113 from => 1,
91916220 114 where => 0,
7853a177 115 join => 1,
116 'left join' => 1,
117 on => 2,
91916220 118 'group by' => 0,
119 'order by' => 0,
7853a177 120 set => 1,
121 into => 1,
91916220 122 values => 1,
7e5600e9 123);
124
75c3a063 125my %profiles = (
126 console => {
84c65032 127 fill_in_placeholders => 1,
1536de15 128 indent_string => ' ',
75c3a063 129 indent_amount => 2,
1536de15 130 newline => "\n",
3be357b0 131 colormap => {},
7e5600e9 132 indentmap => { %indents },
3be357b0 133 },
134 console_monochrome => {
84c65032 135 fill_in_placeholders => 1,
3be357b0 136 indent_string => ' ',
137 indent_amount => 2,
138 newline => "\n",
139 colormap => {},
7e5600e9 140 indentmap => { %indents },
141 },
142 html => {
84c65032 143 fill_in_placeholders => 1,
7e5600e9 144 indent_string => '&nbsp;',
145 indent_amount => 2,
146 newline => "<br />\n",
147 colormap => {
7853a177 148 select => ['<span class="select">' , '</span>'],
149 'insert into' => ['<span class="insert-into">' , '</span>'],
150 update => ['<span class="select">' , '</span>'],
151 'delete from' => ['<span class="delete-from">' , '</span>'],
152 where => ['<span class="where">' , '</span>'],
153 from => ['<span class="from">' , '</span>'],
154 join => ['<span class="join">' , '</span>'],
155 on => ['<span class="on">' , '</span>'],
156 'group by' => ['<span class="group-by">', '</span>'],
157 'order by' => ['<span class="order-by">', '</span>'],
158 set => ['<span class="set">', '</span>'],
159 into => ['<span class="into">', '</span>'],
160 values => ['<span class="values">', '</span>'],
1536de15 161 },
7e5600e9 162 indentmap => { %indents },
75c3a063 163 },
164 none => {
1536de15 165 colormap => {},
166 indentmap => {},
75c3a063 167 },
168);
169
3be357b0 170eval {
171 require Term::ANSIColor;
172 $profiles{console}->{colormap} = {
7853a177 173 select => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
174 'insert into' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
175 update => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
176 'delete from' => [Term::ANSIColor::color('red'), Term::ANSIColor::color('reset')],
177
178 set => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
c1b89c4f 179 from => [Term::ANSIColor::color('cyan'), Term::ANSIColor::color('reset')],
7853a177 180
181 where => [Term::ANSIColor::color('green'), Term::ANSIColor::color('reset')],
182 values => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
183
184 join => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
185 'left join' => [Term::ANSIColor::color('magenta'), Term::ANSIColor::color('reset')],
186 on => [Term::ANSIColor::color('blue'), Term::ANSIColor::color('reset')],
187
188 'group by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
189 'order by' => [Term::ANSIColor::color('yellow'), Term::ANSIColor::color('reset')],
3be357b0 190 };
191};
192
75c3a063 193sub new {
2fed0b4b 194 my $class = shift;
195 my $args = shift || {};
75c3a063 196
197 my $profile = delete $args->{profile} || 'none';
bc482085 198 my $data = $merger->merge( $profiles{$profile}, $args );
75c3a063 199
200 bless $data, $class
201}
d695b0ad 202
01dd4e4f 203sub parse {
d695b0ad 204 my ($self, $s) = @_;
01dd4e4f 205
206 # tokenize string, and remove all optional whitespace
207 my $tokens = [];
208 foreach my $token (split $tokenizer_re, $s) {
209 push @$tokens, $token if (length $token) && ($token =~ /\S/);
210 }
211
d695b0ad 212 my $tree = $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 213 return $tree;
214}
215
216sub _recurse_parse {
d695b0ad 217 my ($self, $tokens, $state) = @_;
01dd4e4f 218
219 my $left;
220 while (1) { # left-associative parsing
221
222 my $lookahead = $tokens->[0];
223 if ( not defined($lookahead)
224 or
225 ($state == PARSE_IN_PARENS && $lookahead eq ')')
226 or
227 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
228 or
229 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
230 ) {
231 return $left;
232 }
233
234 my $token = shift @$tokens;
235
236 # nested expression in ()
237 if ($token eq '(' ) {
d695b0ad 238 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
239 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
240 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 241
242 $left = $left ? [@$left, [PAREN => [$right] ]]
243 : [PAREN => [$right] ];
244 }
245 # AND/OR
246 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
247 my $op = uc $token;
d695b0ad 248 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 249
250 # Merge chunks if logic matches
251 if (ref $right and $op eq $right->[0]) {
252 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
253 }
254 else {
255 $left = [$op => [$left, $right]];
256 }
257 }
258 # binary operator keywords
259 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
260 my $op = uc $token;
d695b0ad 261 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 262
263 # A between with a simple LITERAL for a 1st RHS argument needs a
264 # rerun of the search to (hopefully) find the proper AND construct
265 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
266 unshift @$tokens, $right->[1][0];
d695b0ad 267 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 268 }
269
270 $left = [$op => [$left, $right] ];
271 }
272 # expression terminator keywords (as they start a new expression)
273 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
274 my $op = uc $token;
d695b0ad 275 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 276 $left = $left ? [ $left, [$op => [$right] ]]
277 : [ $op => [$right] ];
278 }
279 # NOT (last as to allow all other NOT X pieces first)
280 elsif ( $token =~ /^ not $/ix ) {
281 my $op = uc $token;
d695b0ad 282 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 283 $left = $left ? [ @$left, [$op => [$right] ]]
284 : [ $op => [$right] ];
285
286 }
287 # literal (eat everything on the right until RHS termination)
288 else {
d695b0ad 289 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
290 $left = $left ? [ $left, [LITERAL => [join ' ', $token, $self->unparse($right)||()] ] ]
291 : [ LITERAL => [join ' ', $token, $self->unparse($right)||()] ];
01dd4e4f 292 }
293 }
294}
295
d695b0ad 296sub format_keyword {
297 my ($self, $keyword) = @_;
298
1536de15 299 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 300 $keyword = "$around->[0]$keyword$around->[1]";
301 }
302
303 return $keyword
304}
305
728f26a2 306my %starters = (
307 select => 1,
308 update => 1,
309 'insert into' => 1,
310 'delete from' => 1,
311);
312
ee4227a7 313sub whitespace_keyword {
a24cc3a0 314 my ($self, $keyword, $depth) = @_;
e171c446 315
316 my $before = '';
1536de15 317 if (defined $self->indentmap->{lc $keyword}) {
318 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 319 }
728f26a2 320 $before = '' if $depth == 0 and defined $starters{lc $keyword};
b4e0e260 321 return [$before, ' '];
a24cc3a0 322}
323
1536de15 324sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 325
a97eb57c 326sub _is_key {
327 my ($self, $tree) = @_;
0569a14f 328 $tree = $tree->[0] while ref $tree;
329
a97eb57c 330 defined $tree && defined $self->indentmap->{lc $tree};
0569a14f 331}
332
fb272e73 333sub _fill_in_placeholder {
334 my ($self, $bindargs) = @_;
335
336 if ($self->fill_in_placeholders) {
637bb22c 337 my $val = pop @{$bindargs} || '';
fb272e73 338 $val =~ s/\\/\\\\/g;
339 $val =~ s/'/\\'/g;
340 return qq('$val')
341 }
342 return '?'
343}
344
01dd4e4f 345sub unparse {
1a3cc911 346 my ($self, $tree, $bindargs, $depth) = @_;
a24cc3a0 347
1a3cc911 348 $depth ||= 0;
01dd4e4f 349
350 if (not $tree ) {
351 return '';
352 }
a24cc3a0 353
354 my $car = $tree->[0];
355 my $cdr = $tree->[1];
356
357 if (ref $car) {
1a3cc911 358 return join ('', map $self->unparse($_, $bindargs, $depth), @$tree);
01dd4e4f 359 }
a24cc3a0 360 elsif ($car eq 'LITERAL') {
fb272e73 361 if ($cdr->[0] eq '?') {
362 return $self->_fill_in_placeholder($bindargs)
363 }
a24cc3a0 364 return $cdr->[0];
01dd4e4f 365 }
a24cc3a0 366 elsif ($car eq 'PAREN') {
e171c446 367 return '(' .
a24cc3a0 368 join(' ',
1a3cc911 369 map $self->unparse($_, $bindargs, $depth + 2), @{$cdr}) .
370 ($self->_is_key($cdr)?( $self->newline||'' ).$self->indent($depth + 1):'') . ') ';
01dd4e4f 371 }
a24cc3a0 372 elsif ($car eq 'OR' or $car eq 'AND' or (grep { $car =~ /^ $_ $/xi } @binary_op_keywords ) ) {
1a3cc911 373 return join (" $car ", map $self->unparse($_, $bindargs, $depth), @{$cdr});
01dd4e4f 374 }
375 else {
ee4227a7 376 my ($l, $r) = @{$self->whitespace_keyword($car, $depth)};
1a3cc911 377 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->unparse($cdr, $bindargs, $depth);
01dd4e4f 378 }
379}
380
fb272e73 381sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
01dd4e4f 382
3831;
384
3be357b0 385=pod
386
387=head1 SYNOPSIS
388
389 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
390
391 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
392
393 # SELECT *
394 # FROM foo
395 # WHERE foo.a > 2
396
6b1bf9f8 397=head1 METHODS
398
399=head2 new
400
401 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
402
c22f502d 403 $args = {
404 profile => 'console', # predefined profile to use (default: 'none')
405 fill_in_placeholders => 1, # true for placeholder population
406 indent_string => ' ', # the string used when indenting
407 indent_amount => 2, # how many of above string to use for a single
408 # indent level
409 newline => "\n", # string for newline
410 colormap => {
411 select => [RED, RESET], # a pair of strings defining what to surround
412 # the keyword with for colorization
413 # ...
414 },
415 indentmap => {
416 select => 0, # A zero means that the keyword will start on
417 # a new line
418 from => 1, # Any other positive integer means that after
419 on => 2, # said newline it will get that many indents
420 # ...
421 },
422 }
423
424Returns a new SQL::Abstract::Tree object. All arguments are optional.
425
426=head3 profiles
427
428There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
429and C<html>. Typically a user will probably just use C<console> or
430C<console_monochrome>, but if something about a profile bothers you, merely
431use the profile and override the parts that you don't like.
432
6b1bf9f8 433=head2 format
434
c22f502d 435 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
436
437Takes C<$sql> and C<\@bindargs>.
6b1bf9f8 438
1a3cc911 439Returns a formatting string based on the string passed in
ee4227a7 440
441=head2 parse
442
443 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
444
445Returns a "tree" representing passed in SQL. Please do not depend on the
446structure of the returned tree. It may be stable at some point, but not yet.
447
448=head2 unparse
449
450 $sqlat->parse($tree_structure, \@bindargs)
451
452Transform "tree" into SQL, applying various transforms on the way.
453
454=head2 format_keyword
455
456 $sqlat->format_keyword('SELECT')
457
458Currently this just takes a keyword and puts the C<colormap> stuff around it.
459Later on it may do more and allow for coderef based transforms.
460
461=head2 whitespace_keyword
462
463 my ($before, $after) = @{$sqlat->whitespace_keyword('SELECT')};
464
465Returns whitespace to be inserted around a keyword.