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