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