Test for resultset corruption by search()
[dbsrgits/DBIx-Class.git] / t / 77prefetch.t
CommitLineData
96e7f9ec 1use strict;
2use warnings;
3
4use Test::More;
1b374bf3 5use Test::Exception;
96e7f9ec 6use lib qw(t/lib);
7use DBICTest;
8use Data::Dumper;
9
10my $schema = DBICTest->init_schema();
11
12my $orig_debug = $schema->storage->debug;
13
14use IO::File;
15
16BEGIN {
17 eval "use DBD::SQLite";
18 plan $@
19 ? ( skip_all => 'needs DBD::SQLite for testing' )
1b374bf3 20 : ( tests => 63 );
96e7f9ec 21}
22
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}
34
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
37my $search = { 'artist.name' => 'Caterwauler McCrae' };
38my $attr = { prefetch => [ qw/artist liner_notes/ ],
39 order_by => 'me.cdid' };
40my $search_str = Dumper($search);
41my $attr_str = Dumper($attr);
42
43my $rs = $schema->resultset("CD")->search($search, $attr);
44
45is(Dumper($search), $search_str, 'Search hash untouched after search()');
46is(Dumper($attr), $attr_str, 'Attribute hash untouched after search()');
47cmp_ok($rs + 0, '==', 3, 'Correct number of records returned');
48
1b374bf3 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)
51{
52 my $cd_rs = $schema->resultset ('Producer')->first->cds;
53 my $attrs = Dumper $cd_rs->{attrs};
54
55 $cd_rs->search ({})->all;
56 is (Dumper ($cd_rs->{attrs}), $attrs, 'Resultset attributes preserved after a simple search');
57
58 lives_ok (sub {
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');
62
63 lives_ok (sub {
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');
67}
68
69
96e7f9ec 70my $queries = 0;
71$schema->storage->debugcb(sub { $queries++; });
72$schema->storage->debug(1);
73
74my @cd = $rs->all;
75
76is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
77
78ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
79
80is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
81
82is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
83
84is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
85
86is($queries, 1, 'prefetch ran only 1 select statement');
87
88$schema->storage->debug($orig_debug);
89$schema->storage->debugobj->callback(undef);
90
91# test for partial prefetch via columns attr
92my $cd = $schema->resultset('CD')->find(1,
93 {
370f2ba2 94 columns => [qw/title artist artist.name/],
96e7f9ec 95 join => { 'artist' => {} }
96 }
97);
98ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
99
100# start test for nested prefetch SELECT count
101$queries = 0;
102$schema->storage->debugcb(sub { $queries++ });
103$schema->storage->debug(1);
104
105$rs = $schema->resultset('Tag')->search(
106 {},
107 {
108 prefetch => { cd => 'artist' }
109 }
110);
111
112my $tag = $rs->first;
113
114is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
115
116is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
117
118# count the SELECTs
119#$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
120is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
121
122$queries = 0;
123
124is($tag->search_related('cd')->search_related('artist')->first->name,
125 'Caterwauler McCrae',
126 'chained belongs_to->belongs_to search_related ok');
127
128is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
129
130$queries = 0;
131
132$cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
133
134is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
135
136is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
137
138$queries = 0;
139
140$schema->storage->debugcb(sub { $queries++; });
141
142$cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
143
144is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
145
146is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
147
148$queries = 0;
149
150my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
151
152is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
153
154is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
155
156$schema->storage->debug($orig_debug);
157$schema->storage->debugobj->callback(undef);
158
159$rs = $schema->resultset('Tag')->search(
160 {},
161 {
162 join => { cd => 'artist' },
163 prefetch => { cd => 'artist' }
164 }
165);
166
167cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
168
169my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
170 { order_by => 'artistid DESC', join => 'cds' });
171
172is($artist->name, 'Random Boy Band', "Join search by object ok");
173
174my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
175 { join => 'liner_notes' });
176
177cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
178
179is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
180
181my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
182 { join => { 'cds' => 'tags' } });
183
184cmp_ok( @artists, '==', 2, "two-join search ok" );
185
186$rs = $schema->resultset("CD")->search(
187 {},
188 { group_by => [qw/ title me.cdid /] }
189);
190
191SKIP: {
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" );
195}
196
197cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
198
199$rs = $schema->resultset("CD")->search(
200 {},
201 { join => [qw/ artist /], group_by => [qw/ artist.name /] }
202);
203
204SKIP: {
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" );
208}
209
210$rs = $schema->resultset("Artist")->search(
211 {},
212 { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
213);
214
215cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
216
217$rs = $rs->search( undef, { having =>{ 'count(*)'=> \'> 2' }});
218
219cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
220
221$rs = $schema->resultset("Artist")->search(
222 { 'cds.title' => 'Spoonful of bees',
223 'cds_2.title' => 'Forkful of bees' },
224 { join => [ 'cds', 'cds' ] });
225
226SKIP: {
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");
230}
231
232is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
233
234$cd = $schema->resultset('Artist')->first->create_related('cds',
235 {
236 title => 'Unproduced Single',
237 year => 2007
238});
239
240my $left_join = $schema->resultset('CD')->search(
241 { 'me.cdid' => $cd->cdid },
242 { prefetch => { cd_to_producer => 'producer' } }
243);
244
245cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
246
247$queries = 0;
248$schema->storage->debugcb(sub { $queries++ });
249$schema->storage->debug(1);
250
251my $tree_like =
8871d4ad 252 $schema->resultset('TreeLike')->find(5,
96e7f9ec 253 { join => { parent => { parent => 'parent' } },
254 prefetch => { parent => { parent => 'parent' } } });
255
256is($tree_like->name, 'quux', 'Bottom of tree ok');
257$tree_like = $tree_like->parent;
258is($tree_like->name, 'baz', 'First level up ok');
259$tree_like = $tree_like->parent;
260is($tree_like->name, 'bar', 'Second level up ok');
261$tree_like = $tree_like->parent;
262is($tree_like->name, 'foo', 'Third level up ok');
263
264$schema->storage->debug($orig_debug);
265$schema->storage->debugobj->callback(undef);
266
267cmp_ok($queries, '==', 1, 'Only one query run');
268
8871d4ad 269$tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
96e7f9ec 270$tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
271is($tree_like->name, 'quux', 'Tree search_related ok');
272
273$tree_like = $schema->resultset('TreeLike')->search_related('children',
8871d4ad 274 { 'children.id' => 3, 'children_2.id' => 4 },
96e7f9ec 275 { prefetch => { children => 'children' } }
276 )->first;
277is(eval { $tree_like->children->first->children->first->name }, 'quux',
278 'Tree search_related with prefetch ok');
279
280$tree_like = eval { $schema->resultset('TreeLike')->search(
8871d4ad 281 { 'children.id' => 3, 'children_2.id' => 6 },
96e7f9ec 282 { join => [qw/children children/] }
8871d4ad 283 )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
96e7f9ec 284 )->first->children->first; };
285is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
286
287# test that collapsed joins don't get a _2 appended to the alias
288
289my $sql = '';
290$schema->storage->debugcb(sub { $sql = $_[1] });
291$schema->storage->debug(1);
292
293eval {
294 my $row = $schema->resultset('Artist')->search_related('cds', undef, {
295 join => 'tracks',
296 prefetch => 'tracks',
297 })->search_related('tracks')->first;
298};
299
300like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
301
302$schema->storage->debug($orig_debug);
303$schema->storage->debugobj->callback(undef);
304
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' });
309is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
310
311# -------------
312#
313# Tests for multilevel has_many prefetch
314
315# artist resultsets - with and without prefetch
316my $art_rs = $schema->resultset('Artist');
317my $art_rs_pr = $art_rs->search(
318 {},
319 {
320 join => [ { cds => ['tracks'] } ],
321 prefetch => [ { cds => ['tracks'] } ],
322 cache => 1 # last test needs this
323 }
324);
325
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
332
333sub make_hash_struc {
334 my $rs = shift;
335
336 my $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 }++;
341 }
342 }
343 }
344 return $struc;
345}
346
347$queries = 0;
348$schema->storage->debugcb(sub { $queries++ });
349$schema->storage->debug(1);
350
351my $prefetch_result = make_hash_struc($art_rs_pr);
352
353is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
354
355my $nonpre_result = make_hash_struc($art_rs);
356
357is_deeply( $prefetch_result, $nonpre_result,
358 'Compare 2 level prefetch result to non-prefetch result' );
359
360$queries = 0;
361
362is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
363 'Fowlin',
364 'chained has_many->has_many search_related ok'
365 );
366
367is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
b2df8400 368
616b461d 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)
b2df8400 371TODO: {
616b461d 372 local $TODO = 'Prefetch of multiple has_many rels at the same level (currently warn to protect the clueless git)';
b2df8400 373
374 #( 1 -> M + M )
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/],
378 });
379
380 my $tracks_rs = $cd_rs->first->tracks;
381 my $tracks_count = $tracks_rs->count;
382
383 my ($pr_tracks_rs, $pr_tracks_count);
384
385 $queries = 0;
386 $schema->storage->debugcb(sub { $queries++ });
387 $schema->storage->debug(1);
616b461d 388
389 my $o_mm_warn;
390 {
391 local $SIG{__WARN__} = sub { $o_mm_warn = shift };
b2df8400 392 $pr_tracks_rs = $pr_cd_rs->first->tracks;
b2df8400 393 };
616b461d 394 $pr_tracks_count = $pr_tracks_rs->count;
b2df8400 395
616b461d 396 ok(! $o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (1 -> M + M)');
b2df8400 397
616b461d 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)');
b2df8400 400
616b461d 401 for ($pr_tracks_rs, $tracks_rs) {
402 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
403 }
6a1bce35 404
616b461d 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)');
b2df8400 406
407 #( M -> 1 -> M + M )
408 my $note_rs = $schema->resultset('LinerNotes')->search ({ notes => 'Buy Whiskey!' });
409 my $pr_note_rs = $note_rs->search ({}, {
410 prefetch => {
411 cd => [qw/tags tracks/]
412 },
413 });
414
415 my $tags_rs = $note_rs->first->cd->tags;
416 my $tags_count = $tags_rs->count;
417
418 my ($pr_tags_rs, $pr_tags_count);
419
420 $queries = 0;
421 $schema->storage->debugcb(sub { $queries++ });
422 $schema->storage->debug(1);
616b461d 423
424 my $m_o_mm_warn;
425 {
426 local $SIG{__WARN__} = sub { $m_o_mm_warn = shift };
b2df8400 427 $pr_tags_rs = $pr_note_rs->first->cd->tags;
b2df8400 428 };
616b461d 429 $pr_tags_count = $pr_tags_rs->count;
b2df8400 430
616b461d 431 ok(! $m_o_mm_warn, 'no warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)');
b2df8400 432
616b461d 433 is($queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query');
b2df8400 434
616b461d 435 is($pr_tags_count, $tags_count, 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)');
6a1bce35 436
616b461d 437 for ($pr_tags_rs, $tags_rs) {
438 $_->result_class ('DBIx::Class::ResultClass::HashRefInflator');
439 }
6a1bce35 440
616b461d 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)');
b2df8400 442};
5aac79f7 443
616b461d 444# remove this closure once the TODO above is working
445my $w;
446{
447 local $SIG{__WARN__} = sub { $w = shift };
448
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)');
455}