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