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