1 package SQL::Abstract::Test; # see doc at end of file
5 use base qw/Test::Builder::Module Exporter/;
10 our @EXPORT_OK = qw/&is_same_sql_bind &is_same_sql &is_same_bind
11 &eq_sql_bind &eq_sql &eq_bind
12 $case_sensitive $sql_differ/;
14 our $case_sensitive = 0;
15 our $parenthesis_significant = 0;
16 our $sql_differ; # keeps track of differing portion between SQLs
17 our $tb = __PACKAGE__->builder;
19 # Parser states for _recurse_parse()
20 use constant PARSE_TOP_LEVEL => 0;
21 use constant PARSE_IN_EXPR => 1;
22 use constant PARSE_IN_PARENS => 2;
23 use constant PARSE_RHS => 3;
25 # These SQL keywords always signal end of the current expression (except inside
26 # of a parenthesized subexpression).
27 # Format: A list of strings that will be compiled to extended syntax (ie.
28 # /.../x) regexes, without capturing parentheses. They will be automatically
29 # anchored to word boundaries to match the whole token).
30 my @expression_terminator_sql_keywords = (
35 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
36 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
55 # These are binary operator keywords always a single LHS and RHS
56 # * AND/OR are handled separately as they are N-ary
57 # * so is NOT as being unary
58 # * BETWEEN without paranthesis around the ANDed arguments (which
59 # makes it a non-binary op) is detected and accomodated in
61 my $stuff_around_mathops = qr/[\w\s\`\'\"\)]/;
62 my @binary_op_keywords = (
65 ' ^ ' . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
66 " (?<= $stuff_around_mathops)" . quotemeta ($_) . "(?= \$ | $stuff_around_mathops ) ",
68 (qw/< > != <> = <= >=/)
71 { '\b (?: NOT \s+)?' . $_ . '\b' }
76 my $tokenizer_re_str = join("\n\t|\n",
77 ( map { '\b' . $_ . '\b' } @expression_terminator_sql_keywords, 'AND', 'OR', 'NOT'),
81 my $tokenizer_re = qr/ \s* ( $tokenizer_re_str | \( | \) | \? ) \s* /xi;
83 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
84 my @unrollable_ops = (
92 sub is_same_sql_bind {
93 my ($sql1, $bind_ref1, $sql2, $bind_ref2, $msg) = @_;
96 my $same_sql = eq_sql($sql1, $sql2);
97 my $same_bind = eq_bind($bind_ref1, $bind_ref2);
99 # call Test::Builder::ok
100 my $ret = $tb->ok($same_sql && $same_bind, $msg);
104 _sql_differ_diag($sql1, $sql2);
107 _bind_differ_diag($bind_ref1, $bind_ref2);
110 # pass ok() result further
115 my ($sql1, $sql2, $msg) = @_;
118 my $same_sql = eq_sql($sql1, $sql2);
120 # call Test::Builder::ok
121 my $ret = $tb->ok($same_sql, $msg);
125 _sql_differ_diag($sql1, $sql2);
128 # pass ok() result further
133 my ($bind_ref1, $bind_ref2, $msg) = @_;
136 my $same_bind = eq_bind($bind_ref1, $bind_ref2);
138 # call Test::Builder::ok
139 my $ret = $tb->ok($same_bind, $msg);
143 _bind_differ_diag($bind_ref1, $bind_ref2);
146 # pass ok() result further
150 sub _sql_differ_diag {
151 my ($sql1, $sql2) = @_;
153 $tb->diag("SQL expressions differ\n"
156 ."differing in :\n$sql_differ\n"
160 sub _bind_differ_diag {
161 my ($bind_ref1, $bind_ref2) = @_;
163 $tb->diag("BIND values differ\n"
164 ." got: " . Dumper($bind_ref1)
165 ."expected: " . Dumper($bind_ref2)
170 my ($sql1, $bind_ref1, $sql2, $bind_ref2) = @_;
172 return eq_sql($sql1, $sql2) && eq_bind($bind_ref1, $bind_ref2);
177 my ($bind_ref1, $bind_ref2) = @_;
179 local $Data::Dumper::Useqq = 1;
180 local $Data::Dumper::Sortkeys = 1;
182 return Dumper($bind_ref1) eq Dumper($bind_ref2);
186 my ($sql1, $sql2) = @_;
189 my $tree1 = parse($sql1);
190 my $tree2 = parse($sql2);
192 return 1 if _eq_sql($tree1, $tree2);
196 my ($left, $right) = @_;
198 # one is defined the other not
199 if ( (defined $left) xor (defined $right) ) {
202 # one is undefined, then so is the other
203 elsif (not defined $left) {
206 # one is a list, the other is an op with a list
207 elsif (ref $left->[0] xor ref $right->[0]) {
208 $sql_differ = sprintf ("left: %s\nright: %s\n", map { unparse ($_) } ($left, $right) );
211 # one is a list, so is the other
212 elsif (ref $left->[0]) {
213 for (my $i = 0; $i <= $#$left or $i <= $#$right; $i++ ) {
214 return 0 if (not _eq_sql ($left->[$i], $right->[$i]) );
218 # both are an op-list combo
221 # unroll parenthesis if possible/allowed
222 _parenthesis_unroll ($_) for ($left, $right);
224 # if operators are different
225 if ( $left->[0] ne $right->[0] ) {
226 $sql_differ = sprintf "OP [$left->[0]] != [$right->[0]] in\nleft: %s\nright: %s\n",
231 # elsif operators are identical, compare operands
233 if ($left->[0] eq 'LITERAL' ) { # unary
234 (my $l = " $left->[1][0] " ) =~ s/\s+/ /g;
235 (my $r = " $right->[1][0] ") =~ s/\s+/ /g;
236 my $eq = $case_sensitive ? $l eq $r : uc($l) eq uc($r);
237 $sql_differ = "[$l] != [$r]\n" if not $eq;
241 my $eq = _eq_sql($left->[1], $right->[1]);
242 $sql_differ ||= sprintf ("left: %s\nright: %s\n", map { unparse ($_) } ($left, $right) ) if not $eq;
252 # tokenize string, and remove all optional whitespace
254 foreach my $token (split $tokenizer_re, $s) {
255 push @$tokens, $token if (length $token) && ($token =~ /\S/);
258 my $tree = _recurse_parse($tokens, PARSE_TOP_LEVEL);
263 my ($tokens, $state) = @_;
266 while (1) { # left-associative parsing
268 my $lookahead = $tokens->[0];
269 if ( not defined($lookahead)
271 ($state == PARSE_IN_PARENS && $lookahead eq ')')
273 ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords ) )
275 ($state == PARSE_RHS && grep { $lookahead =~ /^ $_ $/xi } ('\)', @expression_terminator_sql_keywords, @binary_op_keywords, 'AND', 'OR', 'NOT' ) )
280 my $token = shift @$tokens;
282 # nested expression in ()
283 if ($token eq '(' ) {
284 my $right = _recurse_parse($tokens, PARSE_IN_PARENS);
285 $token = shift @$tokens or croak "missing closing ')' around block " . unparse ($right);
286 $token eq ')' or croak "unexpected token '$token' terminating block " . unparse ($right);
288 $left = $left ? [@$left, [PAREN => [$right] ]]
289 : [PAREN => [$right] ];
292 elsif ($token =~ /^ (?: OR | AND ) $/xi ) {
294 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
296 # Merge chunks if logic matches
297 if (ref $right and $op eq $right->[0]) {
298 $left = [ (shift @$right ), [$left, map { @$_ } @$right] ];
301 $left = [$op => [$left, $right]];
304 # binary operator keywords
305 elsif (grep { $token =~ /^ $_ $/xi } @binary_op_keywords ) {
307 my $right = _recurse_parse($tokens, PARSE_RHS);
309 # A between with a simple LITERAL for a 1st RHS argument needs a
310 # rerun of the search to (hopefully) find the proper AND construct
311 if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
312 unshift @$tokens, $right->[1][0];
313 $right = _recurse_parse($tokens, PARSE_IN_EXPR);
316 $left = [$op => [$left, $right] ];
318 # expression terminator keywords (as they start a new expression)
319 elsif (grep { $token =~ /^ $_ $/xi } @expression_terminator_sql_keywords ) {
321 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
322 $left = $left ? [ $left, [$op => [$right] ]]
323 : [ $op => [$right] ];
325 # NOT (last as to allow all other NOT X pieces first)
326 elsif ( $token =~ /^ not $/ix ) {
328 my $right = _recurse_parse ($tokens, PARSE_RHS);
329 $left = $left ? [ @$left, [$op => [$right] ]]
330 : [ $op => [$right] ];
333 # literal (eat everything on the right until RHS termination)
335 my $right = _recurse_parse ($tokens, PARSE_RHS);
336 $left = $left ? [ $left, [LITERAL => [join ' ', $token, unparse($right)||()] ] ]
337 : [ LITERAL => [join ' ', $token, unparse($right)||()] ];
342 sub _parenthesis_unroll {
345 return if $parenthesis_significant;
346 return unless (ref $ast and ref $ast->[1]);
353 for my $child (@{$ast->[1]}) {
354 if (not ref $child or not $child->[0] eq 'PAREN') {
355 push @children, $child;
359 # unroll nested parenthesis
360 while ($child->[1][0][0] eq 'PAREN') {
361 $child = $child->[1][0];
365 # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
367 ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
369 $child->[1][0][0] eq $ast->[0]
371 push @children, @{$child->[1][0][1]};
375 # if the parent operator explcitly allows it nuke the parenthesis
376 elsif ( grep { $ast->[0] =~ /^ $_ $/xi } @unrollable_ops ) {
377 push @children, $child->[1][0];
381 # only one LITERAL element in the parenthesis
383 @{$child->[1]} == 1 && $child->[1][0][0] eq 'LITERAL'
385 push @children, $child->[1][0];
389 # only one element in the parenthesis which is a binary op with two LITERAL sub-children
393 grep { $child->[1][0][0] =~ /^ $_ $/xi } (@binary_op_keywords)
395 $child->[1][0][1][0][0] eq 'LITERAL'
397 $child->[1][0][1][1][0] eq 'LITERAL'
399 push @children, $child->[1][0];
403 # otherwise no more mucking for this pass
405 push @children, $child;
409 $ast->[1] = \@children;
421 elsif (ref $tree->[0]) {
422 return join (" ", map { unparse ($_) } @$tree);
424 elsif ($tree->[0] eq 'LITERAL') {
425 return $tree->[1][0];
427 elsif ($tree->[0] eq 'PAREN') {
428 return sprintf '(%s)', join (" ", map {unparse($_)} @{$tree->[1]});
430 elsif ($tree->[0] eq 'OR' or $tree->[0] eq 'AND' or (grep { $tree->[0] =~ /^ $_ $/xi } @binary_op_keywords ) ) {
431 return join (" $tree->[0] ", map {unparse($_)} @{$tree->[1]});
434 return sprintf '%s %s', $tree->[0], unparse ($tree->[1]);
446 SQL::Abstract::Test - Helper function for testing SQL::Abstract
452 use SQL::Abstract::Test import => [qw/
453 is_same_sql_bind is_same_sql is_same_bind
454 eq_sql_bind eq_sql eq_bind
457 my ($sql, @bind) = SQL::Abstract->new->select(%args);
459 is_same_sql_bind($given_sql, \@given_bind,
460 $expected_sql, \@expected_bind, $test_msg);
462 is_same_sql($given_sql, $expected_sql, $test_msg);
463 is_same_bind(\@given_bind, \@expected_bind, $test_msg);
465 my $is_same = eq_sql_bind($given_sql, \@given_bind,
466 $expected_sql, \@expected_bind);
468 my $sql_same = eq_sql($given_sql, $expected_sql);
469 my $bind_same = eq_bind(\@given_bind, \@expected_bind);
473 This module is only intended for authors of tests on
474 L<SQL::Abstract|SQL::Abstract> and related modules;
475 it exports functions for comparing two SQL statements
476 and their bound values.
478 The SQL comparison is performed on I<abstract syntax>,
479 ignoring differences in spaces or in levels of parentheses.
480 Therefore the tests will pass as long as the semantics
481 is preserved, even if the surface syntax has changed.
483 B<Disclaimer> : the semantic equivalence handling is pretty limited.
484 A lot of effort goes into distinguishing significant from
485 non-significant parenthesis, including AND/OR operator associativity.
486 Currently this module does not support commutativity and more
487 intelligent transformations like Morgan laws, etc.
489 For a good overview of what this test framework is capable of refer
494 =head2 is_same_sql_bind
496 is_same_sql_bind($given_sql, \@given_bind,
497 $expected_sql, \@expected_bind, $test_msg);
499 Compares given and expected pairs of C<($sql, \@bind)>, and calls
500 L<Test::Builder/ok> on the result, with C<$test_msg> as message. If the test
501 fails, a detailed diagnostic is printed. For clients which use L<Test::More>,
502 this is the one of the three functions (L</is_same_sql_bind>, L</is_same_sql>,
503 L</is_same_bind>) that needs to be imported.
507 is_same_sql($given_sql, $expected_sql, $test_msg);
509 Compares given and expected SQL statements, and calls L<Test::Builder/ok> on
510 the result, with C<$test_msg> as message. If the test fails, a detailed
511 diagnostic is printed. For clients which use L<Test::More>, this is the one of
512 the three functions (L</is_same_sql_bind>, L</is_same_sql>, L</is_same_bind>)
513 that needs to be imported.
517 is_same_bind(\@given_bind, \@expected_bind, $test_msg);
519 Compares given and expected bind values, and calls L<Test::Builder/ok> on the
520 result, with C<$test_msg> as message. If the test fails, a detailed diagnostic
521 is printed. For clients which use L<Test::More>, this is the one of the three
522 functions (L</is_same_sql_bind>, L</is_same_sql>, L</is_same_bind>) that needs
527 my $is_same = eq_sql_bind($given_sql, \@given_bind,
528 $expected_sql, \@expected_bind);
530 Compares given and expected pairs of C<($sql, \@bind)>. Similar to
531 L</is_same_sql_bind>, but it just returns a boolean value and does not print
532 diagnostics or talk to L<Test::Builder>.
536 my $is_same = eq_sql($given_sql, $expected_sql);
538 Compares the abstract syntax of two SQL statements. Similar to L</is_same_sql>,
539 but it just returns a boolean value and does not print diagnostics or talk to
540 L<Test::Builder>. If the result is false, the global variable L</$sql_differ>
541 will contain the SQL portion where a difference was encountered; this is useful
542 for printing diagnostics.
546 my $is_same = eq_sql(\@given_bind, \@expected_bind);
548 Compares two lists of bind values, taking into account the fact that some of
549 the values may be arrayrefs (see L<SQL::Abstract/bindtype>). Similar to
550 L</is_same_bind>, but it just returns a boolean value and does not print
551 diagnostics or talk to L<Test::Builder>.
553 =head1 GLOBAL VARIABLES
555 =head2 $case_sensitive
557 If true, SQL comparisons will be case-sensitive. Default is false;
559 =head2 $parenthesis_significant
561 If true, SQL comparison will preserve and report difference in nested
562 parenthesis. Useful for testing the C<-nest> modifier. Defaults to false;
566 When L</eq_sql> returns false, the global variable
567 C<$sql_differ> contains the SQL portion
568 where a difference was encountered.
573 L<SQL::Abstract>, L<Test::More>, L<Test::Builder>.
577 Laurent Dami, E<lt>laurent.dami AT etat geneve chE<gt>
579 Norbert Buchmuller <norbi@nix.hu>
581 Peter Rabbitson <ribasushi@cpan.org>
583 =head1 COPYRIGHT AND LICENSE
585 Copyright 2008 by Laurent Dami.
587 This library is free software; you can redistribute it and/or modify
588 it under the same terms as Perl itself.