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