8 use DBIC::SqlMakerTest;
10 my $schema = DBICTest->init_schema();
12 my $orig_debug = $schema->storage->debug;
17 eval "use DBD::SQLite";
19 ? ( skip_all => 'needs DBD::SQLite for testing' )
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;
35 # test the abstract join => SQL generator
36 my $sa = new DBIC::SQL::Abstract;
39 { child => 'person' },
40 [ { father => 'person' }, { 'father.person_id' => 'child.father_id' }, ],
41 [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
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 )'
49 $sa->_recurse_from(@j),
56 { mother => 'person' },
57 [ [ { child => 'person' },
58 [ { father => 'person' },
59 { 'father.person_id' => 'child.father_id' }
62 { 'mother.person_id' => 'child.mother_id' }
65 $match = 'person mother JOIN (person child JOIN person father ON ('
66 . ' father.person_id = child.father_id )) ON ( mother.person_id = '
71 $sa->_recurse_from(@j2),
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' } ],
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 )'
90 $sa->_recurse_from(@j3),
93 'join 3 (inner join) ok'
97 { mother => 'person' },
98 [ [ { child => 'person', -join_type => 'left' },
99 [ { father => 'person', -join_type => 'right' },
100 { 'father.person_id' => 'child.father_id' }
103 { 'mother.person_id' => 'child.mother_id' }
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 )'
112 $sa->_recurse_from(@j4),
115 'join 4 (nested joins + join types) ok'
119 { child => 'person' },
120 [ { father => 'person' }, { 'father.person_id' => \'!= child.father_id' }, ],
121 [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
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 )'
129 $sa->_recurse_from(@j5),
132 'join 5 (SCALAR reference for ON statement) ok'
136 { child => 'person' },
137 [ { father => 'person' }, { 'father.person_id' => { '!=', '42' } }, ],
138 [ { mother => 'person' }, { 'mother.person_id' => 'child.mother_id' } ],
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' );
144 my $rs = $schema->resultset("CD")->search(
145 { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
146 { from => [ { 'me' => 'cd' },
148 { artist => 'artist' },
149 { 'me.artist' => 'artist.artistid' }
153 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
155 is($rs->first->title, 'Forkful of bees', 'Correct record returned');
157 $rs = $schema->resultset("CD")->search(
158 { 'year' => 2001, 'artist.name' => 'Caterwauler McCrae' },
159 { join => 'artist' });
161 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
163 is($rs->first->title, 'Forkful of bees', 'Correct record returned');
165 $rs = $schema->resultset("CD")->search(
166 { 'artist.name' => 'We Are Goth',
167 'liner_notes.notes' => 'Kill Yourself!' },
168 { join => [ qw/artist liner_notes/ ] });
170 cmp_ok( $rs + 0, '==', 1, "Single record in resultset");
172 is($rs->first->title, 'Come Be Depressed With Us', 'Correct record returned');
174 # when using join attribute, make sure slice()ing all objects has same count as all()
175 $rs = $schema->resultset("CD")->search(
177 { join => [qw/artist/], order_by => 'artist.name' }
179 cmp_ok( scalar $rs->all, '==', scalar $rs->slice(0, $rs->count - 1), 'slice() with join has same count as all()' );
181 ok(!$rs->slice($rs->count+1000, $rs->count+1002)->count,
182 'Slicing beyond end of rs returns a zero count');
184 $rs = $schema->resultset("Artist")->search(
185 { 'liner_notes.notes' => 'Kill Yourself!' },
186 { join => { 'cds' => 'liner_notes' } });
188 cmp_ok( $rs->count, '==', 1, "Single record in resultset");
190 is($rs->first->name, 'We Are Goth', 'Correct record returned');
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);
200 $rs = $schema->resultset("CD")->search($search, $attr);
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');
207 $schema->storage->debugcb(sub { $queries++; });
208 $schema->storage->debug(1);
212 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
214 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
216 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
218 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
220 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
222 is($queries, 1, 'prefetch ran only 1 select statement');
224 $schema->storage->debug($orig_debug);
225 $schema->storage->debugobj->callback(undef);
227 # test for partial prefetch via columns attr
228 my $cd = $schema->resultset('CD')->find(1,
230 columns => [qw/title artist.name/],
231 join => { 'artist' => {} }
234 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
236 # start test for nested prefetch SELECT count
238 $schema->storage->debugcb(sub { $queries++ });
239 $schema->storage->debug(1);
241 $rs = $schema->resultset('Tag')->search(
244 prefetch => { cd => 'artist' }
248 my $tag = $rs->first;
250 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
252 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
255 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
256 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
260 is($tag->search_related('cd')->search_related('artist')->first->name,
261 'Caterwauler McCrae',
262 'chained belongs_to->belongs_to search_related ok');
264 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
268 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
270 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
272 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
276 $schema->storage->debugcb(sub { $queries++; });
278 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
280 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
282 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
286 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
288 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
290 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
292 $schema->storage->debug($orig_debug);
293 $schema->storage->debugobj->callback(undef);
295 $rs = $schema->resultset('Tag')->search(
298 join => { cd => 'artist' },
299 prefetch => { cd => 'artist' }
303 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
305 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
306 { order_by => 'artistid DESC', join => 'cds' });
308 is($artist->name, 'Random Boy Band', "Join search by object ok");
310 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
311 { join => 'liner_notes' });
313 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
315 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
317 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
318 { join => { 'cds' => 'tags' } });
320 cmp_ok( @artists, '==', 2, "two-join search ok" );
322 $rs = $schema->resultset("CD")->search(
324 { group_by => [qw/ title me.cdid /] }
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" );
333 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
335 $rs = $schema->resultset("CD")->search(
337 { join => [qw/ artist /], group_by => [qw/ artist.name /] }
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" );
346 $rs = $schema->resultset("Artist")->search(
348 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
351 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
353 $rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
355 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
357 $rs = $schema->resultset("Artist")->search(
358 { 'cds.title' => 'Spoonful of bees',
359 'cds_2.title' => 'Forkful of bees' },
360 { join => [ 'cds', 'cds' ] });
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");
368 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
370 $cd = $schema->resultset('Artist')->first->create_related('cds',
372 title => 'Unproduced Single',
376 my $left_join = $schema->resultset('CD')->search(
377 { 'me.cdid' => $cd->cdid },
378 { prefetch => { cd_to_producer => 'producer' } }
381 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
384 $schema->storage->debugcb(sub { $queries++ });
385 $schema->storage->debug(1);
388 $schema->resultset('TreeLike')->find(4,
389 { join => { parent => { parent => 'parent' } },
390 prefetch => { parent => { parent => 'parent' } } });
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');
400 $schema->storage->debug($orig_debug);
401 $schema->storage->debugobj->callback(undef);
403 cmp_ok($queries, '==', 1, 'Only one query run');
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');
409 $tree_like = $schema->resultset('TreeLike')->search_related('children',
410 { 'children.id' => 2, 'children_2.id' => 3 },
411 { prefetch => { children => 'children' } }
413 is(eval { $tree_like->children->first->children->first->name }, 'quux',
414 'Tree search_related with prefetch ok');
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');
423 # test that collapsed joins don't get a _2 appended to the alias
426 $schema->storage->debugcb(sub { $sql = $_[1] });
427 $schema->storage->debug(1);
430 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
432 prefetch => 'tracks',
433 })->search_related('tracks')->first;
436 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
438 $schema->storage->debug($orig_debug);
439 $schema->storage->debugobj->callback(undef);
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');
449 # Tests for multilevel has_many prefetch
451 # artist resultsets - with and without prefetch
452 my $art_rs = $schema->resultset('Artist');
453 my $art_rs_pr = $art_rs->search(
456 join => [ { cds => ['tracks'] } ],
457 prefetch => [ { cds => ['tracks'] } ],
458 cache => 1 # last test needs this
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
469 sub make_hash_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 }++;
484 $schema->storage->debugcb(sub { $queries++ });
485 $schema->storage->debug(1);
487 my $prefetch_result = make_hash_struc($art_rs_pr);
489 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
491 my $nonpre_result = make_hash_struc($art_rs);
493 is_deeply( $prefetch_result, $nonpre_result,
494 'Compare 2 level prefetch result to non-prefetch result' );
498 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
500 'chained has_many->has_many search_related ok'
503 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');