2b8fb90dc5e77a8dbd5801dd789937af89ea113f
[dbsrgits/DBIx-Class.git] / t / 77prefetch.t
1 use strict;
2 use warnings;  
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8 use Data::Dumper;
9
10 my $schema = DBICTest->init_schema();
11
12 my $orig_debug = $schema->storage->debug;
13
14 use IO::File;
15
16 BEGIN {
17     eval "use DBD::SQLite";
18     plan $@
19         ? ( skip_all => 'needs DBD::SQLite for testing' )
20         : ( tests => 74 );
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
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;
33 }
34
35 my $queries = 0;
36 $schema->storage->debugcb(sub { $queries++; });
37 $schema->storage->debug(1);
38
39 my @cd = $rs->all;
40
41 is($cd[0]->title, 'Spoonful of bees', 'First record returned ok');
42
43 ok(!defined $cd[0]->liner_notes, 'No prefetch for NULL LEFT join');
44
45 is($cd[1]->{_relationship_data}{liner_notes}->notes, 'Buy Whiskey!', 'Prefetch for present LEFT JOIN');
46
47 is(ref $cd[1]->liner_notes, 'DBICTest::LinerNotes', 'Prefetch returns correct class');
48
49 is($cd[2]->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'Prefetch on parent object ok');
50
51 is($queries, 1, 'prefetch ran only 1 select statement');
52
53 $schema->storage->debug($orig_debug);
54 $schema->storage->debugobj->callback(undef);
55
56 # test for partial prefetch via columns attr
57 my $cd = $schema->resultset('CD')->find(1,
58     {
59       columns => [qw/title artist artist.name/], 
60       join => { 'artist' => {} }
61     }
62 );
63 ok(eval { $cd->artist->name eq 'Caterwauler McCrae' }, 'single related column prefetched');
64
65 # start test for nested prefetch SELECT count
66 $queries = 0;
67 $schema->storage->debugcb(sub { $queries++ });
68 $schema->storage->debug(1);
69
70 $rs = $schema->resultset('Tag')->search(
71   {},
72   {
73     prefetch => { cd => 'artist' }
74   }
75 );
76
77 my $tag = $rs->first;
78
79 is( $tag->cd->title, 'Spoonful of bees', 'step 1 ok for nested prefetch' );
80
81 is( $tag->cd->artist->name, 'Caterwauler McCrae', 'step 2 ok for nested prefetch');
82
83 # count the SELECTs
84 #$selects++ if /SELECT(?!.*WHERE 1=0.*)/;
85 is($queries, 1, 'nested prefetch ran exactly 1 select statement (excluding column_info)');
86
87 $queries = 0;
88
89 is($tag->search_related('cd')->search_related('artist')->first->name,
90    'Caterwauler McCrae',
91    'chained belongs_to->belongs_to search_related ok');
92
93 is($queries, 0, 'chained search_related after belontgs_to->belongs_to prefetch ran no queries');
94
95 $queries = 0;
96
97 $cd = $schema->resultset('CD')->find(1, { prefetch => 'artist' });
98
99 is($cd->{_inflated_column}{artist}->name, 'Caterwauler McCrae', 'artist prefetched correctly on find');
100
101 is($queries, 1, 'find with prefetch ran exactly 1 select statement (excluding column_info)');
102
103 $queries = 0;
104
105 $schema->storage->debugcb(sub { $queries++; });
106
107 $cd = $schema->resultset('CD')->find(1, { prefetch => { cd_to_producer => 'producer' } });
108
109 is($cd->producers->first->name, 'Matt S Trout', 'many_to_many accessor ok');
110
111 is($queries, 1, 'many_to_many accessor with nested prefetch ran exactly 1 query');
112
113 $queries = 0;
114
115 my $producers = $cd->search_related('cd_to_producer')->search_related('producer');
116
117 is($producers->first->name, 'Matt S Trout', 'chained many_to_many search_related ok');
118
119 is($queries, 0, 'chained search_related after many_to_many prefetch ran no queries');
120
121 $schema->storage->debug($orig_debug);
122 $schema->storage->debugobj->callback(undef);
123
124 $rs = $schema->resultset('Tag')->search(
125   {},
126   {
127     join => { cd => 'artist' },
128     prefetch => { cd => 'artist' }
129   }
130 );
131
132 cmp_ok( $rs->count, '>=', 0, 'nested prefetch does not duplicate joins' );
133
134 my ($artist) = $schema->resultset("Artist")->search({ 'cds.year' => 2001 },
135                  { order_by => 'artistid DESC', join => 'cds' });
136
137 is($artist->name, 'Random Boy Band', "Join search by object ok");
138
139 my @cds = $schema->resultset("CD")->search({ 'liner_notes.notes' => 'Buy Merch!' },
140                                { join => 'liner_notes' });
141
142 cmp_ok(scalar @cds, '==', 1, "Single CD retrieved via might_have");
143
144 is($cds[0]->title, "Generic Manufactured Singles", "Correct CD retrieved");
145
146 my @artists = $schema->resultset("Artist")->search({ 'tags.tag' => 'Shiny' },
147                                        { join => { 'cds' => 'tags' } });
148
149 cmp_ok( @artists, '==', 2, "two-join search ok" );
150
151 $rs = $schema->resultset("CD")->search(
152   {},
153   { group_by => [qw/ title me.cdid /] }
154 );
155
156 SKIP: {
157     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
158         if $is_broken_sqlite;
159     cmp_ok( $rs->count, '==', 5, "count() ok after group_by on main pk" );
160 }
161
162 cmp_ok( scalar $rs->all, '==', 5, "all() returns same count as count() after group_by on main pk" );
163
164 $rs = $schema->resultset("CD")->search(
165   {},
166   { join => [qw/ artist /], group_by => [qw/ artist.name /] }
167 );
168
169 SKIP: {
170     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
171         if $is_broken_sqlite;
172     cmp_ok( $rs->count, '==', 3, "count() ok after group_by on related column" );
173 }
174
175 $rs = $schema->resultset("Artist")->search(
176   {},
177       { join => [qw/ cds /], group_by => [qw/ me.name /], having =>{ 'MAX(cds.cdid)'=> \'< 5' } }
178 );
179
180 cmp_ok( $rs->all, '==', 2, "results ok after group_by on related column with a having" );
181
182 $rs = $rs->search( undef, {  having =>{ 'count(*)'=> \'> 2' }});
183
184 cmp_ok( $rs->all, '==', 1, "count() ok after group_by on related column with a having" );
185
186 $rs = $schema->resultset("Artist")->search(
187         { 'cds.title' => 'Spoonful of bees',
188           'cds_2.title' => 'Forkful of bees' },
189         { join => [ 'cds', 'cds' ] });
190
191 SKIP: {
192     skip "SQLite < 3.2.6 doesn't understand COUNT(DISTINCT())", 1
193         if $is_broken_sqlite;
194     cmp_ok($rs->count, '==', 1, "single artist returned from multi-join");
195 }
196
197 is($rs->next->name, 'Caterwauler McCrae', "Correct artist returned");
198
199 $cd = $schema->resultset('Artist')->first->create_related('cds',
200     {
201     title   => 'Unproduced Single',
202     year    => 2007
203 });
204
205 my $left_join = $schema->resultset('CD')->search(
206     { 'me.cdid' => $cd->cdid },
207     { prefetch => { cd_to_producer => 'producer' } }
208 );
209
210 cmp_ok($left_join, '==', 1, 'prefetch with no join record present');
211
212 $queries = 0;
213 $schema->storage->debugcb(sub { $queries++ });
214 $schema->storage->debug(1);
215
216 my $tree_like =
217      $schema->resultset('TreeLike')->find(5,
218        { join     => { parent => { parent => 'parent' } },
219          prefetch => { parent => { parent => 'parent' } } });
220
221 is($tree_like->name, 'quux', 'Bottom of tree ok');
222 $tree_like = $tree_like->parent;
223 is($tree_like->name, 'baz', 'First level up ok');
224 $tree_like = $tree_like->parent;
225 is($tree_like->name, 'bar', 'Second level up ok');
226 $tree_like = $tree_like->parent;
227 is($tree_like->name, 'foo', 'Third level up ok');
228
229 $schema->storage->debug($orig_debug);
230 $schema->storage->debugobj->callback(undef);
231
232 cmp_ok($queries, '==', 1, 'Only one query run');
233
234 $tree_like = $schema->resultset('TreeLike')->search({'me.id' => 2});
235 $tree_like = $tree_like->search_related('children')->search_related('children')->search_related('children')->first;
236 is($tree_like->name, 'quux', 'Tree search_related ok');
237
238 $tree_like = $schema->resultset('TreeLike')->search_related('children',
239     { 'children.id' => 3, 'children_2.id' => 4 },
240     { prefetch => { children => 'children' } }
241   )->first;
242 is(eval { $tree_like->children->first->children->first->name }, 'quux',
243    'Tree search_related with prefetch ok');
244
245 $tree_like = eval { $schema->resultset('TreeLike')->search(
246     { 'children.id' => 3, 'children_2.id' => 6 }, 
247     { join => [qw/children children/] }
248   )->search_related('children', { 'children_4.id' => 7 }, { prefetch => 'children' }
249   )->first->children->first; };
250 is(eval { $tree_like->name }, 'fong', 'Tree with multiple has_many joins ok');
251
252 # test that collapsed joins don't get a _2 appended to the alias
253
254 my $sql = '';
255 $schema->storage->debugcb(sub { $sql = $_[1] });
256 $schema->storage->debug(1);
257
258 eval {
259   my $row = $schema->resultset('Artist')->search_related('cds', undef, {
260     join => 'tracks',
261     prefetch => 'tracks',
262   })->search_related('tracks')->first;
263 };
264
265 like( $sql, qr/^SELECT tracks_2\.trackid/, "join not collapsed for search_related" );
266
267 $schema->storage->debug($orig_debug);
268 $schema->storage->debugobj->callback(undef);
269
270 $rs = $schema->resultset('Artist');
271 $rs->create({ artistid => 4, name => 'Unknown singer-songwriter' });
272 $rs->create({ artistid => 5, name => 'Emo 4ever' });
273 @artists = $rs->search(undef, { prefetch => 'cds', order_by => 'artistid' });
274 is(scalar @artists, 5, 'has_many prefetch with adjacent empty rows ok');
275
276 # -------------
277 #
278 # Tests for multilevel has_many prefetch
279
280 # artist resultsets - with and without prefetch
281 my $art_rs = $schema->resultset('Artist');
282 my $art_rs_pr = $art_rs->search(
283     {},
284     {
285         join     => [ { cds => ['tracks'] } ],
286         prefetch => [ { cds => ['tracks'] } ],
287         cache    => 1 # last test needs this
288     }
289 );
290
291 # This test does the same operation twice - once on a
292 # set of items fetched from the db with no prefetch of has_many rels
293 # The second prefetches 2 levels of has_many
294 # We check things are the same by comparing the name or title
295 # we build everything into a hash structure and compare the one
296 # from each rs to see what differs
297
298 sub make_hash_struc {
299     my $rs = shift;
300
301     my $struc = {};
302     foreach my $art ( $rs->all ) {
303         foreach my $cd ( $art->cds ) {
304             foreach my $track ( $cd->tracks ) {
305                 $struc->{ $art->name }{ $cd->title }{ $track->title }++;
306             }
307         }
308     }
309     return $struc;
310 }
311
312 $queries = 0;
313 $schema->storage->debugcb(sub { $queries++ });
314 $schema->storage->debug(1);
315
316 my $prefetch_result = make_hash_struc($art_rs_pr);
317
318 is($queries, 1, 'nested prefetch across has_many->has_many ran exactly 1 query');
319
320 my $nonpre_result   = make_hash_struc($art_rs);
321
322 is_deeply( $prefetch_result, $nonpre_result,
323     'Compare 2 level prefetch result to non-prefetch result' );
324
325 $queries = 0;
326
327 is($art_rs_pr->search_related('cds')->search_related('tracks')->first->title,
328    'Fowlin',
329    'chained has_many->has_many search_related ok'
330   );
331
332 is($queries, 0, 'chained search_related after has_many->has_many prefetch ran no queries');
333