add tests for nested prefetch with many_to_many and chained search_related
[dbsrgits/DBIx-Class.git] / t / 76joins.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 => 62 );
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 # test the abstract join => SQL generator
35 my $sa = new DBIC::SQL::Abstract;
36
37 my @j = (
38     { child => 'person' },
39     [ { father => 'person' }, { 'father.person_id' => 'child.father_id' }, ],
40     [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
41 );
42 my $match = 'person child JOIN person father ON ( father.person_id = '
43           . 'child.father_id ) JOIN person mother ON ( mother.person_id '
44           . '= child.mother_id )'
45           ;
46 is( $sa->_recurse_from(@j), $match, 'join 1 ok' );
47
48 my @j2 = (
49     { mother => 'person' },
50     [   [   { child => 'person' },
51             [   { father             => 'person' },
52                 { 'father.person_id' => 'child.father_id' }
53             ]
54         ],
55         { 'mother.person_id' => 'child.mother_id' }
56     ],
57 );
58 $match = 'person mother JOIN (person child JOIN person father ON ('
59        . ' father.person_id = child.father_id )) ON ( mother.person_id = '
60        . 'child.mother_id )'
61        ;
62 is( $sa->_recurse_from(@j2), $match, 'join 2 ok' );
63
64 my @j3 = (
65     { child => 'person' },
66     [ { father => 'person', -join_type => 'inner' }, { 'father.person_id' => 'child.father_id' }, ],
67     [ { mother => 'person', -join_type => 'inner'  }, { 'mother.person_id' => 'child.mother_id' } ],
68 );
69 $match = 'person child INNER JOIN person father ON ( father.person_id = '
70           . 'child.father_id ) INNER JOIN person mother ON ( mother.person_id '
71           . '= child.mother_id )'
72           ;
73
74 is( $sa->_recurse_from(@j3), $match, 'join 3 (inner join) ok');
75
76 my @j4 = (
77     { mother => 'person' },
78     [   [   { child => 'person', -join_type => 'left' },
79             [   { father             => 'person', -join_type => 'right' },
80                 { 'father.person_id' => 'child.father_id' }
81             ]
82         ],
83         { 'mother.person_id' => 'child.mother_id' }
84     ],
85 );
86 $match = 'person mother LEFT JOIN (person child RIGHT JOIN person father ON ('
87        . ' father.person_id = child.father_id )) ON ( mother.person_id = '
88        . 'child.mother_id )'
89        ;
90 is( $sa->_recurse_from(@j4), $match, 'join 4 (nested joins + join types) ok');
91
92 my @j5 = (
93     { child => 'person' },
94     [ { father => 'person' }, { 'father.person_id' => \'!= child.father_id' }, ],
95     [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
96 );
97 $match = 'person child JOIN person father ON ( father.person_id != '
98           . 'child.father_id ) JOIN person mother ON ( mother.person_id '
99           . '= child.mother_id )'
100           ;
101 is( $sa->_recurse_from(@j5), $match, 'join 5 (SCALAR reference for ON statement) ok' );
102
103 my @j6 = (
104     { child => 'person' },
105     [ { father => 'person' }, { 'father.person_id' => { '!=', '42' } }, ],
106     [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
107 );
108 $match = qr/^HASH reference arguments are not supported in JOINS - try using "\.\.\." instead/;
109 eval { $sa->_recurse_from(@j6) };
110 like( $@, $match, 'join 6 (HASH reference for ON statement dies) ok' );
111
112 my $rs = $schema->resultset("CD")->search(
113            { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
114            { from => [ { 'me' => 'cd' },
115                          [
116                            { artist => 'artist' },
117                            { 'me.artist' => 'artist.artistid' }
118                          ] ] }
119          );
120
121 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
122
123 is($rs->first->title, 'Forkful of bees', 'Correct record returned');
124
125 $rs = $schema->resultset("CD")->search(
126            { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
127            { join => 'artist' });
128
129 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
130
131 is($rs->first->title, 'Forkful of bees', 'Correct record returned');
132
133 $rs = $schema->resultset("CD")->search(
134            { 'artist.name' => 'We Are Goth',
135              'liner_notes.notes' => 'Kill Yourself!' },
136            { join => [ qw/artist liner_notes/ ] });
137
138 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
139
140 is($rs->first->title, 'Come Be Depressed With Us', 'Correct record returned');
141
142 # when using join attribute, make sure slice()ing all objects has same count as all()
143 $rs = $schema->resultset("CD")->search(
144     { 'artist' => 1 },
145     { join => [qw/artist/], order_by => 'artist.name' }
146 );
147 cmp_ok( scalar $rs->all, '==', scalar $rs->slice(0, $rs->count - 1), 'slice() with join has same count as all()' );
148
149 $rs = $schema->resultset("Artist")->search(
150         { 'liner_notes.notes' => 'Kill Yourself!' },
151         { join => { 'cds' => 'liner_notes' } });
152
153 cmp_ok( $rs->count, '==', 1, "Single record in resultset");
154
155 is($rs->first->name, 'We Are Goth', 'Correct record returned');
156
157 # bug in 0.07000 caused attr (join/prefetch) to be modifed by search
158 # so we check the search & attr arrays are not modified
159 my $search = { 'artist.name' => 'Caterwauler McCrae' };
160 my $attr = { prefetch => [ qw/artist liner_notes/ ],
161              order_by => 'me.cdid' };
162 my $search_str = Dumper($search);
163 my $attr_str = Dumper($attr);
164
165 $rs = $schema->resultset("CD")->search($search, $attr);
166
167 is(Dumper($search), $search_str, 'Search hash untouched after search()');
168 is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
169 cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
170
171 my $queries = 0;
172 $schema->storage->debugcb(sub { $queries++ });
173 $schema->storage->debug(1);
174
175 my @cd = $rs->all;
176
177 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
178
179 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
180
181 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
182
183 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
184
185 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
186
187 is($queries, 1, 'prefetch ran only 1 select statement');
188
189 $schema->storage->debug($orig_debug);
190 $schema->storage->debugobj->callback(undef);
191
192 # test for partial prefetch via columns attr
193 my $cd = $schema->resultset('CD')->find(1,
194     {
195       columns => [qw/title artist.name/], 
196       join => { 'artist' => {} }
197     }
198 );
199 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
200
201 # start test for nested prefetch SELECT count
202 $queries = 0;
203 $schema->storage->debugcb(sub { $queries++ });
204 $schema->storage->debug(1);
205
206 $rs = $schema->resultset('Tag')->search(
207   {},
208   {
209     prefetch => { cd => 'artist' }
210   }
211 );
212
213 my $tag = $rs->first;
214
215 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
216
217 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
218
219 # count the SELECTs
220 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
221 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
222
223 $queries = 0;
224
225 is($tag->search_related('cd')->search_related('artist')->first->name,
226    'Caterwauler McCrae',
227    'chained belongs_to->belongs_to search_related ok');
228
229 TODO: {
230   local $TODO = 'use prefetched values for nested search_related';
231
232   is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
233 }
234
235 $queries = 0;
236
237 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
238
239 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
240
241 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
242
243 $queries = 0;
244
245 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
246
247 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
248
249 TODO: {
250   local $TODO = 'use prefetched values for many_to_many accessor';
251
252   is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
253 }
254
255 $queries = 0;
256
257 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
258
259 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
260
261 TODO: {
262   local $TODO = 'use prefetched values for search_related';
263
264   is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
265 }
266
267 $schema->storage->debug($orig_debug);
268 $schema->storage->debugobj->callback(undef);
269
270 $rs = $schema->resultset('Tag')->search(
271   {},
272   {
273     join => { cd => 'artist' },
274     prefetch => { cd => 'artist' }
275   }
276 );
277
278 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
279
280 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
281                  { order_by => 'artistid DESC', join => 'cds' });
282
283 is($artist->name, 'Random Boy Band', "Join search by object ok");
284
285 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
286                                { join => 'liner_notes' });
287
288 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
289
290 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
291
292 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
293                                        { join => { 'cds' => 'tags' } });
294
295 cmp_ok( @artists, '==', 2, "two-join search ok" );
296
297 $rs = $schema->resultset("CD")->search(
298   {},
299   { group_by => [qw/ title me.cdid /] }
300 );
301
302 SKIP: {
303     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
304         if $is_broken_sqlite;
305     cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
306 }
307
308 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
309
310 $rs = $schema->resultset("CD")->search(
311   {},
312   { join => [qw/ artist /], group_by => [qw/ artist.name /] }
313 );
314
315 SKIP: {
316     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
317         if $is_broken_sqlite;
318     cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
319 }
320
321 $rs = $schema->resultset("Artist")->search(
322   {},
323       { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
324 );
325
326 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
327
328 $rs = $rs->search( undef, {  having =>{ 'count(*)'=> \'> 2' }});
329
330 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
331
332 $rs = $schema->resultset("Artist")->search(
333         { 'cds.title' => 'Spoonful of bees',
334           'cds_2.title' => 'Forkful of bees' },
335         { join => [ 'cds', 'cds' ] });
336
337 SKIP: {
338     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
339         if $is_broken_sqlite;
340     cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
341 }
342
343 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
344
345 $queries = 0;
346 $schema->storage->debugcb(sub { $queries++ });
347 $schema->storage->debug(1);
348
349 my $tree_like =
350      $schema->resultset('TreeLike')->find(4,
351        { join     => { parent => { parent => 'parent' } },
352          prefetch => { parent => { parent => 'parent' } } });
353
354 is($tree_like->name, 'quux', 'Bottom of tree ok');
355 $tree_like = $tree_like->parent;
356 is($tree_like->name, 'baz', 'First level up ok');
357 $tree_like = $tree_like->parent;
358 is($tree_like->name, 'bar', 'Second level up ok');
359 $tree_like = $tree_like->parent;
360 is($tree_like->name, 'foo', 'Third level up ok');
361
362 $schema->storage->debug($orig_debug);
363 $schema->storage->debugobj->callback(undef);
364
365 cmp_ok($queries, '==', 1, 'Only one query run');
366
367 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 1});
368 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
369 is($tree_like->name, 'quux', 'Tree search_related ok');
370
371 $tree_like = $schema->resultset('TreeLike')->search_related('children',
372     { 'children.id' => 2, 'children_2.id' => 3 },
373     { prefetch => { children => 'children' } }
374   )->first;
375 is(eval { $tree_like->children->first->children->first->name }, 'quux',
376    'Tree search_related with prefetch ok');
377
378 $tree_like = eval { $schema->resultset('TreeLike')->search(
379     { 'children.id' => 2, 'children_2.id' => 5 }, 
380     { join => [qw/children children/] }
381   )->search_related('children', { 'children_4.id' => 6 }, { prefetch => 'children' }
382   )->first->children->first; };
383 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
384
385 # test that collapsed joins don't get a _2 appended to the alias
386
387 my $sql = '';
388 $schema->storage->debugcb(sub { $sql = $_[1] });
389 $schema->storage->debug(1);
390
391 eval {
392   my $row = $schema->resultset('Artist')->search_related('cds', undef, {
393     join => 'tracks',
394     prefetch => 'tracks',
395   })->search_related('tracks')->first;
396 };
397
398 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
399
400 $schema->storage->debug($orig_debug);
401 $schema->storage->debugobj->callback(undef);
402
403 $rs = $schema->resultset('Artist');
404 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
405 $rs->create({ artistid => 5, name => 'Emo 4ever' });
406 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
407 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
408
409 # -------------
410 #
411 # Tests for multilevel has_many prefetch
412
413 # artist resultsets - with and without prefetch
414 my $art_rs = $schema->resultset('Artist');
415 my $art_rs_pr = $art_rs->search(
416     {},
417     {
418         join     => [ { cds => ['tracks'] } ],
419         prefetch => [ { cds => ['tracks'] } ]
420     }
421 );
422
423 # This test does the same operation twice - once on a
424 # set of items fetched from the db with no prefetch of has_many rels
425 # The second prefetches 2 levels of has_many
426 # We check things are the same by comparing the name or title
427 # we build everything into a hash structure and compare the one
428 # from each rs to see what differs
429
430 sub make_hash_struc {
431     my $rs = shift;
432
433     my $struc = {};
434     foreach my $art ( $rs->all ) {
435         foreach my $cd ( $art->cds ) {
436             foreach my $track ( $cd->tracks ) {
437                 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
438             }
439         }
440     }
441     return $struc;
442 }
443
444 $queries = 0;
445 $schema->storage->debugcb(sub { $queries++ });
446 $schema->storage->debug(1);
447
448 my $prefetch_result = make_hash_struc($art_rs_pr);
449
450 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
451
452 my $nonpre_result   = make_hash_struc($art_rs);
453
454 is_deeply( $prefetch_result, $nonpre_result,
455     'Compare 2 level prefetch result to non-prefetch result' );
456
457 $queries = 0;
458
459 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
460    'Fowlin',
461    'chained has_many->has_many search_related ok'
462   );
463
464 TODO: {
465   local $TODO ='use prefetched values for chained search_related';
466
467   is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
468 }