A new predicate sub: eq_sql_bind
[dbsrgits/SQL-Abstract.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/;
fffe6900 6use Data::Dumper;
7use Carp;
4abea32b 8use Test::Builder;
9use Test::Deep qw(eq_deeply);
fffe6900 10
e7827ba2 11our @EXPORT_OK = qw/&is_same_sql_bind &is_same_sql &is_same_bind
12 &eq_sql_bind &eq_sql &eq_bind
fffe6900 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) {
e7827ba2 83 _sql_differ_diag($sql1, $sql2);
fffe6900 84 }
85 if (!$same_bind) {
e7827ba2 86 _bind_differ_diag($bind_ref1, $bind_ref2);
fffe6900 87 }
88}
89
e7827ba2 90sub is_same_sql {
91 my ($sql1, $sql2, $msg) = @_;
92
93 # compare
94 my $same_sql = eq_sql($sql1, $sql2);
95
96 # call Test::Builder::ok
97 $tb->ok($same_sql, $msg);
98
99 # add debugging info
100 if (!$same_sql) {
101 _sql_differ_diag($sql1, $sql2);
102 }
103}
104
105sub is_same_bind {
106 my ($bind_ref1, $bind_ref2, $msg) = @_;
107
108 # compare
109 my $same_bind = eq_bind($bind_ref1, $bind_ref2);
110
111 # call Test::Builder::ok
112 $tb->ok($same_bind, $msg);
113
114 # add debugging info
115 if (!$same_bind) {
116 _bind_differ_diag($bind_ref1, $bind_ref2);
117 }
118}
119
120sub _sql_differ_diag {
121 my ($sql1, $sql2) = @_;
122
123 $tb->diag("SQL expressions differ\n"
124 ." got: $sql1\n"
125 ."expected: $sql2\n"
126 ."differing in :\n$sql_differ\n"
127 );
128}
129
130sub _bind_differ_diag {
131 my ($bind_ref1, $bind_ref2) = @_;
132
133 $tb->diag("BIND values differ\n"
134 ." got: " . Dumper($bind_ref1)
135 ."expected: " . Dumper($bind_ref2)
136 );
137}
138
139sub eq_sql_bind {
140 my ($sql1, $bind_ref1, $sql2, $bind_ref2) = @_;
141
142 return eq_sql($sql1, $sql2) && eq_bind($bind_ref1, $bind_ref2);
143}
144
145
fffe6900 146sub eq_bind {
147 my ($bind_ref1, $bind_ref2) = @_;
fffe6900 148
4abea32b 149 return eq_deeply($bind_ref1, $bind_ref2);
fffe6900 150}
151
152sub eq_sql {
25823711 153 my ($sql1, $sql2) = @_;
154
155 # parse
156 my $tree1 = parse($sql1);
157 my $tree2 = parse($sql2);
158
159 return _eq_sql($tree1, $tree2);
160}
161
162sub _eq_sql {
fffe6900 163 my ($left, $right) = @_;
164
165 # ignore top-level parentheses
166 while ($left->[0] eq 'PAREN') {$left = $left->[1] }
167 while ($right->[0] eq 'PAREN') {$right = $right->[1]}
168
169 # if operators are different
170 if ($left->[0] ne $right->[0]) {
171 $sql_differ = sprintf "OP [$left->[0]] != [$right->[0]] in\nleft: %s\nright: %s\n",
172 unparse($left),
173 unparse($right);
174 return 0;
175 }
176 # elsif operators are identical, compare operands
177 else {
178 if ($left->[0] eq 'EXPR' ) { # unary operator
179 (my $l = " $left->[1] " ) =~ s/\s+/ /g;
180 (my $r = " $right->[1] ") =~ s/\s+/ /g;
181 my $eq = $case_sensitive ? $l eq $r : uc($l) eq uc($r);
182 $sql_differ = "[$left->[1]] != [$right->[1]]\n" if not $eq;
183 return $eq;
184 }
185 else { # binary operator
25823711 186 return _eq_sql($left->[1][0], $right->[1][0]) # left operand
187 && _eq_sql($left->[1][1], $right->[1][1]); # right operand
fffe6900 188 }
189 }
190}
191
192
193sub parse {
194 my $s = shift;
195
25823711 196 # tokenize string, and remove all optional whitespace
197 my $tokens = [];
198 foreach my $token (split $tokenizer_re, $s) {
199 $token =~ s/\s+/ /g;
200 $token =~ s/\s+([^\w\s])/$1/g;
201 $token =~ s/([^\w\s])\s+/$1/g;
202 push @$tokens, $token if $token !~ /^$/;
203 }
fffe6900 204
25823711 205 my $tree = _recurse_parse($tokens, PARSE_TOP_LEVEL);
fffe6900 206 return $tree;
207}
208
209sub _recurse_parse {
25823711 210 my ($tokens, $state) = @_;
fffe6900 211
212 my $left;
213 while (1) { # left-associative parsing
214
215 my $lookahead = $tokens->[0];
25823711 216 return $left if !defined($lookahead)
217 || ($state == PARSE_IN_PARENS && $lookahead eq ')')
218 || ($state == PARSE_IN_EXPR && grep { $lookahead =~ /^$_$/xi }
219 '\)', @expression_terminator_sql_keywords
220 );
fffe6900 221
222 my $token = shift @$tokens;
223
224 # nested expression in ()
225 if ($token eq '(') {
25823711 226 my $right = _recurse_parse($tokens, PARSE_IN_PARENS);
fffe6900 227 $token = shift @$tokens or croak "missing ')'";
228 $token eq ')' or croak "unexpected token : $token";
229 $left = $left ? [CONCAT => [$left, [PAREN => $right]]]
230 : [PAREN => $right];
231 }
232 # AND/OR
233 elsif ($token eq 'AND' || $token eq 'OR') {
25823711 234 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
fffe6900 235 $left = [$token => [$left, $right]];
236 }
25823711 237 # expression terminator keywords (as they start a new expression)
238 elsif (grep { $token =~ /^$_$/xi } @expression_terminator_sql_keywords) {
239 my $right = _recurse_parse($tokens, PARSE_IN_EXPR);
240 $left = $left ? [CONCAT => [$left, [CONCAT => [[EXPR => $token], [PAREN => $right]]]]]
241 : [CONCAT => [[EXPR => $token], [PAREN => $right]]];
242 }
fffe6900 243 # leaf expression
244 else {
245 $left = $left ? [CONCAT => [$left, [EXPR => $token]]]
246 : [EXPR => $token];
247 }
248 }
249}
250
251
252
253sub unparse {
254 my $tree = shift;
255 my $dispatch = {
256 EXPR => sub {$tree->[1] },
257 PAREN => sub {"(" . unparse($tree->[1]) . ")" },
258 CONCAT => sub {join " ", map {unparse($_)} @{$tree->[1]}},
259 AND => sub {join " AND ", map {unparse($_)} @{$tree->[1]}},
260 OR => sub {join " OR ", map {unparse($_)} @{$tree->[1]}},
261 };
262 $dispatch->{$tree->[0]}->();
263}
264
265
2661;
267
268
269__END__
270
271=head1 NAME
272
273SQL::Abstract::Test - Helper function for testing SQL::Abstract
274
275=head1 SYNOPSIS
276
277 use SQL::Abstract;
278 use Test::More;
e7827ba2 279 use SQL::Abstract::Test import => [qw/
280 is_same_sql_bind is_same_sql is_same_bind
281 eq_sql_bind eq_sql eq_bind
282 /];
fffe6900 283
284 my ($sql, @bind) = SQL::Abstract->new->select(%args);
e7827ba2 285
fffe6900 286 is_same_sql_bind($given_sql, \@given_bind,
287 $expected_sql, \@expected_bind, $test_msg);
288
e7827ba2 289 is_same_sql($given_sql, $expected_sql, $test_msg);
290 is_same_bind(\@given_bind, \@expected_bind, $test_msg);
291
292 my $is_same = eq_sql_bind($given_sql, \@given_bind,
293 $expected_sql, \@expected_bind);
294
295 my $sql_same = eq_sql($given_sql, $expected_sql);
296 my $bind_same = eq_bind(\@given_bind, \@expected_bind);
297
fffe6900 298=head1 DESCRIPTION
299
300This module is only intended for authors of tests on
301L<SQL::Abstract|SQL::Abstract> and related modules;
302it exports functions for comparing two SQL statements
303and their bound values.
304
305The SQL comparison is performed on I<abstract syntax>,
306ignoring differences in spaces or in levels of parentheses.
307Therefore the tests will pass as long as the semantics
308is preserved, even if the surface syntax has changed.
309
310B<Disclaimer> : this is only a half-cooked semantic equivalence;
311parsing is simple-minded, and comparison of SQL abstract syntax trees
312ignores commutativity or associativity of AND/OR operators, Morgan
313laws, etc.
314
315=head1 FUNCTIONS
316
317=head2 is_same_sql_bind
318
319 is_same_sql_bind($given_sql, \@given_bind,
320 $expected_sql, \@expected_bind, $test_msg);
321
322Compares given and expected pairs of C<($sql, \@bind)>, and calls
e7827ba2 323L<Test::Builder/ok> on the result, with C<$test_msg> as message. If the test
324fails, a detailed diagnostic is printed. For clients which use L<Test::More>,
325this is the one of the three functions (L</is_same_sql_bind>, L</is_same_sql>,
326L</is_same_bind>) that needs to be imported.
327
328=head2 is_same_sql
329
330 is_same_sql($given_sql, $expected_sql, $test_msg);
331
332Compares given and expected SQL statements, and calls L<Test::Builder/ok> on
333the result, with C<$test_msg> as message. If the test fails, a detailed
334diagnostic is printed. For clients which use L<Test::More>, this is the one of
335the three functions (L</is_same_sql_bind>, L</is_same_sql>, L</is_same_bind>)
336that needs to be imported.
337
338=head2 is_same_bind
339
340 is_same_bind(\@given_bind, \@expected_bind, $test_msg);
341
342Compares given and expected bind values, and calls L<Test::Builder/ok> on the
343result, with C<$test_msg> as message. If the test fails, a detailed diagnostic
344is printed. For clients which use L<Test::More>, this is the one of the three
345functions (L</is_same_sql_bind>, L</is_same_sql>, L</is_same_bind>) that needs
346to be imported.
347
348=head2 eq_sql_bind
349
350 my $is_same = eq_sql_bind($given_sql, \@given_bind,
351 $expected_sql, \@expected_bind);
352
353Compares given and expected pairs of C<($sql, \@bind)>. Similar to
354L</is_same_sql_bind>, but it just returns a boolean value and does not print
355diagnostics or talk to L<Test::Builder>.
fffe6900 356
357=head2 eq_sql
358
359 my $is_same = eq_sql($given_sql, $expected_sql);
360
e7827ba2 361Compares the abstract syntax of two SQL statements. Similar to L</is_same_sql>,
362but it just returns a boolean value and does not print diagnostics or talk to
363L<Test::Builder>. If the result is false, the global variable L</$sql_differ>
364will contain the SQL portion where a difference was encountered; this is useful
365for printing diagnostics.
fffe6900 366
367=head2 eq_bind
368
369 my $is_same = eq_sql(\@given_bind, \@expected_bind);
370
e7827ba2 371Compares two lists of bind values, taking into account the fact that some of
372the values may be arrayrefs (see L<SQL::Abstract/bindtype>). Similar to
373L</is_same_bind>, but it just returns a boolean value and does not print
374diagnostics or talk to L<Test::Builder>.
fffe6900 375
376=head1 GLOBAL VARIABLES
377
e7827ba2 378=head2 $case_sensitive
fffe6900 379
380If true, SQL comparisons will be case-sensitive. Default is false;
381
e7827ba2 382=head2 $sql_differ
fffe6900 383
384When L</eq_sql> returns false, the global variable
385C<$sql_differ> contains the SQL portion
386where a difference was encountered.
387
388
389=head1 SEE ALSO
390
a6daa642 391L<SQL::Abstract>, L<Test::More>, L<Test::Builder>.
fffe6900 392
25823711 393=head1 AUTHORS
fffe6900 394
395Laurent Dami, E<lt>laurent.dami AT etat geneve chE<gt>
396
25823711 397Norbert Buchmuller <norbi@nix.hu>
398
fffe6900 399=head1 COPYRIGHT AND LICENSE
400
401Copyright 2008 by Laurent Dami.
402
403This library is free software; you can redistribute it and/or modify
404it under the same terms as Perl itself.