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