Deduplicate (and stabilize) the result of _collapse_cond
[dbsrgits/DBIx-Class.git] / t / search / stack_cond.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use lib qw(t/lib);
6 use DBICTest ':DiffSQL';
7 use SQL::Abstract qw(is_plain_value is_literal_value);
8 use List::Util 'shuffle';
9 use Data::Dumper;
10 $Data::Dumper::Terse = 1;
11 $Data::Dumper::Useqq = 1;
12 $Data::Dumper::Indent = 0;
13
14 my $schema = DBICTest->init_schema();
15
16 for my $c (
17   { cond => undef, sql => 'IS NULL' },
18   { cond => { -value => undef }, sql => 'IS NULL' },
19   { cond => \'foo', sql => '= foo' },
20   { cond => 'foo', sql => '= ?', bind => [
21     [ { dbic_colname => "title", sqlt_datatype => "varchar", sqlt_size => 100 } => 'foo' ],
22     [ { dbic_colname => "year", sqlt_datatype => "varchar", sqlt_size => 100 } => 'foo' ],
23   ]},
24   { cond => { -value => 'foo' }, sql => '= ?', bind => [
25     [ { dbic_colname => "title", sqlt_datatype => "varchar", sqlt_size => 100 } => 'foo' ],
26     [ { dbic_colname => "year", sqlt_datatype => "varchar", sqlt_size => 100 } => 'foo' ],
27   ]},
28   { cond => \[ '?', "foo" ], sql => '= ?', bind => [
29     [ {} => 'foo' ],
30     [ {} => 'foo' ],
31   ]},
32 ) {
33   my $rs = $schema->resultset('CD')->search({}, { columns => 'title' });
34
35   my $bare_cond = is_literal_value($c->{cond}) ? { '=', $c->{cond} } : $c->{cond};
36
37   my @query_steps = (
38     # this is a monkey-wrench, always there
39     { title => { '!=', [ -and => \'bar' ] }, year => { '!=', [ -and => 'bar' ] } },
40
41     { title => $bare_cond, year => { '=', $c->{cond} } },
42     { -and => [ year => $bare_cond, { title => { '=', $c->{cond} } } ] },
43     [ year => $bare_cond ],
44     [ title => $bare_cond ],
45     { -and => [ { year => { '=', $c->{cond} } }, { title => { '=', $c->{cond} } } ] },
46     { -and => { -or => { year => { '=', $c->{cond} } } }, -or => { title => $bare_cond } },
47   );
48
49   if (my $v = is_plain_value($c->{cond})) {
50     push @query_steps,
51       { year => $v->[0] },
52       { title => $v->[0] },
53       { -and => [ year => $v->[0], title => $v->[0] ] },
54     ;
55   }
56
57   @query_steps = shuffle @query_steps;
58
59   $rs = $rs->search($_) for @query_steps;
60
61   my @bind = @{$c->{bind} || []};
62   {
63     no warnings 'misc';
64     splice @bind, 1, 0, [ { dbic_colname => "year", sqlt_datatype => "varchar", sqlt_size => 100 } => 'bar' ];
65   }
66
67   is_same_sql_bind (
68     $rs->as_query,
69     "(
70       SELECT me.title
71         FROM cd me
72       WHERE title != bar AND title $c->{sql} AND year != ? AND year $c->{sql}
73     )",
74     \@bind,
75     'Double condition correctly collapsed for steps' . Dumper \@query_steps,
76   );
77 }
78
79 done_testing;