More author-requires
[dbsrgits/DBIx-Class.git] / t / 77prefetch.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 use Data::Dumper;
9
10 my $schema = DBICTest->init_schema();
11
12 my $orig_debug = $schema->storage->debug;
13
14 use IO::File;
15
16 BEGIN {
17     eval "use DBD::SQLite";
18     plan $@
19         ? ( skip_all => 'needs DBD::SQLite for testing' )
20         : ( tests => 68 );
21 }
22
23 # figure out if we've got a version of sqlite that is older than 3.2.6, in
24 # which case COUNT(DISTINCT()) doesn't work
25 my $is_broken_sqlite = 0;
26 my ($sqlite_major_ver,$sqlite_minor_ver,$sqlite_patch_ver) =
27     split /\./, $schema->storage->dbh->get_info(18);
28 if( $schema->storage->dbh->get_info(17) eq 'SQLite' &&
29     ( ($sqlite_major_ver < 3) ||
30       ($sqlite_major_ver == 3 && $sqlite_minor_ver < 2) ||
31       ($sqlite_major_ver == 3 && $sqlite_minor_ver == 2 && $sqlite_patch_ver < 6) ) ) {
32     $is_broken_sqlite = 1;
33 }
34
35 # bug in 0.07000 caused attr (join/prefetch) to be modifed by search
36 # so we check the search & attr arrays are not modified
37 my $search = { 'artist.name' => 'Caterwauler McCrae' };
38 my $attr = { prefetch => [ qw/artist liner_notes/ ],
39              order_by => 'me.cdid' };
40 my $search_str = Dumper($search);
41 my $attr_str = Dumper($attr);
42
43 my $rs = $schema->resultset("CD")->search($search, $attr);
44
45 is(Dumper($search), $search_str, 'Search hash untouched after search()');
46 is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
47 cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
48
49 # A search() with prefetch seems to pollute an already joined resultset
50 # in a way that offsets future joins (adapted from a test case by Debolaz)
51 {
52   my ($cd_rs, $attrs);
53
54   # test a real-life case - rs is obtained by an implicit m2m join
55   $cd_rs = $schema->resultset ('Producer')->first->cds;
56   $attrs = Dumper $cd_rs->{attrs};
57
58   $cd_rs->search ({})->all;
59   is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
60
61   lives_ok (sub {
62     $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
63     is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after search with prefetch');
64   }, 'first prefetching search ok');
65
66   lives_ok (sub {
67     $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
68     is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after another search with prefetch')
69   }, 'second prefetching search ok');
70
71
72   # test a regular rs with an empty seen_join injected - it should still work!
73   $cd_rs = $schema->resultset ('CD');
74   $cd_rs->{attrs}{seen_join}  = {};
75   $attrs = Dumper $cd_rs->{attrs};
76
77   $cd_rs->search ({})->all;
78   is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
79
80   lives_ok (sub {
81     $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
82     is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after search with prefetch');
83   }, 'first prefetching search ok');
84
85   lives_ok (sub {
86     $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
87     is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after another search with prefetch')
88   }, 'second prefetching search ok');
89 }
90
91
92 my $queries = 0;
93 $schema->storage->debugcb(sub { $queries++; });
94 $schema->storage->debug(1);
95
96 my @cd = $rs->all;
97
98 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
99
100 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
101
102 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
103
104 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
105
106 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
107
108 is($queries, 1, 'prefetch ran only 1 select statement');
109
110 $schema->storage->debug($orig_debug);
111 $schema->storage->debugobj->callback(undef);
112
113 # test for partial prefetch via columns attr
114 my $cd = $schema->resultset('CD')->find(1,
115     {
116       columns => [qw/title artist artist.name/], 
117       join => { 'artist' => {} }
118     }
119 );
120 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
121
122 # start test for nested prefetch SELECT count
123 $queries = 0;
124 $schema->storage->debugcb(sub { $queries++ });
125 $schema->storage->debug(1);
126
127 $rs = $schema->resultset('Tag')->search(
128   {},
129   {
130     prefetch => { cd => 'artist' }
131   }
132 );
133
134 my $tag = $rs->first;
135
136 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
137
138 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
139
140 # count the SELECTs
141 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
142 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
143
144 $queries = 0;
145
146 is($tag->search_related('cd')->search_related('artist')->first->name,
147    'Caterwauler McCrae',
148    'chained belongs_to->belongs_to search_related ok');
149
150 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
151
152 $queries = 0;
153
154 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
155
156 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
157
158 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
159
160 $queries = 0;
161
162 $schema->storage->debugcb(sub { $queries++; });
163
164 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
165
166 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
167
168 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
169
170 $queries = 0;
171
172 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
173
174 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
175
176 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
177
178 $schema->storage->debug($orig_debug);
179 $schema->storage->debugobj->callback(undef);
180
181 $rs = $schema->resultset('Tag')->search(
182   {},
183   {
184     join => { cd => 'artist' },
185     prefetch => { cd => 'artist' }
186   }
187 );
188
189 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
190
191 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
192                  { order_by => 'artistid DESC', join => 'cds' });
193
194 is($artist->name, 'Random Boy Band', "Join search by object ok");
195
196 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
197                                { join => 'liner_notes' });
198
199 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
200
201 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
202
203 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
204                                        { join => { 'cds' => 'tags' } });
205
206 cmp_ok( @artists, '==', 2, "two-join search ok" );
207
208 $rs = $schema->resultset("CD")->search(
209   {},
210   { group_by => [qw/ title me.cdid /] }
211 );
212
213 SKIP: {
214     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
215         if $is_broken_sqlite;
216     cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
217 }
218
219 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
220
221 $rs = $schema->resultset("CD")->search(
222   {},
223   { join => [qw/ artist /], group_by => [qw/ artist.name /] }
224 );
225
226 SKIP: {
227     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
228         if $is_broken_sqlite;
229     cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
230 }
231
232 $rs = $schema->resultset("Artist")->search(
233   {},
234       { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
235 );
236
237 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
238
239 $rs = $rs->search( undef, {  having =>{ 'count(*)'=> \'> 2' }});
240
241 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
242
243 $rs = $schema->resultset("Artist")->search(
244         { 'cds.title' => 'Spoonful of bees',
245           'cds_2.title' => 'Forkful of bees' },
246         { join => [ 'cds', 'cds' ] });
247
248 SKIP: {
249     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
250         if $is_broken_sqlite;
251     cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
252 }
253
254 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
255
256 $cd = $schema->resultset('Artist')->first->create_related('cds',
257     {
258     title   => 'Unproduced Single',
259     year    => 2007
260 });
261
262 my $left_join = $schema->resultset('CD')->search(
263     { 'me.cdid' => $cd->cdid },
264     { prefetch => { cd_to_producer => 'producer' } }
265 );
266
267 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
268
269 $queries = 0;
270 $schema->storage->debugcb(sub { $queries++ });
271 $schema->storage->debug(1);
272
273 my $tree_like =
274      $schema->resultset('TreeLike')->find(5,
275        { join     => { parent => { parent => 'parent' } },
276          prefetch => { parent => { parent => 'parent' } } });
277
278 is($tree_like->name, 'quux', 'Bottom of tree ok');
279 $tree_like = $tree_like->parent;
280 is($tree_like->name, 'baz', 'First level up ok');
281 $tree_like = $tree_like->parent;
282 is($tree_like->name, 'bar', 'Second level up ok');
283 $tree_like = $tree_like->parent;
284 is($tree_like->name, 'foo', 'Third level up ok');
285
286 $schema->storage->debug($orig_debug);
287 $schema->storage->debugobj->callback(undef);
288
289 cmp_ok($queries, '==', 1, 'Only one query run');
290
291 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
292 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
293 is($tree_like->name, 'quux', 'Tree search_related ok');
294
295 $tree_like = $schema->resultset('TreeLike')->search_related('children',
296     { 'children.id' => 3, 'children_2.id' => 4 },
297     { prefetch => { children => 'children' } }
298   )->first;
299 is(eval { $tree_like->children->first->children->first->name }, 'quux',
300    'Tree search_related with prefetch ok');
301
302 $tree_like = eval { $schema->resultset('TreeLike')->search(
303     { 'children.id' => 3, 'children_2.id' => 6 }, 
304     { join => [qw/children children/] }
305   )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
306   )->first->children->first; };
307 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
308
309 # test that collapsed joins don't get a _2 appended to the alias
310
311 my $sql = '';
312 $schema->storage->debugcb(sub { $sql = $_[1] });
313 $schema->storage->debug(1);
314
315 eval {
316   my $row = $schema->resultset('Artist')->search_related('cds', undef, {
317     join => 'tracks',
318     prefetch => 'tracks',
319   })->search_related('tracks')->first;
320 };
321
322 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
323
324 $schema->storage->debug($orig_debug);
325 $schema->storage->debugobj->callback(undef);
326
327 $rs = $schema->resultset('Artist');
328 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
329 $rs->create({ artistid => 5, name => 'Emo 4ever' });
330 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
331 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
332
333 # -------------
334 #
335 # Tests for multilevel has_many prefetch
336
337 # artist resultsets - with and without prefetch
338 my $art_rs = $schema->resultset('Artist');
339 my $art_rs_pr = $art_rs->search(
340     {},
341     {
342         join     => [ { cds => ['tracks'] } ],
343         prefetch => [ { cds => ['tracks'] } ],
344         cache    => 1 # last test needs this
345     }
346 );
347
348 # This test does the same operation twice - once on a
349 # set of items fetched from the db with no prefetch of has_many rels
350 # The second prefetches 2 levels of has_many
351 # We check things are the same by comparing the name or title
352 # we build everything into a hash structure and compare the one
353 # from each rs to see what differs
354
355 sub make_hash_struc {
356     my $rs = shift;
357
358     my $struc = {};
359     foreach my $art ( $rs->all ) {
360         foreach my $cd ( $art->cds ) {
361             foreach my $track ( $cd->tracks ) {
362                 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
363             }
364         }
365     }
366     return $struc;
367 }
368
369 $queries = 0;
370 $schema->storage->debugcb(sub { $queries++ });
371 $schema->storage->debug(1);
372
373 my $prefetch_result = make_hash_struc($art_rs_pr);
374
375 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
376
377 my $nonpre_result   = make_hash_struc($art_rs);
378
379 is_deeply( $prefetch_result, $nonpre_result,
380     'Compare 2 level prefetch result to non-prefetch result' );
381
382 $queries = 0;
383
384 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
385    'Fowlin',
386    'chained has_many->has_many search_related ok'
387   );
388
389 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
390
391 # once the following TODO is complete, remove the 2 warning tests immediately after the TODO block
392 # (the TODO block itself contains tests ensuring that the warns are removed)
393 TODO: {
394     local $TODO = 'Prefetch of multiple has_many rels at the same level (currently warn to protect the clueless git)';
395
396     #( 1 -> M + M )
397     my $cd_rs = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' });
398     my $pr_cd_rs = $cd_rs->search ({}, {
399         prefetch => [qw/tracks tags/],
400     });
401
402     my $tracks_rs = $cd_rs->first->tracks;
403     my $tracks_count = $tracks_rs->count;
404
405     my ($pr_tracks_rs, $pr_tracks_count);
406
407     $queries = 0;
408     $schema->storage->debugcb(sub { $queries++ });
409     $schema->storage->debug(1);
410
411     my $o_mm_warn;
412     {
413         local $SIG{__WARN__} = sub { $o_mm_warn = shift };
414         $pr_tracks_rs = $pr_cd_rs->first->tracks;
415     };
416     $pr_tracks_count = $pr_tracks_rs->count;
417
418     ok(! $o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
419
420     is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
421     is($pr_tracks_count, $tracks_count, 'equal count of prefetched relations over several same level has_many\'s (1 -> M + M)');
422
423     for ($pr_tracks_rs, $tracks_rs) {
424         $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
425     }
426
427     is_deeply ([$pr_tracks_rs->all], [$tracks_rs->all], 'same structure returned with and without prefetch over several same level has_many\'s (1 -> M + M)');
428
429     #( M -> 1 -> M + M )
430     my $note_rs = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' });
431     my $pr_note_rs = $note_rs->search ({}, {
432         prefetch => {
433             cd => [qw/tags tracks/]
434         },
435     });
436
437     my $tags_rs = $note_rs->first->cd->tags;
438     my $tags_count = $tags_rs->count;
439
440     my ($pr_tags_rs, $pr_tags_count);
441
442     $queries = 0;
443     $schema->storage->debugcb(sub { $queries++ });
444     $schema->storage->debug(1);
445
446     my $m_o_mm_warn;
447     {
448         local $SIG{__WARN__} = sub { $m_o_mm_warn = shift };
449         $pr_tags_rs = $pr_note_rs->first->cd->tags;
450     };
451     $pr_tags_count = $pr_tags_rs->count;
452
453     ok(! $m_o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
454
455     is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
456
457     is($pr_tags_count, $tags_count, 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)');
458
459     for ($pr_tags_rs, $tags_rs) {
460         $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
461     }
462
463     is_deeply ([$pr_tags_rs->all], [$tags_rs->all], 'same structure returned with and without prefetch over several same level has_many\'s (M -> 1 -> M + M)');
464 };
465
466 # remove this closure once the TODO above is working
467 my $w;
468 {
469     local $SIG{__WARN__} = sub { $w = shift };
470
471     my $track = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' }, { prefetch => [qw/tracks tags/] })->first->tracks->first;
472     like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
473         'warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
474     my $tag = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' }, { prefetch => { cd => [qw/tags tracks/] } })->first->cd->tags->first;
475     like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
476         'warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
477 }