Added test for join and empty prefetch exception
[dbsrgits/DBIx-Class.git] / t / prefetch / standard.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8
9 my $schema = DBICTest->init_schema();
10 my $orig_debug = $schema->storage->debug;
11
12 my $queries = 0;
13 $schema->storage->debugcb(sub { $queries++; });
14 $schema->storage->debug(1);
15
16 my $search = { 'artist.name' => 'Caterwauler McCrae' };
17 my $attr = { prefetch => [ qw/artist liner_notes/ ],
18              order_by => 'me.cdid' };
19
20 my $rs = $schema->resultset("CD")->search($search, $attr);
21 my @cd = $rs->all;
22
23 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
24
25 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
26
27 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
28
29 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
30
31 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
32
33 is($queries, 1, 'prefetch ran only 1 select statement');
34
35 $schema->storage->debug($orig_debug);
36 $schema->storage->debugobj->callback(undef);
37
38 # test for partial prefetch via columns attr
39 my $cd = $schema->resultset('CD')->find(1,
40     {
41       columns => [qw/title artist artist.name/],
42       join => { 'artist' => {} }
43     }
44 );
45 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
46
47 # start test for nested prefetch SELECT count
48 $queries = 0;
49 $schema->storage->debugcb(sub { $queries++ });
50 $schema->storage->debug(1);
51
52 $rs = $schema->resultset('Tag')->search(
53   {},
54   {
55     prefetch => { cd => 'artist' }
56   }
57 );
58
59 my $tag = $rs->first;
60
61 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
62
63 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
64
65 # count the SELECTs
66 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
67 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
68
69 $queries = 0;
70
71 is($tag->search_related('cd')->search_related('artist')->first->name,
72    'Caterwauler McCrae',
73    'chained belongs_to->belongs_to search_related ok');
74
75 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
76
77 $queries = 0;
78
79 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
80
81 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
82
83 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
84
85 $queries = 0;
86
87 $schema->storage->debugcb(sub { $queries++; });
88
89 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
90
91 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
92
93 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
94
95 $queries = 0;
96
97 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
98
99 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
100
101 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
102
103 $schema->storage->debug($orig_debug);
104 $schema->storage->debugobj->callback(undef);
105
106 $rs = $schema->resultset('Tag')->search(
107   {},
108   {
109     join => { cd => 'artist' },
110     prefetch => { cd => 'artist' }
111   }
112 );
113
114 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
115
116 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
117                  { order_by => 'artistid DESC', join => 'cds' });
118
119 is($artist->name, 'Random Boy Band', "Join search by object ok");
120
121 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
122                                { join => 'liner_notes' });
123
124 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
125
126 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
127
128 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
129                                        { join => { 'cds' => 'tags' } });
130
131 cmp_ok( @artists, '==', 2, "two-join search ok" );
132
133 $rs = $schema->resultset("CD")->search(
134   {},
135   { group_by => [qw/ title me.cdid /] }
136 );
137
138 cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
139
140 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
141
142 $rs = $schema->resultset("CD")->search(
143   {},
144   { join => [qw/ artist /], group_by => [qw/ artist.name /] }
145 );
146
147 cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
148
149 $rs = $schema->resultset("Artist")->search({}, {
150   join => [qw/ cds /],
151   group_by => [qw/ me.name /],
152   having => \[ 'MAX(cds.cdid) < ?', [ \'int' => 5 ] ],
153 });
154
155 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
156
157 $rs = $rs->search( undef, {  having =>{ 'count(*)'=> \'> 2' }});
158
159 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
160
161 $rs = $schema->resultset("Artist")->search(
162         { 'cds.title' => 'Spoonful of bees',
163           'cds_2.title' => 'Forkful of bees' },
164         { join => [ 'cds', 'cds' ] });
165
166 cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
167
168 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
169
170 $cd = $schema->resultset('Artist')->first->create_related('cds',
171     {
172     title   => 'Unproduced Single',
173     year    => 2007
174 });
175
176 my $left_join = $schema->resultset('CD')->search(
177     { 'me.cdid' => $cd->cdid },
178     { prefetch => { cd_to_producer => 'producer' } }
179 );
180
181 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
182
183 $queries = 0;
184 $schema->storage->debugcb(sub { $queries++ });
185 $schema->storage->debug(1);
186
187 my $tree_like =
188      $schema->resultset('TreeLike')->find(5,
189        { join     => { parent => { parent => 'parent' } },
190          prefetch => { parent => { parent => 'parent' } } });
191
192 is($tree_like->name, 'quux', 'Bottom of tree ok');
193 $tree_like = $tree_like->parent;
194 is($tree_like->name, 'baz', 'First level up ok');
195 $tree_like = $tree_like->parent;
196 is($tree_like->name, 'bar', 'Second level up ok');
197 $tree_like = $tree_like->parent;
198 is($tree_like->name, 'foo', 'Third level up ok');
199
200 $schema->storage->debug($orig_debug);
201 $schema->storage->debugobj->callback(undef);
202
203 cmp_ok($queries, '==', 1, 'Only one query run');
204
205 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
206 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
207 is($tree_like->name, 'quux', 'Tree search_related ok');
208
209 $tree_like = $schema->resultset('TreeLike')->search_related('children',
210     { 'children.id' => 3, 'children_2.id' => 4 },
211     { prefetch => { children => 'children' } }
212   )->first;
213 is(eval { $tree_like->children->first->children->first->name }, 'quux',
214    'Tree search_related with prefetch ok');
215
216 $tree_like = eval { $schema->resultset('TreeLike')->search(
217     { 'children.id' => 3, 'children_2.id' => 6 },
218     { join => [qw/children children children/] }
219   )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
220   )->first->children->first; };
221 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
222
223 $rs = $schema->resultset('Artist');
224 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
225 $rs->create({ artistid => 5, name => 'Emo 4ever' });
226 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
227 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
228
229 lives_ok { @artists = $rs->search(undef, {
230         join => ['cds'],
231         prefetch => [],
232         rows => 20,
233     });
234 } 'join and empty prefetch ok';
235
236 # -------------
237 #
238 # Tests for multilevel has_many prefetch
239
240 # artist resultsets - with and without prefetch
241 my $art_rs = $schema->resultset('Artist');
242 my $art_rs_pr = $art_rs->search(
243     {},
244     {
245         join     => [ { cds => ['tracks'] } ],
246         prefetch => [ { cds => ['tracks'] } ],
247         cache    => 1 # last test needs this
248     }
249 );
250
251 # This test does the same operation twice - once on a
252 # set of items fetched from the db with no prefetch of has_many rels
253 # The second prefetches 2 levels of has_many
254 # We check things are the same by comparing the name or title
255 # we build everything into a hash structure and compare the one
256 # from each rs to see what differs
257
258 sub make_hash_struc {
259     my $rs = shift;
260
261     my $struc = {};
262     # all of these ought to work, but do not for some reason
263     # a noop cloning search() pollution?
264     #foreach my $art ( $rs->search({}, { order_by => 'me.artistid' })->all ) {
265     #foreach my $art ( $rs->search({}, {})->all ) {
266     #foreach my $art ( $rs->search()->all ) {
267     foreach my $art ( $rs->all ) {
268         foreach my $cd ( $art->cds ) {
269             foreach my $track ( $cd->tracks ) {
270                 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
271             }
272         }
273     }
274     return $struc;
275 }
276
277 $queries = 0;
278 $schema->storage->debugcb(sub { $queries++ });
279 $schema->storage->debug(1);
280
281 my $prefetch_result = make_hash_struc($art_rs_pr);
282
283 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
284
285 my $nonpre_result   = make_hash_struc($art_rs);
286
287 is_deeply( $prefetch_result, $nonpre_result,
288     'Compare 2 level prefetch result to non-prefetch result' );
289
290 $queries = 0;
291
292 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
293    'Fowlin',
294    'chained has_many->has_many search_related ok'
295   );
296
297 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
298
299 $schema->storage->debug($orig_debug);
300 $schema->storage->debugobj->callback(undef);
301
302 done_testing;