9 my $schema = DBICTest->init_schema();
11 my $orig_debug = $schema->storage->debug;
16 eval "use DBD::SQLite";
18 ? ( skip_all => 'needs DBD::SQLite for testing' )
22 # figure out if we've got a version of sqlite that is older than 3.2.6, in
23 # which case COUNT(DISTINCT()) doesn't work
24 my $is_broken_sqlite = 0;
25 my ($sqlite_major_ver,$sqlite_minor_ver,$sqlite_patch_ver) =
26 split /\./, $schema->storage->dbh->get_info(18);
27 if( $schema->storage->dbh->get_info(17) eq 'SQLite' &&
28 ( ($sqlite_major_ver < 3) ||
29 ($sqlite_major_ver == 3 && $sqlite_minor_ver < 2) ||
30 ($sqlite_major_ver == 3 && $sqlite_minor_ver == 2 && $sqlite_patch_ver < 6) ) ) {
31 $is_broken_sqlite = 1;
34 # bug in 0.07000 caused attr (join/prefetch) to be modifed by search
35 # so we check the search & attr arrays are not modified
36 my $search = { 'artist.name' => 'Caterwauler McCrae' };
37 my $attr = { prefetch => [ qw/artist liner_notes/ ],
38 order_by => 'me.cdid' };
39 my $search_str = Dumper($search);
40 my $attr_str = Dumper($attr);
42 my $rs = $schema->resultset("CD")->search($search, $attr);
44 is(Dumper($search), $search_str, 'Search hash untouched after search()');
45 is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
46 cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
49 $schema->storage->debugcb(sub { $queries++; });
50 $schema->storage->debug(1);
54 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
56 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
58 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
60 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
62 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
64 is($queries, 1, 'prefetch ran only 1 select statement');
66 $schema->storage->debug($orig_debug);
67 $schema->storage->debugobj->callback(undef);
69 # test for partial prefetch via columns attr
70 my $cd = $schema->resultset('CD')->find(1,
72 columns => [qw/title artist.name/],
73 join => { 'artist' => {} }
76 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
78 # start test for nested prefetch SELECT count
80 $schema->storage->debugcb(sub { $queries++ });
81 $schema->storage->debug(1);
83 $rs = $schema->resultset('Tag')->search(
86 prefetch => { cd => 'artist' }
92 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
94 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
97 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
98 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
102 is($tag->search_related('cd')->search_related('artist')->first->name,
103 'Caterwauler McCrae',
104 'chained belongs_to->belongs_to search_related ok');
106 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
110 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
112 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
114 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
118 $schema->storage->debugcb(sub { $queries++; });
120 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
122 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
124 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
128 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
130 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
132 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
134 $schema->storage->debug($orig_debug);
135 $schema->storage->debugobj->callback(undef);
137 $rs = $schema->resultset('Tag')->search(
140 join => { cd => 'artist' },
141 prefetch => { cd => 'artist' }
145 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
147 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
148 { order_by => 'artistid DESC', join => 'cds' });
150 is($artist->name, 'Random Boy Band', "Join search by object ok");
152 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
153 { join => 'liner_notes' });
155 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
157 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
159 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
160 { join => { 'cds' => 'tags' } });
162 cmp_ok( @artists, '==', 2, "two-join search ok" );
164 $rs = $schema->resultset("CD")->search(
166 { group_by => [qw/ title me.cdid /] }
170 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
171 if $is_broken_sqlite;
172 cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
175 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
177 $rs = $schema->resultset("CD")->search(
179 { join => [qw/ artist /], group_by => [qw/ artist.name /] }
183 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
184 if $is_broken_sqlite;
185 cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
188 $rs = $schema->resultset("Artist")->search(
190 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
193 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
195 $rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
197 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
199 $rs = $schema->resultset("Artist")->search(
200 { 'cds.title' => 'Spoonful of bees',
201 'cds_2.title' => 'Forkful of bees' },
202 { join => [ 'cds', 'cds' ] });
205 skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
206 if $is_broken_sqlite;
207 cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
210 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
212 $cd = $schema->resultset('Artist')->first->create_related('cds',
214 title => 'Unproduced Single',
218 my $left_join = $schema->resultset('CD')->search(
219 { 'me.cdid' => $cd->cdid },
220 { prefetch => { cd_to_producer => 'producer' } }
223 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
226 $schema->storage->debugcb(sub { $queries++ });
227 $schema->storage->debug(1);
230 $schema->resultset('TreeLike')->find(4,
231 { join => { parent => { parent => 'parent' } },
232 prefetch => { parent => { parent => 'parent' } } });
234 is($tree_like->name, 'quux', 'Bottom of tree ok');
235 $tree_like = $tree_like->parent;
236 is($tree_like->name, 'baz', 'First level up ok');
237 $tree_like = $tree_like->parent;
238 is($tree_like->name, 'bar', 'Second level up ok');
239 $tree_like = $tree_like->parent;
240 is($tree_like->name, 'foo', 'Third level up ok');
242 $schema->storage->debug($orig_debug);
243 $schema->storage->debugobj->callback(undef);
245 cmp_ok($queries, '==', 1, 'Only one query run');
247 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 1});
248 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
249 is($tree_like->name, 'quux', 'Tree search_related ok');
251 $tree_like = $schema->resultset('TreeLike')->search_related('children',
252 { 'children.id' => 2, 'children_2.id' => 3 },
253 { prefetch => { children => 'children' } }
255 is(eval { $tree_like->children->first->children->first->name }, 'quux',
256 'Tree search_related with prefetch ok');
258 $tree_like = eval { $schema->resultset('TreeLike')->search(
259 { 'children.id' => 2, 'children_2.id' => 5 },
260 { join => [qw/children children/] }
261 )->search_related('children', { 'children_4.id' => 6 }, { prefetch => 'children' }
262 )->first->children->first; };
263 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
265 # test that collapsed joins don't get a _2 appended to the alias
268 $schema->storage->debugcb(sub { $sql = $_[1] });
269 $schema->storage->debug(1);
272 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
274 prefetch => 'tracks',
275 })->search_related('tracks')->first;
278 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
280 $schema->storage->debug($orig_debug);
281 $schema->storage->debugobj->callback(undef);
283 $rs = $schema->resultset('Artist');
284 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
285 $rs->create({ artistid => 5, name => 'Emo 4ever' });
286 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
287 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
291 # Tests for multilevel has_many prefetch
293 # artist resultsets - with and without prefetch
294 my $art_rs = $schema->resultset('Artist');
295 my $art_rs_pr = $art_rs->search(
298 join => [ { cds => ['tracks'] } ],
299 prefetch => [ { cds => ['tracks'] } ],
300 cache => 1 # last test needs this
304 # This test does the same operation twice - once on a
305 # set of items fetched from the db with no prefetch of has_many rels
306 # The second prefetches 2 levels of has_many
307 # We check things are the same by comparing the name or title
308 # we build everything into a hash structure and compare the one
309 # from each rs to see what differs
311 sub make_hash_struc {
315 foreach my $art ( $rs->all ) {
316 foreach my $cd ( $art->cds ) {
317 foreach my $track ( $cd->tracks ) {
318 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
326 $schema->storage->debugcb(sub { $queries++ });
327 $schema->storage->debug(1);
329 my $prefetch_result = make_hash_struc($art_rs_pr);
331 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
333 my $nonpre_result = make_hash_struc($art_rs);
335 is_deeply( $prefetch_result, $nonpre_result,
336 'Compare 2 level prefetch result to non-prefetch result' );
340 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
342 'chained has_many->has_many search_related ok'
345 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
347 # once the following TODO is complete, remove the 2 stop-gap tests immediately after the TODO block
348 # (the TODO block itself contains tests ensuring that the stop-gaps are removed)
350 local $TODO = 'Prefetch of multiple has_many rels at the same level (currently must die to protect the clueless git)';
351 use DBIx::Class::ResultClass::HashRefInflator;
354 my $cd_rs = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' });
355 my $pr_cd_rs = $cd_rs->search ({}, {
356 prefetch => [qw/tracks tags/],
359 my $tracks_rs = $cd_rs->first->tracks;
360 my $tracks_count = $tracks_rs->count;
362 my ($pr_tracks_rs, $pr_tracks_count);
365 $schema->storage->debugcb(sub { $queries++ });
366 $schema->storage->debug(1);
368 $pr_tracks_rs = $pr_cd_rs->first->tracks;
369 $pr_tracks_count = $pr_tracks_rs->count;
373 ok(! $o_mm_exc, 'exception on attempt to prefetch several same level has_many\'s (1 -> M + M)');
376 skip "1 -> M + M prefetch died", 3 if $o_mm_exc;
378 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
379 is($pr_tracks_count, $tracks_count, 'equal count of prefetched relations over several same level has_many\'s (1 -> M + M)');
381 for ($pr_tracks_rs, $tracks_rs) {
382 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
385 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)');
389 my $note_rs = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' });
390 my $pr_note_rs = $note_rs->search ({}, {
392 cd => [qw/tags tracks/]
396 my $tags_rs = $note_rs->first->cd->tags;
397 my $tags_count = $tags_rs->count;
399 my ($pr_tags_rs, $pr_tags_count);
402 $schema->storage->debugcb(sub { $queries++ });
403 $schema->storage->debug(1);
405 $pr_tags_rs = $pr_note_rs->first->cd->tags;
406 $pr_tags_count = $pr_tags_rs->count;
410 ok(! $m_o_mm_exc, 'exception on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
413 skip "M -> 1 -> M + M prefetch died", 3 if $m_o_mm_exc;
415 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
417 is($pr_tags_count, $tags_count, 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)');
419 for ($pr_tags_rs, $tags_rs) {
420 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
423 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)');
427 eval { my $track = $schema->resultset('CD')->search ({ 'me.title' => 'Forkful of bees' }, { prefetch => [qw/tracks tags/] })->first->tracks->first };
428 ok ($@, 'exception on attempt to prefetch several same level has_many\'s (1 -> M + M)');
429 eval { my $tag = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' }, { prefetch => { cd => [qw/tags tracks/] } })->first->cd->tags->first };
430 ok ($@, 'exception on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');