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)
54 # test a real-life case - rs is obtained by an implicit m2m join
55 $cd_rs = $schema->resultset ('Producer')->first->cds;
56 $attrs = Dumper $cd_rs->{attrs};
58 $cd_rs->search ({})->all;
59 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
62 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
63 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after search with prefetch');
64 }, 'first prefetching search ok');
67 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
68 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after another search with prefetch')
69 }, 'second prefetching search ok');
72 # test a regular rs with an empty seen_join injected - it should still work!
73 $cd_rs = $schema->resultset ('CD');
74 $cd_rs->{attrs}{seen_join} = {};
75 $attrs = Dumper $cd_rs->{attrs};
77 $cd_rs->search ({})->all;
78 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
81 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
82 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after search with prefetch');
83 }, 'first prefetching search ok');
86 $cd_rs->search ({'artist.artistid' => 1}, { prefetch => 'artist' })->all;
87 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after another search with prefetch')
88 }, 'second prefetching search ok');
93 $schema->storage->debugcb(sub { $queries++; });
94 $schema->storage->debug(1);
98 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
100 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
102 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
104 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
106 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
108 is($queries, 1, 'prefetch ran only 1 select statement');
110 $schema->storage->debug($orig_debug);
111 $schema->storage->debugobj->callback(undef);
113 # test for partial prefetch via columns attr
114 my $cd = $schema->resultset('CD')->find(1,
116 columns => [qw/title artist artist.name/],
117 join => { 'artist' => {} }
120 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
122 # start test for nested prefetch SELECT count
124 $schema->storage->debugcb(sub { $queries++ });
125 $schema->storage->debug(1);
127 $rs = $schema->resultset('Tag')->search(
130 prefetch => { cd => 'artist' }
134 my $tag = $rs->first;
136 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
138 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
141 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
142 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
146 is($tag->search_related('cd')->search_related('artist')->first->name,
147 'Caterwauler McCrae',
148 'chained belongs_to->belongs_to search_related ok');
150 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
154 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
156 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
158 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
162 $schema->storage->debugcb(sub { $queries++; });
164 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
166 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
168 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
172 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
174 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
176 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
178 $schema->storage->debug($orig_debug);
179 $schema->storage->debugobj->callback(undef);
181 $rs = $schema->resultset('Tag')->search(
184 join => { cd => 'artist' },
185 prefetch => { cd => 'artist' }
189 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
191 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
192 { order_by => 'artistid DESC', join => 'cds' });
194 is($artist->name, 'Random Boy Band', "Join search by object ok");
196 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
197 { join => 'liner_notes' });
199 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
201 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
203 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
204 { join => { 'cds' => 'tags' } });
206 cmp_ok( @artists, '==', 2, "two-join search ok" );
208 $rs = $schema->resultset("CD")->search(
210 { group_by => [qw/ title me.cdid /] }
214 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
215 if $is_broken_sqlite;
216 cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
219 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
221 $rs = $schema->resultset("CD")->search(
223 { join => [qw/ artist /], group_by => [qw/ artist.name /] }
227 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
228 if $is_broken_sqlite;
229 cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
232 $rs = $schema->resultset("Artist")->search(
234 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
237 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
239 $rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
241 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
243 $rs = $schema->resultset("Artist")->search(
244 { 'cds.title' => 'Spoonful of bees',
245 'cds_2.title' => 'Forkful of bees' },
246 { join => [ 'cds', 'cds' ] });
249 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
250 if $is_broken_sqlite;
251 cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
254 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
256 $cd = $schema->resultset('Artist')->first->create_related('cds',
258 title => 'Unproduced Single',
262 my $left_join = $schema->resultset('CD')->search(
263 { 'me.cdid' => $cd->cdid },
264 { prefetch => { cd_to_producer => 'producer' } }
267 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
270 $schema->storage->debugcb(sub { $queries++ });
271 $schema->storage->debug(1);
274 $schema->resultset('TreeLike')->find(5,
275 { join => { parent => { parent => 'parent' } },
276 prefetch => { parent => { parent => 'parent' } } });
278 is($tree_like->name, 'quux', 'Bottom of tree ok');
279 $tree_like = $tree_like->parent;
280 is($tree_like->name, 'baz', 'First level up ok');
281 $tree_like = $tree_like->parent;
282 is($tree_like->name, 'bar', 'Second level up ok');
283 $tree_like = $tree_like->parent;
284 is($tree_like->name, 'foo', 'Third level up ok');
286 $schema->storage->debug($orig_debug);
287 $schema->storage->debugobj->callback(undef);
289 cmp_ok($queries, '==', 1, 'Only one query run');
291 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
292 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
293 is($tree_like->name, 'quux', 'Tree search_related ok');
295 $tree_like = $schema->resultset('TreeLike')->search_related('children',
296 { 'children.id' => 3, 'children_2.id' => 4 },
297 { prefetch => { children => 'children' } }
299 is(eval { $tree_like->children->first->children->first->name }, 'quux',
300 'Tree search_related with prefetch ok');
302 $tree_like = eval { $schema->resultset('TreeLike')->search(
303 { 'children.id' => 3, 'children_2.id' => 6 },
304 { join => [qw/children children/] }
305 )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
306 )->first->children->first; };
307 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
309 # test that collapsed joins don't get a _2 appended to the alias
312 $schema->storage->debugcb(sub { $sql = $_[1] });
313 $schema->storage->debug(1);
316 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
318 prefetch => 'tracks',
319 })->search_related('tracks')->first;
322 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
324 $schema->storage->debug($orig_debug);
325 $schema->storage->debugobj->callback(undef);
327 $rs = $schema->resultset('Artist');
328 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
329 $rs->create({ artistid => 5, name => 'Emo 4ever' });
330 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
331 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
335 # Tests for multilevel has_many prefetch
337 # artist resultsets - with and without prefetch
338 my $art_rs = $schema->resultset('Artist');
339 my $art_rs_pr = $art_rs->search(
342 join => [ { cds => ['tracks'] } ],
343 prefetch => [ { cds => ['tracks'] } ],
344 cache => 1 # last test needs this
348 # This test does the same operation twice - once on a
349 # set of items fetched from the db with no prefetch of has_many rels
350 # The second prefetches 2 levels of has_many
351 # We check things are the same by comparing the name or title
352 # we build everything into a hash structure and compare the one
353 # from each rs to see what differs
355 sub make_hash_struc {
359 foreach my $art ( $rs->all ) {
360 foreach my $cd ( $art->cds ) {
361 foreach my $track ( $cd->tracks ) {
362 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
370 $schema->storage->debugcb(sub { $queries++ });
371 $schema->storage->debug(1);
373 my $prefetch_result = make_hash_struc($art_rs_pr);
375 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
377 my $nonpre_result = make_hash_struc($art_rs);
379 is_deeply( $prefetch_result, $nonpre_result,
380 'Compare 2 level prefetch result to non-prefetch result' );
384 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
386 'chained has_many->has_many search_related ok'
389 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
391 # once the following TODO is complete, remove the 2 warning tests immediately after the TODO block
392 # (the TODO block itself contains tests ensuring that the warns are removed)
394 local $TODO = 'Prefetch of multiple has_many rels at the same level (currently warn to protect the clueless git)';
397 my $cd_rs = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' });
398 my $pr_cd_rs = $cd_rs->search ({}, {
399 prefetch => [qw/tracks tags/],
402 my $tracks_rs = $cd_rs->first->tracks;
403 my $tracks_count = $tracks_rs->count;
405 my ($pr_tracks_rs, $pr_tracks_count);
408 $schema->storage->debugcb(sub { $queries++ });
409 $schema->storage->debug(1);
413 local $SIG{__WARN__} = sub { $o_mm_warn = shift };
414 $pr_tracks_rs = $pr_cd_rs->first->tracks;
416 $pr_tracks_count = $pr_tracks_rs->count;
418 ok(! $o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
420 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
421 is($pr_tracks_count, $tracks_count, 'equal count of prefetched relations over several same level has_many\'s (1 -> M + M)');
423 for ($pr_tracks_rs, $tracks_rs) {
424 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
427 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)');
430 my $note_rs = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' });
431 my $pr_note_rs = $note_rs->search ({}, {
433 cd => [qw/tags tracks/]
437 my $tags_rs = $note_rs->first->cd->tags;
438 my $tags_count = $tags_rs->count;
440 my ($pr_tags_rs, $pr_tags_count);
443 $schema->storage->debugcb(sub { $queries++ });
444 $schema->storage->debug(1);
448 local $SIG{__WARN__} = sub { $m_o_mm_warn = shift };
449 $pr_tags_rs = $pr_note_rs->first->cd->tags;
451 $pr_tags_count = $pr_tags_rs->count;
453 ok(! $m_o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
455 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
457 is($pr_tags_count, $tags_count, 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)');
459 for ($pr_tags_rs, $tags_rs) {
460 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
463 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)');
466 # remove this closure once the TODO above is working
469 local $SIG{__WARN__} = sub { $w = shift };
471 my $track = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' }, { prefetch => [qw/tracks tags/] })->first->tracks->first;
472 like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
473 'warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
474 my $tag = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' }, { prefetch => { cd => [qw/tags tracks/] } })->first->cd->tags->first;
475 like ($w, qr/will currently disrupt both the functionality of .rs->count\(\), and the amount of objects retrievable via .rs->next\(\)/,
476 'warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');