Merged changes from the '1.50_RC-extraparens' branch.
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Test.pm
CommitLineData
fffe6900 1package SQL::Abstract::Test; # see doc at end of file
2
3use strict;
4use warnings;
5aad8cf3 5use base qw/Test::Builder::Module Exporter/;
32c34379 6use Scalar::Util qw(looks_like_number blessed reftype);
fffe6900 7use Data::Dumper;
8use Carp;
4abea32b 9use Test::Builder;
10use Test::Deep qw(eq_deeply);
fffe6900 11
12our @EXPORT_OK = qw/&is_same_sql_bind &eq_sql &eq_bind
13 $case_sensitive $sql_differ/;
14
15our $case_sensitive = 0;
16our $sql_differ; # keeps track of differing portion between SQLs
5aad8cf3 17our $tb = __PACKAGE__->builder;
fffe6900 18
25823711 19# Parser states for _recurse_parse()
20use constant {
21 PARSE_TOP_LEVEL => 0,
22 PARSE_IN_EXPR => 1,
23 PARSE_IN_PARENS => 2,
24};
25
26# These SQL keywords always signal end of the current expression (except inside
27# of a parenthesized subexpression).
28# Format: A list of strings that will be compiled to extended syntax (ie.
29# /.../x) regexes, without capturing parentheses. They will be automatically
30# anchored to word boundaries to match the whole token).
31my @expression_terminator_sql_keywords = (
32 'FROM',
33 '(?:
34 (?:
35 (?: \b (?: LEFT | RIGHT | FULL ) \s+ )?
36 (?: \b (?: CROSS | INNER | OUTER ) \s+ )?
37 )?
38 JOIN
39 )',
40 'ON',
41 'WHERE',
42 'GROUP \s+ BY',
43 'HAVING',
44 'ORDER \s+ BY',
45 'LIMIT',
46 'OFFSET',
47 'FOR',
48 'UNION',
49 'INTERSECT',
50 'EXCEPT',
51);
52
53my $tokenizer_re_str = join('|',
54 map { '\b' . $_ . '\b' }
55 @expression_terminator_sql_keywords, 'AND', 'OR'
56);
57
58my $tokenizer_re = qr/
59 \s*
60 (
61 \(
62 |
63 \)
64 |
65 $tokenizer_re_str
66 )
67 \s*
68/xi;
69
70
fffe6900 71sub is_same_sql_bind {
72 my ($sql1, $bind_ref1, $sql2, $bind_ref2, $msg) = @_;
73
74 # compare
25823711 75 my $same_sql = eq_sql($sql1, $sql2);
fffe6900 76 my $same_bind = eq_bind($bind_ref1, $bind_ref2);
77
a6daa642 78 # call Test::Builder::ok
5aad8cf3 79 $tb->ok($same_sql && $same_bind, $msg);
fffe6900 80
81 # add debugging info
82 if (!$same_sql) {
5aad8cf3 83 $tb->diag("SQL expressions differ\n"
fffe6900 84 ." got: $sql1\n"
85 ."expected: $sql2\n"
5aad8cf3 86 ."differing in :\n$sql_differ\n"
87 );
fffe6900 88 }
89 if (!$same_bind) {
5aad8cf3 90 $tb->diag("BIND values differ\n"
fffe6900 91 ." got: " . Dumper($bind_ref1)
92 ."expected: " . Dumper($bind_ref2)
5aad8cf3 93 );
fffe6900 94 }
95}
96
fffe6900 97sub eq_bind {
98 my ($bind_ref1, $bind_ref2) = @_;
fffe6900 99
4abea32b 100 return eq_deeply($bind_ref1, $bind_ref2);
fffe6900 101}
102
103sub eq_sql {
25823711 104 my ($sql1, $sql2) = @_;
105
106 # parse
107 my $tree1 = parse($sql1);
108 my $tree2 = parse($sql2);
109
110 return _eq_sql($tree1, $tree2);
111}
112
113sub _eq_sql {
fffe6900 114 my ($left, $right) = @_;
115
116 # ignore top-level parentheses
117 while ($left->[0] eq 'PAREN') {$left = $left->[1] }
118 while ($right->[0] eq 'PAREN') {$right = $right->[1]}
119
120 # if operators are different
121 if ($left->[0] ne $right->[0]) {
122 $sql_differ = sprintf "OP [$left->[0]] != [$right->[0]] in\nleft: %s\nright: %s\n",
123 unparse($left),
124 unparse($right);
125 return 0;
126 }
127 # elsif operators are identical, compare operands
128 else {
129 if ($left->[0] eq 'EXPR' ) { # unary operator
130 (my $l = " $left->[1] " ) =~ s/\s+/ /g;
131 (my $r = " $right->[1] ") =~ s/\s+/ /g;
132 my $eq = $case_sensitive ? $l eq $r : uc($l) eq uc($r);
133 $sql_differ = "[$left->[1]] != [$right->[1]]\n" if not $eq;
134 return $eq;
135 }
136 else { # binary operator
25823711 137 return _eq_sql($left->[1][0], $right->[1][0]) # left operand
138 && _eq_sql($left->[1][1], $right->[1][1]); # right operand
fffe6900 139 }
140 }
141}
142
143
144sub parse {
145 my $s = shift;
146
25823711 147 # tokenize string, and remove all optional whitespace
148 my $tokens = [];
149 foreach my $token (split $tokenizer_re, $s) {
150 $token =~ s/\s+/ /g;
151 $token =~ s/\s+([^\w\s])/$1/g;
152 $token =~ s/([^\w\s])\s+/$1/g;
153 push @$tokens, $token if $token !~ /^$/;
154 }
fffe6900 155
25823711 156 my $tree = _recurse_parse($tokens, PARSE_TOP_LEVEL);
fffe6900 157 return $tree;
158}
159
160sub _recurse_parse {
25823711 161 my ($tokens, $state) = @_;
fffe6900 162
163 my $left;
164 while (1) { # left-associative parsing
165
166 my $lookahead = $tokens->[0];
25823711 167 return $left if !defined($lookahead)
168 || ($state == PARSE_IN_PARENS && $lookahead eq ')')
169 || ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^$_$/xi }
170 '\)', @expression_terminator_sql_keywords
171 );
fffe6900 172
173 my $token = shift @$tokens;
174
175 # nested expression in ()
176 if ($token eq '(') {
25823711 177 my $right = _recurse_parse($tokens, PARSE_IN_PARENS);
fffe6900 178 $token = shift @$tokens or croak "missing ')'";
179 $token eq ')' or croak "unexpected token : $token";
180 $left = $left ? [CONCAT => [$left, [PAREN => $right]]]
181 : [PAREN => $right];
182 }
183 # AND/OR
184 elsif ($token eq 'AND' || $token eq 'OR') {
25823711 185 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
fffe6900 186 $left = [$token => [$left, $right]];
187 }
25823711 188 # expression terminator keywords (as they start a new expression)
189 elsif (grep { $token =~ /^$_$/xi } @expression_terminator_sql_keywords) {
190 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
191 $left = $left ? [CONCAT => [$left, [CONCAT => [[EXPR => $token], [PAREN => $right]]]]]
192 : [CONCAT => [[EXPR => $token], [PAREN => $right]]];
193 }
fffe6900 194 # leaf expression
195 else {
196 $left = $left ? [CONCAT => [$left, [EXPR => $token]]]
197 : [EXPR => $token];
198 }
199 }
200}
201
202
203
204sub unparse {
205 my $tree = shift;
206 my $dispatch = {
207 EXPR => sub {$tree->[1] },
208 PAREN => sub {"(" . unparse($tree->[1]) . ")" },
209 CONCAT => sub {join " ", map {unparse($_)} @{$tree->[1]}},
210 AND => sub {join " AND ", map {unparse($_)} @{$tree->[1]}},
211 OR => sub {join " OR ", map {unparse($_)} @{$tree->[1]}},
212 };
213 $dispatch->{$tree->[0]}->();
214}
215
216
2171;
218
219
220__END__
221
222=head1 NAME
223
224SQL::Abstract::Test - Helper function for testing SQL::Abstract
225
226=head1 SYNOPSIS
227
228 use SQL::Abstract;
229 use Test::More;
5aad8cf3 230 use SQL::Abstract::Test import => ['is_same_sql_bind'];
fffe6900 231
232 my ($sql, @bind) = SQL::Abstract->new->select(%args);
233 is_same_sql_bind($given_sql, \@given_bind,
234 $expected_sql, \@expected_bind, $test_msg);
235
236=head1 DESCRIPTION
237
238This module is only intended for authors of tests on
239L<SQL::Abstract|SQL::Abstract> and related modules;
240it exports functions for comparing two SQL statements
241and their bound values.
242
243The SQL comparison is performed on I<abstract syntax>,
244ignoring differences in spaces or in levels of parentheses.
245Therefore the tests will pass as long as the semantics
246is preserved, even if the surface syntax has changed.
247
248B<Disclaimer> : this is only a half-cooked semantic equivalence;
249parsing is simple-minded, and comparison of SQL abstract syntax trees
250ignores commutativity or associativity of AND/OR operators, Morgan
251laws, etc.
252
253=head1 FUNCTIONS
254
255=head2 is_same_sql_bind
256
257 is_same_sql_bind($given_sql, \@given_bind,
258 $expected_sql, \@expected_bind, $test_msg);
259
260Compares given and expected pairs of C<($sql, \@bind)>, and calls
a6daa642 261L<Test::Builder/ok> on the result, with C<$test_msg> as message. If the
fffe6900 262test fails, a detailed diagnostic is printed. For clients which use
a6daa642 263L<Test::Build>, this is the only function that needs to be
fffe6900 264imported.
265
266=head2 eq_sql
267
268 my $is_same = eq_sql($given_sql, $expected_sql);
269
270Compares the abstract syntax of two SQL statements. If the result is
271false, global variable L</sql_differ> will contain the SQL portion
272where a difference was encountered; this is useful for printing diagnostics.
273
274=head2 eq_bind
275
276 my $is_same = eq_sql(\@given_bind, \@expected_bind);
277
278Compares two lists of bind values, taking into account
279the fact that some of the values may be
280arrayrefs (see L<SQL::Abstract/bindtype>).
281
282=head1 GLOBAL VARIABLES
283
284=head2 case_sensitive
285
286If true, SQL comparisons will be case-sensitive. Default is false;
287
288=head2 sql_differ
289
290When L</eq_sql> returns false, the global variable
291C<$sql_differ> contains the SQL portion
292where a difference was encountered.
293
294
295=head1 SEE ALSO
296
a6daa642 297L<SQL::Abstract>, L<Test::More>, L<Test::Builder>.
fffe6900 298
25823711 299=head1 AUTHORS
fffe6900 300
301Laurent Dami, E<lt>laurent.dami AT etat geneve chE<gt>
302
25823711 303Norbert Buchmuller <norbi@nix.hu>
304
fffe6900 305=head1 COPYRIGHT AND LICENSE
306
307Copyright 2008 by Laurent Dami.
308
309This library is free software; you can redistribute it and/or modify
310it under the same terms as Perl itself.