Port 89dbicadmin.t from trunk - now runs on MSWin32 too
[dbsrgits/DBIx-Class.git] / t / 76joins.t
CommitLineData
70350518 1use strict;
2use warnings;
3
4use Test::More;
5use lib qw(t/lib);
6use DBICTest;
cb3e35d2 7use Data::Dumper;
cadd7ab8 8use DBIC::SqlMakerTest;
70350518 9
a47e1233 10my $schema = DBICTest->init_schema();
0567538f 11
4d91ad3f 12my $orig_debug = $schema->storage->debug;
13
0567538f 14use IO::File;
15
16BEGIN {
17 eval "use DBD::SQLite";
18 plan $@
19 ? ( skip_all => 'needs DBD::SQLite for testing' )
2bd9c7c0 20 : ( tests => 64 );
0567538f 21}
22
58ff4acf 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
25my $is_broken_sqlite = 0;
26my ($sqlite_major_ver,$sqlite_minor_ver,$sqlite_patch_ver) =
27 split /\./, $schema->storage->dbh->get_info(18);
28if( $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}
485f6e10 34
0567538f 35# test the abstract join => SQL generator
36my $sa = new DBIC::SQL::Abstract;
37
38my @j = (
39 { child => 'person' },
40 [ { father => 'person' }, { 'father.person_id' => 'child.father_id' }, ],
41 [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
42);
43my $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 ;
cadd7ab8 47ok (eq_sql
48 (
49 $sa->_recurse_from(@j),
50 $match,
51 ),
52 'join 1 ok'
53);
0567538f 54
55my @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 ;
cadd7ab8 69ok (eq_sql
70 (
71 $sa->_recurse_from(@j2),
72 $match,
73 ),
74 'join 2 ok'
75);
76
0567538f 77
78my @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
cadd7ab8 88ok (eq_sql
89 (
90 $sa->_recurse_from(@j3),
91 $match,
92 ),
93 'join 3 (inner join) ok'
94);
0567538f 95
ca7b9fdf 96my @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 ;
cadd7ab8 110ok (eq_sql
111 (
112 $sa->_recurse_from(@j4),
113 $match,
114 ),
115 'join 4 (nested joins + join types) ok'
116);
ca7b9fdf 117
635b9634 118my @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 ;
cadd7ab8 127ok (eq_sql
128 (
129 $sa->_recurse_from(@j5),
130 $match,
131 ),
132 'join 5 (SCALAR reference for ON statement) ok'
133);
635b9634 134
135my @j6 = (
136 { child => 'person' },
137 [ { father => 'person' }, { 'father.person_id' => { '!=', '42' } }, ],
138 [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
139);
11aada86 140$match = qr/^HASH reference arguments are not supported in JOINS - try using "\.\.\." instead/;
635b9634 141eval { $sa->_recurse_from(@j6) };
142like( $@, $match, 'join 6 (HASH reference for ON statement dies) ok' );
143
f9db5527 144my $rs = $schema->resultset("CD")->search(
0567538f 145 { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
146 { from => [ { 'me' => 'cd' },
147 [
148 { artist => 'artist' },
149 { 'me.artist' => 'artist.artistid' }
150 ] ] }
151 );
152
ebaefbc2 153cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
0567538f 154
155is($rs->first->title, 'Forkful of bees', 'Correct record returned');
156
f9db5527 157$rs = $schema->resultset("CD")->search(
0567538f 158 { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
159 { join => 'artist' });
160
ebaefbc2 161cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
0567538f 162
163is($rs->first->title, 'Forkful of bees', 'Correct record returned');
164
f9db5527 165$rs = $schema->resultset("CD")->search(
0567538f 166 { 'artist.name' => 'We Are Goth',
167 'liner_notes.notes' => 'Kill Yourself!' },
168 { join => [ qw/artist liner_notes/ ] });
169
ebaefbc2 170cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
0567538f 171
172is($rs->first->title, 'Come Be Depressed With Us', 'Correct record returned');
173
8fe164b9 174# when using join attribute, make sure slice()ing all objects has same count as all()
f9db5527 175$rs = $schema->resultset("CD")->search(
8fe164b9 176 { 'artist' => 1 },
177 { join => [qw/artist/], order_by => 'artist.name' }
178);
179cmp_ok( scalar $rs->all, '==', scalar $rs->slice(0, $rs->count - 1), 'slice() with join has same count as all()' );
180
2bd9c7c0 181ok(!$rs->slice($rs->count+1000, $rs->count+1002)->count,
182 'Slicing beyond end of rs returns a zero count');
183
f9db5527 184$rs = $schema->resultset("Artist")->search(
0567538f 185 { 'liner_notes.notes' => 'Kill Yourself!' },
186 { join => { 'cds' => 'liner_notes' } });
187
188cmp_ok( $rs->count, '==', 1, "Single record in resultset");
189
190is($rs->first->name, 'We Are Goth', 'Correct record returned');
191
cb3e35d2 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
194my $search = { 'artist.name' => 'Caterwauler McCrae' };
195my $attr = { prefetch => [ qw/artist liner_notes/ ],
196 order_by => 'me.cdid' };
197my $search_str = Dumper($search);
198my $attr_str = Dumper($attr);
199
200$rs = $schema->resultset("CD")->search($search, $attr);
0567538f 201
cb3e35d2 202is(Dumper($search), $search_str, 'Search hash untouched after search()');
203is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
ebaefbc2 204cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
0567538f 205
d52170d4 206my $queries = 0;
9809a6df 207$schema->storage->debugcb(sub { $queries++; });
d52170d4 208$schema->storage->debug(1);
0567538f 209
210my @cd = $rs->all;
211
212is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
213
7cd300ea 214ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
0567538f 215
216is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
217
dd417d06 218is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
219
0567538f 220is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
221
d52170d4 222is($queries, 1, 'prefetch ran only 1 select statement');
223
4d91ad3f 224$schema->storage->debug($orig_debug);
225$schema->storage->debugobj->callback(undef);
0567538f 226
9b465d00 227# test for partial prefetch via columns attr
d20bb28e 228my $cd = $schema->resultset('CD')->find(1,
229 {
9b465d00 230 columns => [qw/title artist.name/],
0e35aa05 231 join => { 'artist' => {} }
d20bb28e 232 }
233);
234ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
235
b3e8ac9b 236# start test for nested prefetch SELECT count
d52170d4 237$queries = 0;
db0e65d2 238$schema->storage->debugcb(sub { $queries++ });
d52170d4 239$schema->storage->debug(1);
b3e8ac9b 240
241$rs = $schema->resultset('Tag')->search(
242 {},
243 {
244 prefetch => { cd => 'artist' }
245 }
246);
247
248my $tag = $rs->first;
249
250is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
251
252is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
253
254# count the SELECTs
d52170d4 255#$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
256is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
b3e8ac9b 257
d52170d4 258$queries = 0;
c5b7d799 259
d54c409f 260is($tag->search_related('cd')->search_related('artist')->first->name,
261 'Caterwauler McCrae',
262 'chained belongs_to->belongs_to search_related ok');
263
9809a6df 264is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
d54c409f 265
266$queries = 0;
267
d20bb28e 268$cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
c5b7d799 269
270is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
271
d52170d4 272is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
273
d54c409f 274$queries = 0;
275
95303b0a 276$schema->storage->debugcb(sub { $queries++; });
9809a6df 277
d54c409f 278$cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
279
280is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
281
0ed8d3b6 282is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
d54c409f 283
284$queries = 0;
285
286my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
287
288is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
289
9809a6df 290is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
d54c409f 291
4d91ad3f 292$schema->storage->debug($orig_debug);
293$schema->storage->debugobj->callback(undef);
c5b7d799 294
b3e8ac9b 295$rs = $schema->resultset('Tag')->search(
296 {},
297 {
298 join => { cd => 'artist' },
299 prefetch => { cd => 'artist' }
300 }
301);
302
303cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
304
f9db5527 305my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
0567538f 306 { order_by => 'artistid DESC', join => 'cds' });
307
308is($artist->name, 'Random Boy Band', "Join search by object ok");
309
f9db5527 310my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
0567538f 311 { join => 'liner_notes' });
312
313cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
314
315is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
316
f9db5527 317my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
0567538f 318 { join => { 'cds' => 'tags' } });
319
320cmp_ok( @artists, '==', 2, "two-join search ok" );
321
15c382be 322$rs = $schema->resultset("CD")->search(
323 {},
324 { group_by => [qw/ title me.cdid /] }
325);
326
485f6e10 327SKIP: {
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}
15c382be 332
333cmp_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
485f6e10 340SKIP: {
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}
15c382be 345
8839560b 346$rs = $schema->resultset("Artist")->search(
6991aba3 347 {},
01c73d7b 348 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
6991aba3 349);
350
8839560b 351cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
6991aba3 352
01c73d7b 353$rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
6991aba3 354
8839560b 355cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
489709af 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
485f6e10 362SKIP: {
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
489709af 368is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
369
d96034a1 370$cd = $schema->resultset('Artist')->first->create_related('cds',
24010dd8 371 {
372 title => 'Unproduced Single',
373 year => 2007
374});
375
376my $left_join = $schema->resultset('CD')->search(
377 { 'me.cdid' => $cd->cdid },
378 { prefetch => { cd_to_producer => 'producer' } }
379);
380
381cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
8206c013 382
d52170d4 383$queries = 0;
db0e65d2 384$schema->storage->debugcb(sub { $queries++ });
887ce227 385$schema->storage->debug(1);
386
387my $tree_like =
388 $schema->resultset('TreeLike')->find(4,
389 { join => { parent => { parent => 'parent' } },
390 prefetch => { parent => { parent => 'parent' } } });
391
392is($tree_like->name, 'quux', 'Bottom of tree ok');
393$tree_like = $tree_like->parent;
394is($tree_like->name, 'baz', 'First level up ok');
395$tree_like = $tree_like->parent;
396is($tree_like->name, 'bar', 'Second level up ok');
397$tree_like = $tree_like->parent;
398is($tree_like->name, 'foo', 'Third level up ok');
399
4d91ad3f 400$schema->storage->debug($orig_debug);
401$schema->storage->debugobj->callback(undef);
887ce227 402
403cmp_ok($queries, '==', 1, 'Only one query run');
404
10ed6c25 405$tree_like = $schema->resultset('TreeLike')->search({'me.id' => 1});
af4cd3e5 406$tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
7e5b5f6e 407is($tree_like->name, 'quux', 'Tree search_related ok');
408
48d2be64 409$tree_like = $schema->resultset('TreeLike')->search_related('children',
410 { 'children.id' => 2, 'children_2.id' => 3 },
411 { prefetch => { children => 'children' } }
412 )->first;
b377c7e1 413is(eval { $tree_like->children->first->children->first->name }, 'quux',
414 'Tree search_related with prefetch ok');
10ed6c25 415
b377c7e1 416$tree_like = eval { $schema->resultset('TreeLike')->search(
10ed6c25 417 { 'children.id' => 2, 'children_2.id' => 5 },
3583d755 418 { join => [qw/children children/] }
9755b3df 419 )->search_related('children', { 'children_4.id' => 6 }, { prefetch => 'children' }
b377c7e1 420 )->first->children->first; };
421is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
10ed6c25 422
7e5b5f6e 423# test that collapsed joins don't get a _2 appended to the alias
424
425my $sql = '';
426$schema->storage->debugcb(sub { $sql = $_[1] });
427$schema->storage->debug(1);
428
429eval {
430 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
431 join => 'tracks',
432 prefetch => 'tracks',
433 })->search_related('tracks')->first;
434};
435
9755b3df 436like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
7e5b5f6e 437
4d91ad3f 438$schema->storage->debug($orig_debug);
439$schema->storage->debugobj->callback(undef);
907d3b9b 440
a08c907f 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' });
445is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
446
907d3b9b 447# -------------
448#
449# Tests for multilevel has_many prefetch
450
451# artist resultsets - with and without prefetch
452my $art_rs = $schema->resultset('Artist');
453my $art_rs_pr = $art_rs->search(
454 {},
455 {
456 join => [ { cds => ['tracks'] } ],
9809a6df 457 prefetch => [ { cds => ['tracks'] } ],
458 cache => 1 # last test needs this
907d3b9b 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
469sub 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
d54c409f 483$queries = 0;
484$schema->storage->debugcb(sub { $queries++ });
485$schema->storage->debug(1);
486
907d3b9b 487my $prefetch_result = make_hash_struc($art_rs_pr);
d54c409f 488
489is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
490
907d3b9b 491my $nonpre_result = make_hash_struc($art_rs);
492
493is_deeply( $prefetch_result, $nonpre_result,
494 'Compare 2 level prefetch result to non-prefetch result' );
d54c409f 495
496$queries = 0;
497
498is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
499 'Fowlin',
500 'chained has_many->has_many search_related ok'
501 );
502
9809a6df 503is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');