Hide bulk inserts from DBIx::Class
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
CommitLineData
01dd4e4f 1package SQL::Abstract::Tree;
2
3use strict;
4use warnings;
b3b79607 5no warnings 'qw';
01dd4e4f 6use Carp;
7
0769ac0e 8use Hash::Merge qw//;
9
10use base 'Class::Accessor::Grouped';
11
12__PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
13 newline indent_string indent_amount colormap indentmap fill_in_placeholders
14 placeholder_surround
15);
2fed0b4b 16
bc482085 17my $merger = Hash::Merge->new;
18
19$merger->specify_behavior({
2fed0b4b 20 SCALAR => {
21 SCALAR => sub { $_[1] },
22 ARRAY => sub { [ $_[0], @{$_[1]} ] },
23 HASH => sub { $_[1] },
24 },
25 ARRAY => {
26 SCALAR => sub { $_[1] },
27 ARRAY => sub { $_[1] },
28 HASH => sub { $_[1] },
29 },
30 HASH => {
31 SCALAR => sub { $_[1] },
32 ARRAY => sub { [ values %{$_[0]}, @{$_[1]} ] },
33 HASH => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
34 },
0769ac0e 35}, 'SQLA::Tree Behavior' );
1536de15 36
0769ac0e 37my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
b3b79607 38my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
39
0769ac0e 40my $quote_left = qr/[\`\'\"\[]/;
41my $quote_right = qr/[\`\'\"\]]/;
01dd4e4f 42
4e914a7c 43my $placeholder_re = qr/(?: \? | \$\d+ )/x;
44
01dd4e4f 45# These SQL keywords always signal end of the current expression (except inside
46# of a parenthesized subexpression).
0769ac0e 47# Format: A list of strings that will be compiled to extended syntax ie.
01dd4e4f 48# /.../x) regexes, without capturing parentheses. They will be automatically
0769ac0e 49# anchored to op boundaries (excluding quotes) to match the whole token.
50my @expression_start_keywords = (
01dd4e4f 51 'SELECT',
7853a177 52 'UPDATE',
53 'INSERT \s+ INTO',
54 'DELETE \s+ FROM',
3d910890 55 'FROM',
7853a177 56 'SET',
01dd4e4f 57 '(?:
58 (?:
0769ac0e 59 (?: (?: LEFT | RIGHT | FULL ) \s+ )?
60 (?: (?: CROSS | INNER | OUTER ) \s+ )?
01dd4e4f 61 )?
62 JOIN
63 )',
64 'ON',
65 'WHERE',
efc991a0 66 '(?: DEFAULT \s+ )? VALUES',
01dd4e4f 67 'EXISTS',
68 'GROUP \s+ BY',
69 'HAVING',
70 'ORDER \s+ BY',
c0eaa9fd 71 'SKIP',
72 'FIRST',
01dd4e4f 73 'LIMIT',
74 'OFFSET',
75 'FOR',
76 'UNION',
77 'INTERSECT',
78 'EXCEPT',
79 'RETURNING',
8d0dd7dc 80 'ROW_NUMBER \s* \( \s* \) \s+ OVER',
01dd4e4f 81);
82
b3b79607 83my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
84$expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
0769ac0e 85
01dd4e4f 86# These are binary operator keywords always a single LHS and RHS
87# * AND/OR are handled separately as they are N-ary
88# * so is NOT as being unary
89# * BETWEEN without paranthesis around the ANDed arguments (which
90# makes it a non-binary op) is detected and accomodated in
91# _recurse_parse()
01dd4e4f 92
0769ac0e 93# this will be included in the $binary_op_re, the distinction is interesting during
94# testing as one is tighter than the other, plus mathops have different look
95# ahead/behind (e.g. "x"="y" )
96my @math_op_keywords = (qw/ < > != <> = <= >= /);
97my $math_re = join ("\n\t|\n", map
98 { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )" . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
99 @math_op_keywords
01dd4e4f 100);
b7b0f832 101$math_re = qr/$math_re/x;
0769ac0e 102
103sub _math_op_re { $math_re }
104
105
106my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
b3b79607 107$binary_op_re = join "\n\t|\n",
108 "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
109 $math_re,
110 $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
111;
b7b0f832 112$binary_op_re = qr/$binary_op_re/x;
0769ac0e 113
114sub _binary_op_re { $binary_op_re }
115
b3b79607 116my $all_known_re = join("\n\t|\n",
117 $expr_start_re,
0769ac0e 118 $binary_op_re,
119 "$op_look_behind (?i: AND|OR|NOT ) $op_look_ahead",
b3b79607 120 (map { quotemeta $_ } qw/, ( ) */),
4e914a7c 121 $placeholder_re,
0769ac0e 122);
01dd4e4f 123
b3b79607 124$all_known_re = qr/$all_known_re/x;
125
126#this one *is* capturing for the split below
127# splits on whitespace if all else fails
128my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
129
130# Parser states for _recurse_parse()
131use constant PARSE_TOP_LEVEL => 0;
132use constant PARSE_IN_EXPR => 1;
133use constant PARSE_IN_PARENS => 2;
134use constant PARSE_IN_FUNC => 3;
135use constant PARSE_RHS => 4;
136
137my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
138my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
4e914a7c 139my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
01dd4e4f 140
7e5600e9 141my %indents = (
7853a177 142 select => 0,
143 update => 0,
144 'insert into' => 0,
145 'delete from' => 0,
3d910890 146 from => 1,
91916220 147 where => 0,
7853a177 148 join => 1,
149 'left join' => 1,
150 on => 2,
91916220 151 'group by' => 0,
152 'order by' => 0,
7853a177 153 set => 1,
154 into => 1,
91916220 155 values => 1,
c0eaa9fd 156 limit => 1,
157 offset => 1,
158 skip => 1,
159 first => 1,
7e5600e9 160);
161
75c3a063 162my %profiles = (
163 console => {
84c65032 164 fill_in_placeholders => 1,
9d11f0d4 165 placeholder_surround => ['?/', ''],
1536de15 166 indent_string => ' ',
75c3a063 167 indent_amount => 2,
1536de15 168 newline => "\n",
3be357b0 169 colormap => {},
7e5600e9 170 indentmap => { %indents },
aafbf833 171
172 eval { require Term::ANSIColor }
173 ? do {
174 my $c = \&Term::ANSIColor::color;
175 (
09931431 176 placeholder_surround => [q(') . $c->('black on_magenta'), $c->('reset') . q(')],
aafbf833 177 colormap => {
178 select => [$c->('red'), $c->('reset')],
179 'insert into' => [$c->('red'), $c->('reset')],
180 update => [$c->('red'), $c->('reset')],
181 'delete from' => [$c->('red'), $c->('reset')],
182
183 set => [$c->('cyan'), $c->('reset')],
184 from => [$c->('cyan'), $c->('reset')],
185
186 where => [$c->('green'), $c->('reset')],
187 values => [$c->('yellow'), $c->('reset')],
188
189 join => [$c->('magenta'), $c->('reset')],
190 'left join' => [$c->('magenta'), $c->('reset')],
191 on => [$c->('blue'), $c->('reset')],
192
193 'group by' => [$c->('yellow'), $c->('reset')],
194 'order by' => [$c->('yellow'), $c->('reset')],
c0eaa9fd 195
196 skip => [$c->('green'), $c->('reset')],
197 first => [$c->('green'), $c->('reset')],
198 limit => [$c->('green'), $c->('reset')],
199 offset => [$c->('green'), $c->('reset')],
aafbf833 200 }
201 );
202 } : (),
3be357b0 203 },
204 console_monochrome => {
84c65032 205 fill_in_placeholders => 1,
9d11f0d4 206 placeholder_surround => ['?/', ''],
3be357b0 207 indent_string => ' ',
208 indent_amount => 2,
209 newline => "\n",
210 colormap => {},
7e5600e9 211 indentmap => { %indents },
212 },
213 html => {
84c65032 214 fill_in_placeholders => 1,
9d11f0d4 215 placeholder_surround => ['<span class="placeholder">', '</span>'],
7e5600e9 216 indent_string => '&nbsp;',
217 indent_amount => 2,
218 newline => "<br />\n",
219 colormap => {
7853a177 220 select => ['<span class="select">' , '</span>'],
221 'insert into' => ['<span class="insert-into">' , '</span>'],
222 update => ['<span class="select">' , '</span>'],
223 'delete from' => ['<span class="delete-from">' , '</span>'],
c0eaa9fd 224
225 set => ['<span class="set">', '</span>'],
7853a177 226 from => ['<span class="from">' , '</span>'],
c0eaa9fd 227
228 where => ['<span class="where">' , '</span>'],
229 values => ['<span class="values">', '</span>'],
230
7853a177 231 join => ['<span class="join">' , '</span>'],
c0eaa9fd 232 'left join' => ['<span class="left-join">','</span>'],
7853a177 233 on => ['<span class="on">' , '</span>'],
c0eaa9fd 234
7853a177 235 'group by' => ['<span class="group-by">', '</span>'],
236 'order by' => ['<span class="order-by">', '</span>'],
c0eaa9fd 237
238 skip => ['<span class="skip">', '</span>'],
239 first => ['<span class="first">', '</span>'],
240 limit => ['<span class="limit">', '</span>'],
241 offset => ['<span class="offset">', '</span>'],
1536de15 242 },
7e5600e9 243 indentmap => { %indents },
75c3a063 244 },
245 none => {
1536de15 246 colormap => {},
247 indentmap => {},
75c3a063 248 },
249);
250
251sub new {
2fed0b4b 252 my $class = shift;
253 my $args = shift || {};
75c3a063 254
255 my $profile = delete $args->{profile} || 'none';
bc482085 256 my $data = $merger->merge( $profiles{$profile}, $args );
75c3a063 257
258 bless $data, $class
259}
d695b0ad 260
01dd4e4f 261sub parse {
d695b0ad 262 my ($self, $s) = @_;
01dd4e4f 263
264 # tokenize string, and remove all optional whitespace
265 my $tokens = [];
266 foreach my $token (split $tokenizer_re, $s) {
b3b79607 267 push @$tokens, $token if (
268 defined $token
269 and
270 length $token
09931431 271 and
b3b79607 272 $token =~ /\S/
273 );
01dd4e4f 274 }
b3b79607 275 $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
01dd4e4f 276}
277
278sub _recurse_parse {
d695b0ad 279 my ($self, $tokens, $state) = @_;
01dd4e4f 280
281 my $left;
282 while (1) { # left-associative parsing
283
284 my $lookahead = $tokens->[0];
285 if ( not defined($lookahead)
286 or
287 ($state == PARSE_IN_PARENS && $lookahead eq ')')
288 or
b3b79607 289 ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
0769ac0e 290 or
b3b79607 291 ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
01dd4e4f 292 or
b3b79607 293 ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
01dd4e4f 294 ) {
0769ac0e 295 return $left||();
01dd4e4f 296 }
297
298 my $token = shift @$tokens;
299
300 # nested expression in ()
301 if ($token eq '(' ) {
d695b0ad 302 my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
303 $token = shift @$tokens or croak "missing closing ')' around block " . $self->unparse($right);
304 $token eq ')' or croak "unexpected token '$token' terminating block " . $self->unparse($right);
01dd4e4f 305
0769ac0e 306 $left = $left ? [$left, [PAREN => [$right||()] ]]
307 : [PAREN => [$right||()] ];
01dd4e4f 308 }
b3b79607 309 # AND/OR and LIST (,)
310 elsif ($token =~ /^ (?: OR | AND | \, ) $/xi ) {
311 my $op = ($token eq ',') ? 'LIST' : uc $token;
312
d695b0ad 313 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 314
315 # Merge chunks if logic matches
316 if (ref $right and $op eq $right->[0]) {
b3b79607 317 $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
01dd4e4f 318 }
319 else {
b3b79607 320 $left = [$op => [ $left||(), $right||() ]];
01dd4e4f 321 }
322 }
323 # binary operator keywords
a1e204f4 324 elsif ( $token =~ /^ $binary_op_re $ /x ) {
01dd4e4f 325 my $op = uc $token;
d695b0ad 326 my $right = $self->_recurse_parse($tokens, PARSE_RHS);
01dd4e4f 327
328 # A between with a simple LITERAL for a 1st RHS argument needs a
329 # rerun of the search to (hopefully) find the proper AND construct
330 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
331 unshift @$tokens, $right->[1][0];
d695b0ad 332 $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
01dd4e4f 333 }
334
335 $left = [$op => [$left, $right] ];
336 }
337 # expression terminator keywords (as they start a new expression)
b3b79607 338 elsif ( $token =~ / ^ $expr_start_re $ /x ) {
01dd4e4f 339 my $op = uc $token;
d695b0ad 340 my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
efc991a0 341 $left = $left ? [ $left, [$op => [$right||()] ]]
342 : [ $op => [$right||()] ];
01dd4e4f 343 }
0769ac0e 344 # NOT
345 elsif ( $token =~ /^ NOT $/ix ) {
01dd4e4f 346 my $op = uc $token;
d695b0ad 347 my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
01dd4e4f 348 $left = $left ? [ @$left, [$op => [$right] ]]
349 : [ $op => [$right] ];
350
351 }
4e914a7c 352 elsif ( $token =~ $placeholder_re) {
353 $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
354 : [ PLACEHOLDER => [ $token ] ];
355 }
b3b79607 356 # we're now in "unknown token" land - start eating tokens until
357 # we see something familiar
01dd4e4f 358 else {
b3b79607 359 my $right;
360
361 # check if the current token is an unknown op-start
362 if (@$tokens and $tokens->[0] =~ $func_start_re) {
363 $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
364 }
365 else {
366 $right = [ LITERAL => [ $token ] ];
367 }
368
369 $left = $left ? [ $left, $right ]
370 : $right;
01dd4e4f 371 }
372 }
373}
374
d695b0ad 375sub format_keyword {
376 my ($self, $keyword) = @_;
377
1536de15 378 if (my $around = $self->colormap->{lc $keyword}) {
d695b0ad 379 $keyword = "$around->[0]$keyword$around->[1]";
380 }
381
382 return $keyword
383}
384
728f26a2 385my %starters = (
386 select => 1,
387 update => 1,
388 'insert into' => 1,
389 'delete from' => 1,
390);
391
f2ab166a 392sub pad_keyword {
a24cc3a0 393 my ($self, $keyword, $depth) = @_;
e171c446 394
395 my $before = '';
1536de15 396 if (defined $self->indentmap->{lc $keyword}) {
397 $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
a24cc3a0 398 }
728f26a2 399 $before = '' if $depth == 0 and defined $starters{lc $keyword};
e4570c8e 400 return [$before, ''];
a24cc3a0 401}
402
1536de15 403sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
a24cc3a0 404
a97eb57c 405sub _is_key {
406 my ($self, $tree) = @_;
0569a14f 407 $tree = $tree->[0] while ref $tree;
408
a97eb57c 409 defined $tree && defined $self->indentmap->{lc $tree};
0569a14f 410}
411
9d11f0d4 412sub fill_in_placeholder {
fb272e73 413 my ($self, $bindargs) = @_;
414
415 if ($self->fill_in_placeholders) {
ad46269d 416 my $val = shift @{$bindargs} || '';
9d11f0d4 417 my ($left, $right) = @{$self->placeholder_surround};
fb272e73 418 $val =~ s/\\/\\\\/g;
419 $val =~ s/'/\\'/g;
ad46269d 420 return qq($left$val$right)
fb272e73 421 }
422 return '?'
423}
424
3a247d23 425# FIXME - terrible name for a user facing API
01dd4e4f 426sub unparse {
3a247d23 427 my ($self, $tree, $bindargs) = @_;
428 $self->_unparse($tree, [@{$bindargs||[]}], 0);
429}
a24cc3a0 430
3a247d23 431sub _unparse {
432 my ($self, $tree, $bindargs, $depth) = @_;
01dd4e4f 433
0769ac0e 434 if (not $tree or not @$tree) {
01dd4e4f 435 return '';
436 }
a24cc3a0 437
0769ac0e 438 my ($car, $cdr) = @{$tree}[0,1];
439
440 if (! defined $car or (! ref $car and ! defined $cdr) ) {
441 require Data::Dumper;
442 Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
443 Data::Dumper::Dumper($tree)
444 ) );
445 }
a24cc3a0 446
447 if (ref $car) {
3a247d23 448 return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
01dd4e4f 449 }
a24cc3a0 450 elsif ($car eq 'LITERAL') {
451 return $cdr->[0];
01dd4e4f 452 }
4e914a7c 453 elsif ($car eq 'PLACEHOLDER') {
454 return $self->fill_in_placeholder($bindargs);
455 }
a24cc3a0 456 elsif ($car eq 'PAREN') {
e4570c8e 457 return sprintf ('(%s)',
458 join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
459 .
460 ($self->_is_key($cdr)
461 ? ( $self->newline||'' ) . $self->indent($depth + 1)
462 : ''
463 )
464 );
01dd4e4f 465 }
0769ac0e 466 elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
3a247d23 467 return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
01dd4e4f 468 }
b3b79607 469 elsif ($car eq 'LIST' ) {
3a247d23 470 return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
b3b79607 471 }
01dd4e4f 472 else {
f2ab166a 473 my ($l, $r) = @{$self->pad_keyword($car, $depth)};
3a247d23 474 return sprintf "$l%s %s$r", $self->format_keyword($car), $self->_unparse($cdr, $bindargs, $depth);
01dd4e4f 475 }
476}
477
fb272e73 478sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
01dd4e4f 479
4801;
481
3be357b0 482=pod
483
484=head1 SYNOPSIS
485
486 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
487
488 print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
489
490 # SELECT *
491 # FROM foo
492 # WHERE foo.a > 2
493
6b1bf9f8 494=head1 METHODS
495
496=head2 new
497
498 my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
499
c22f502d 500 $args = {
501 profile => 'console', # predefined profile to use (default: 'none')
502 fill_in_placeholders => 1, # true for placeholder population
9d11f0d4 503 placeholder_surround => # The strings that will be wrapped around
504 [GREEN, RESET], # populated placeholders if the above is set
c22f502d 505 indent_string => ' ', # the string used when indenting
506 indent_amount => 2, # how many of above string to use for a single
507 # indent level
508 newline => "\n", # string for newline
509 colormap => {
510 select => [RED, RESET], # a pair of strings defining what to surround
511 # the keyword with for colorization
512 # ...
513 },
514 indentmap => {
515 select => 0, # A zero means that the keyword will start on
516 # a new line
517 from => 1, # Any other positive integer means that after
518 on => 2, # said newline it will get that many indents
519 # ...
520 },
521 }
522
523Returns a new SQL::Abstract::Tree object. All arguments are optional.
524
525=head3 profiles
526
527There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
528and C<html>. Typically a user will probably just use C<console> or
529C<console_monochrome>, but if something about a profile bothers you, merely
530use the profile and override the parts that you don't like.
531
6b1bf9f8 532=head2 format
533
c22f502d 534 $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
535
536Takes C<$sql> and C<\@bindargs>.
6b1bf9f8 537
1a3cc911 538Returns a formatting string based on the string passed in
ee4227a7 539
540=head2 parse
541
542 $sqlat->parse('SELECT * FROM bar WHERE x = ?')
543
544Returns a "tree" representing passed in SQL. Please do not depend on the
545structure of the returned tree. It may be stable at some point, but not yet.
546
547=head2 unparse
548
549 $sqlat->parse($tree_structure, \@bindargs)
550
551Transform "tree" into SQL, applying various transforms on the way.
552
553=head2 format_keyword
554
555 $sqlat->format_keyword('SELECT')
556
557Currently this just takes a keyword and puts the C<colormap> stuff around it.
558Later on it may do more and allow for coderef based transforms.
559
f2ab166a 560=head2 pad_keyword
ee4227a7 561
f2ab166a 562 my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
ee4227a7 563
564Returns whitespace to be inserted around a keyword.
9d11f0d4 565
566=head2 fill_in_placeholder
567
568 my $value = $sqlat->fill_in_placeholder(\@bindargs)
569
570Removes last arg from passed arrayref and returns it, surrounded with
571the values in placeholder_surround, and then surrounded with single quotes.
f2ab166a 572
573=head2 indent
574
575Returns as many indent strings as indent amounts times the first argument.
576
577=head1 ACCESSORS
578
579=head2 colormap
580
581See L</new>
582
583=head2 fill_in_placeholders
584
585See L</new>
586
587=head2 indent_amount
588
589See L</new>
590
591=head2 indent_string
592
593See L</new>
594
595=head2 indentmap
596
597See L</new>
598
599=head2 newline
600
601See L</new>
602
603=head2 placeholder_surround
604
605See L</new>
606