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