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 # bug in 0.07000 caused attr (join/prefetch) to be modifed by search
36 # so we check the search & attr arrays are not modified
37 my $search = { 'artist.name' => 'Caterwauler McCrae' };
38 my $attr = { prefetch => [ qw/artist liner_notes/ ],
39 order_by => 'me.cdid' };
40 my $search_str = Dumper($search);
41 my $attr_str = Dumper($attr);
43 my $rs = $schema->resultset("CD")->search($search, $attr);
45 is(Dumper($search), $search_str, 'Search hash untouched after search()');
46 is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
47 cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
49 # A search() with prefetch seems to pollute an already joined resultset
50 # in a way that offsets future joins (adapted from a test case by Debolaz)
52 my $cd_rs = $schema->resultset ('Producer')->first->cds;
53 my $attrs = Dumper $cd_rs->{attrs};
55 $cd_rs->search ({})->all;
56 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
59 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
60 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after search with prefetch');
61 }, 'first prefetching search ok');
64 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
65 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after another search with prefetch')
66 }, 'second prefetching search ok');
71 $schema->storage->debugcb(sub { $queries++; });
72 $schema->storage->debug(1);
76 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
78 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
80 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
82 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
84 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
86 is($queries, 1, 'prefetch ran only 1 select statement');
88 $schema->storage->debug($orig_debug);
89 $schema->storage->debugobj->callback(undef);
91 # test for partial prefetch via columns attr
92 my $cd = $schema->resultset('CD')->find(1,
94 columns => [qw/title artist artist.name/],
95 join => { 'artist' => {} }
98 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
100 # start test for nested prefetch SELECT count
102 $schema->storage->debugcb(sub { $queries++ });
103 $schema->storage->debug(1);
105 $rs = $schema->resultset('Tag')->search(
108 prefetch => { cd => 'artist' }
112 my $tag = $rs->first;
114 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
116 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
119 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
120 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
124 is($tag->search_related('cd')->search_related('artist')->first->name,
125 'Caterwauler McCrae',
126 'chained belongs_to->belongs_to search_related ok');
128 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
132 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
134 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
136 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
140 $schema->storage->debugcb(sub { $queries++; });
142 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
144 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
146 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
150 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
152 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
154 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
156 $schema->storage->debug($orig_debug);
157 $schema->storage->debugobj->callback(undef);
159 $rs = $schema->resultset('Tag')->search(
162 join => { cd => 'artist' },
163 prefetch => { cd => 'artist' }
167 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
169 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
170 { order_by => 'artistid DESC', join => 'cds' });
172 is($artist->name, 'Random Boy Band', "Join search by object ok");
174 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
175 { join => 'liner_notes' });
177 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
179 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
181 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
182 { join => { 'cds' => 'tags' } });
184 cmp_ok( @artists, '==', 2, "two-join search ok" );
186 $rs = $schema->resultset("CD")->search(
188 { group_by => [qw/ title me.cdid /] }
192 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
193 if $is_broken_sqlite;
194 cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
197 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
199 $rs = $schema->resultset("CD")->search(
201 { join => [qw/ artist /], group_by => [qw/ artist.name /] }
205 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
206 if $is_broken_sqlite;
207 cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
210 $rs = $schema->resultset("Artist")->search(
212 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
215 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
217 $rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
219 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
221 $rs = $schema->resultset("Artist")->search(
222 { 'cds.title' => 'Spoonful of bees',
223 'cds_2.title' => 'Forkful of bees' },
224 { join => [ 'cds', 'cds' ] });
227 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
228 if $is_broken_sqlite;
229 cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
232 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
234 $cd = $schema->resultset('Artist')->first->create_related('cds',
236 title => 'Unproduced Single',
240 my $left_join = $schema->resultset('CD')->search(
241 { 'me.cdid' => $cd->cdid },
242 { prefetch => { cd_to_producer => 'producer' } }
245 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
248 $schema->storage->debugcb(sub { $queries++ });
249 $schema->storage->debug(1);
252 $schema->resultset('TreeLike')->find(5,
253 { join => { parent => { parent => 'parent' } },
254 prefetch => { parent => { parent => 'parent' } } });
256 is($tree_like->name, 'quux', 'Bottom of tree ok');
257 $tree_like = $tree_like->parent;
258 is($tree_like->name, 'baz', 'First level up ok');
259 $tree_like = $tree_like->parent;
260 is($tree_like->name, 'bar', 'Second level up ok');
261 $tree_like = $tree_like->parent;
262 is($tree_like->name, 'foo', 'Third level up ok');
264 $schema->storage->debug($orig_debug);
265 $schema->storage->debugobj->callback(undef);
267 cmp_ok($queries, '==', 1, 'Only one query run');
269 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
270 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
271 is($tree_like->name, 'quux', 'Tree search_related ok');
273 $tree_like = $schema->resultset('TreeLike')->search_related('children',
274 { 'children.id' => 3, 'children_2.id' => 4 },
275 { prefetch => { children => 'children' } }
277 is(eval { $tree_like->children->first->children->first->name }, 'quux',
278 'Tree search_related with prefetch ok');
280 $tree_like = eval { $schema->resultset('TreeLike')->search(
281 { 'children.id' => 3, 'children_2.id' => 6 },
282 { join => [qw/children children/] }
283 )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
284 )->first->children->first; };
285 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
287 # test that collapsed joins don't get a _2 appended to the alias
290 $schema->storage->debugcb(sub { $sql = $_[1] });
291 $schema->storage->debug(1);
294 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
296 prefetch => 'tracks',
297 })->search_related('tracks')->first;
300 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
302 $schema->storage->debug($orig_debug);
303 $schema->storage->debugobj->callback(undef);
305 $rs = $schema->resultset('Artist');
306 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
307 $rs->create({ artistid => 5, name => 'Emo 4ever' });
308 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
309 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
313 # Tests for multilevel has_many prefetch
315 # artist resultsets - with and without prefetch
316 my $art_rs = $schema->resultset('Artist');
317 my $art_rs_pr = $art_rs->search(
320 join => [ { cds => ['tracks'] } ],
321 prefetch => [ { cds => ['tracks'] } ],
322 cache => 1 # last test needs this
326 # This test does the same operation twice - once on a
327 # set of items fetched from the db with no prefetch of has_many rels
328 # The second prefetches 2 levels of has_many
329 # We check things are the same by comparing the name or title
330 # we build everything into a hash structure and compare the one
331 # from each rs to see what differs
333 sub make_hash_struc {
337 foreach my $art ( $rs->all ) {
338 foreach my $cd ( $art->cds ) {
339 foreach my $track ( $cd->tracks ) {
340 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
348 $schema->storage->debugcb(sub { $queries++ });
349 $schema->storage->debug(1);
351 my $prefetch_result = make_hash_struc($art_rs_pr);
353 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
355 my $nonpre_result = make_hash_struc($art_rs);
357 is_deeply( $prefetch_result, $nonpre_result,
358 'Compare 2 level prefetch result to non-prefetch result' );
362 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
364 'chained has_many->has_many search_related ok'
367 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
369 # once the following TODO is complete, remove the 2 warning tests immediately after the TODO block
370 # (the TODO block itself contains tests ensuring that the warns are removed)
372 local $TODO = 'Prefetch of multiple has_many rels at the same level (currently warn to protect the clueless git)';
375 my $cd_rs = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' });
376 my $pr_cd_rs = $cd_rs->search ({}, {
377 prefetch => [qw/tracks tags/],
380 my $tracks_rs = $cd_rs->first->tracks;
381 my $tracks_count = $tracks_rs->count;
383 my ($pr_tracks_rs, $pr_tracks_count);
386 $schema->storage->debugcb(sub { $queries++ });
387 $schema->storage->debug(1);
391 local $SIG{__WARN__} = sub { $o_mm_warn = shift };
392 $pr_tracks_rs = $pr_cd_rs->first->tracks;
394 $pr_tracks_count = $pr_tracks_rs->count;
396 ok(! $o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
398 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
399 is($pr_tracks_count, $tracks_count, 'equal count of prefetched relations over several same level has_many\'s (1 -> M + M)');
401 for ($pr_tracks_rs, $tracks_rs) {
402 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
405 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)');
408 my $note_rs = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' });
409 my $pr_note_rs = $note_rs->search ({}, {
411 cd => [qw/tags tracks/]
415 my $tags_rs = $note_rs->first->cd->tags;
416 my $tags_count = $tags_rs->count;
418 my ($pr_tags_rs, $pr_tags_count);
421 $schema->storage->debugcb(sub { $queries++ });
422 $schema->storage->debug(1);
426 local $SIG{__WARN__} = sub { $m_o_mm_warn = shift };
427 $pr_tags_rs = $pr_note_rs->first->cd->tags;
429 $pr_tags_count = $pr_tags_rs->count;
431 ok(! $m_o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
433 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
435 is($pr_tags_count, $tags_count, 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)');
437 for ($pr_tags_rs, $tags_rs) {
438 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
441 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)');
444 # remove this closure once the TODO above is working
447 local $SIG{__WARN__} = sub { $w = shift };
449 my $track = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' }, { prefetch => [qw/tracks tags/] })->first->tracks->first;
450 like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
451 'warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
452 my $tag = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' }, { prefetch => { cd => [qw/tags tracks/] } })->first->cd->tags->first;
453 like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
454 'warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');