Radically rethink complex prefetch - make most useful cases just work (tm)
[dbsrgits/DBIx-Class.git] / t / prefetch / manual.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Deep;
6 use Test::Warn;
7 use Test::Exception;
8 use lib qw(t/lib);
9 use DBICTest;
10
11 my $schema = DBICTest->init_schema(no_populate => 1);
12
13 $schema->resultset('Artist')->create({ name => 'JMJ', cds => [{
14   title => 'Magnetic Fields',
15   year => 1981,
16   genre => { name => 'electro' },
17   tracks => [
18     { title => 'm1' },
19     { title => 'm2' },
20     { title => 'm3' },
21     { title => 'm4' },
22   ],
23 } ] });
24
25 $schema->resultset('CD')->create({
26   title => 'Equinoxe',
27   year => 1978,
28   artist => { name => 'JMJ' },
29   genre => { name => 'electro' },
30   tracks => [
31     { title => 'e1' },
32     { title => 'e2' },
33     { title => 'e3' },
34   ],
35   single_track => {
36     title => 'o1',
37     cd => {
38       title => 'Oxygene',
39       year => 1976,
40       artist => { name => 'JMJ' },
41       tracks => [
42         { title => 'o2', position => 2},  # the position should not be here, bug in MC
43       ],
44     },
45   },
46 });
47
48 my $rs = $schema->resultset ('CD')->search ({}, {
49   join => [ 'tracks', { single_track => { cd => { artist => { cds => 'tracks' } } } }  ],
50   collapse => 1,
51   columns => [
52     { 'year'                                    => 'me.year' },               # non-unique
53     { 'genreid'                                 => 'me.genreid' },            # nullable
54     { 'tracks.title'                            => 'tracks.title' },          # non-unique (no me.id)
55     { 'single_track.cd.artist.cds.cdid'         => 'cds.cdid' },              # to give uniquiness to ...tracks.title below
56     { 'single_track.cd.artist.artistid'         => 'artist.artistid' },       # uniqufies entire parental chain
57     { 'single_track.cd.artist.cds.year'         => 'cds.year' },              # non-unique
58     { 'single_track.cd.artist.cds.genreid'      => 'cds.genreid' },           # nullable
59     { 'single_track.cd.artist.cds.tracks.title' => 'tracks_2.title' },        # unique when combined with ...cds.cdid above
60     { 'latest_cd'                     => \ "(SELECT MAX(year) FROM cd)" },    # random function
61     { 'title'                                   => 'me.title' },              # uniquiness for me
62     { 'artist'                                  => 'me.artist' },             # uniquiness for me
63   ],
64   order_by => [{ -desc => 'cds.year' }, { -desc => 'me.title'} ],
65 });
66
67 my $hri_rs = $rs->search({}, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' });
68
69 cmp_deeply (
70   [$hri_rs->all],
71   [
72     { artist => 1, genreid => 1, latest_cd => 1981, title => "Equinoxe", year => 1978,
73       single_track => {
74         cd => {
75           artist => { artistid => 1, cds => [
76             { cdid => 1, genreid => 1, year => 1981, tracks => [
77               { title => "m1" },
78               { title => "m2" },
79               { title => "m3" },
80               { title => "m4" },
81             ]},
82             { cdid => 3, genreid => 1, year => 1978, tracks => [
83               { title => "e1" },
84               { title => "e2" },
85               { title => "e3" },
86             ]},
87             { cdid => 2, genreid => undef, year => 1976, tracks => [
88               { title => "o1" },
89               { title => "o2" },
90             ]},
91           ]},
92         },
93       },
94       tracks => [
95         { title => "e1" },
96         { title => "e2" },
97         { title => "e3" },
98       ],
99     },
100     {
101       artist => 1, genreid => undef, latest_cd => 1981, title => "Oxygene", year => 1976, single_track => undef,
102       tracks => [
103         { title => "o1" },
104         { title => "o2" },
105       ],
106     },
107     {
108       artist => 1, genreid => 1, latest_cd => 1981, title => "Magnetic Fields", year => 1981, single_track => undef,
109       tracks => [
110         { title => "m1" },
111         { title => "m2" },
112         { title => "m3" },
113         { title => "m4" },
114       ],
115     },
116   ],
117   'W00T, manual prefetch with collapse works'
118 );
119
120 TODO: {
121   my ($row) = $rs->all;
122   local $TODO = 'Something is wrong with filter type rels, they throw on incomplete objects >.<';
123
124   lives_ok {
125     cmp_deeply (
126       { $row->single_track->get_columns },
127       {},
128       'empty intermediate object ok',
129     )
130   } 'no exception';
131 }
132
133 TODO: {
134 local $TODO = 'this does not work at all, need to promote rsattrs to an object on its own';
135 # make sure has_many column redirection does not do weird stuff when collapse is requested
136 for my $pref_args (
137   { prefetch => 'cds'},
138   { collapse => 1 }
139 ) {
140   for my $col_and_join_args (
141     { '+columns' => { 'cd_title' => 'cds_2.title' }, join => [ 'cds', 'cds' ] },
142     { '+columns' => { 'cd_title' => 'cds.title' }, join => 'cds', }
143   ) {
144
145     my $weird_rs = $schema->resultset('Artist')->search({}, {
146       %$col_and_join_args, %$pref_args,
147     });
148
149     for (qw/next all first/) {
150       throws_ok { $weird_rs->$_ } qr/not yet determined exception text/;
151     }
152   }
153 }
154 }
155
156 # multi-has_many with underdefined root, with rather random order
157 $rs = $schema->resultset ('CD')->search ({}, {
158   join => [ 'tracks', { single_track => { cd => { artist => { cds => 'tracks' } } } }  ],
159   collapse => 1,
160   columns => [
161     { 'single_track.trackid'                    => 'single_track.trackid' },  # definitive link to root from 1:1:1:1:M:M chain
162     { 'year'                                    => 'me.year' },               # non-unique
163     { 'tracks.cd'                               => 'tracks.cd' },             # \ together both uniqueness for second multirel
164     { 'tracks.title'                            => 'tracks.title' },          # / and definitive link back to root
165     { 'single_track.cd.artist.cds.cdid'         => 'cds.cdid' },              # to give uniquiness to ...tracks.title below
166     { 'single_track.cd.artist.cds.year'         => 'cds.year' },              # non-unique
167     { 'single_track.cd.artist.artistid'         => 'artist.artistid' },       # uniqufies entire parental chain
168     { 'single_track.cd.artist.cds.genreid'      => 'cds.genreid' },           # nullable
169     { 'single_track.cd.artist.cds.tracks.title' => 'tracks_2.title' },        # unique when combined with ...cds.cdid above
170   ],
171 });
172
173 for (1..3) {
174   $rs->create({ artist => 1, year => 1977, title => "fuzzy_$_" });
175 }
176
177 my $rs_random = $rs->search({}, { order_by => \ 'RANDOM()' });
178 is ($rs_random->count, 6, 'row count matches');
179
180 if ($ENV{TEST_VERBOSE}) {
181  my @lines = (
182     [ "What are we actually trying to collapse (Select/As, tests below will see a *DIFFERENT* random order):" ],
183     [ map { my $s = $_; $s =~ s/single_track\./sngl_tr./; $s } @{$rs_random->{_attrs}{select} } ],
184     $rs_random->{_attrs}{as},
185     [ "-" x 159 ],
186     $rs_random->cursor->all,
187   );
188
189   diag join ' # ', map { sprintf '% 15s', (defined $_ ? $_ : 'NULL') } @$_
190     for @lines;
191 }
192
193 {
194   my $queries = 0;
195   $schema->storage->debugcb(sub { $queries++ });
196   my $orig_debug = $schema->storage->debug;
197   $schema->storage->debug (1);
198
199   for my $use_next (0, 1) {
200     my @random_cds;
201     if ($use_next) {
202       warnings_exist {
203         while (my $o = $rs_random->next) {
204           push @random_cds, $o;
205         }
206       } qr/performed an eager cursor slurp underneath/,
207       'Warned on auto-eager cursor';
208     }
209     else {
210       @random_cds = $rs_random->all;
211     }
212
213     is (@random_cds, 6, 'object count matches');
214
215     for my $cd (@random_cds) {
216       if ($cd->year == 1977) {
217         is( scalar $cd->tracks, 0, 'no tracks on 1977 cd' );
218         is( $cd->single_track, undef, 'no single_track on 1977 cd' );
219       }
220       elsif ($cd->year == 1976) {
221         is( scalar $cd->tracks, 2, 'Two tracks on 1976 cd' );
222         like( $_->title, qr/^o\d/, "correct title" )
223           for $cd->tracks;
224         is( $cd->single_track, undef, 'no single_track on 1976 cd' );
225       }
226       elsif ($cd->year == 1981) {
227         is( scalar $cd->tracks, 4, 'Four tracks on 1981 cd' );
228         like( $_->title, qr/^m\d/, "correct title" )
229           for $cd->tracks;
230         is( $cd->single_track, undef, 'no single_track on 1981 cd' );
231       }
232       elsif ($cd->year == 1978) {
233         is( scalar $cd->tracks, 3, 'Three tracks on 1978 cd' );
234         like( $_->title, qr/^e\d/, "correct title" )
235           for $cd->tracks;
236         ok( defined $cd->single_track, 'single track prefetched on 1987 cd' );
237         is( $cd->single_track->cd->artist->id, 1, 'Single_track->cd->artist prefetched on 1978 cd' );
238         is( scalar $cd->single_track->cd->artist->cds, 6, '6 cds prefetched on artist' );
239       }
240     }
241   }
242
243   $schema->storage->debugcb(undef);
244   $schema->storage->debug($orig_debug);
245   is ($queries, 2, "Only two queries for two prefetch calls total");
246 }
247
248 # can't cmp_deeply a random set - need *some* order
249 my $ord_rs = $rs->search({}, {
250   order_by => [ 'tracks_2.title', 'tracks.title', 'cds.cdid', \ 'RANDOM()' ],
251   result_class => 'DBIx::Class::ResultClass::HashRefInflator',
252 });
253 my @hris_all = sort { $a->{year} cmp $b->{year} } $ord_rs->all;
254 is (@hris_all, 6, 'hri count matches' );
255
256 my $iter_rs = $rs->search({}, {
257   order_by => [ 'me.year', 'me.cdid', 'tracks_2.title', 'tracks.title', 'cds.cdid', \ 'RANDOM()' ],
258   result_class => 'DBIx::Class::ResultClass::HashRefInflator',
259 });
260 my @hris_iter;
261 while (my $r = $iter_rs->next) {
262   push @hris_iter, $r;
263 }
264
265 cmp_deeply(
266   \@hris_iter,
267   \@hris_all,
268   'Iteration works correctly',
269 );
270
271 my @hri_contents = (
272   { year => 1976, single_track => undef, tracks => [
273     { cd => 2, title => "o1" },
274     { cd => 2, title => "o2" },
275   ]},
276   { year => 1977, single_track => undef, tracks => [] },
277   { year => 1977, single_track => undef, tracks => [] },
278   { year => 1977, single_track => undef, tracks => [] },
279   {
280     year => 1978,
281     single_track => {
282       trackid => 6,
283       cd => {
284         artist => {
285           artistid => 1, cds => [
286             { cdid => 4, genreid => undef, year => 1977, tracks => [] },
287             { cdid => 5, genreid => undef, year => 1977, tracks => [] },
288             { cdid => 6, genreid => undef, year => 1977, tracks => [] },
289             { cdid => 3, genreid => 1, year => 1978, tracks => [
290               { title => "e1" },
291               { title => "e2" },
292               { title => "e3" },
293             ]},
294             { cdid => 1, genreid => 1, year => 1981, tracks => [
295               { title => "m1" },
296               { title => "m2" },
297               { title => "m3" },
298               { title => "m4" },
299             ]},
300             { cdid => 2, genreid => undef, year => 1976, tracks => [
301               { title => "o1" },
302               { title => "o2" },
303             ]},
304           ]
305         },
306       },
307     },
308     tracks => [
309       { cd => 3, title => "e1" },
310       { cd => 3, title => "e2" },
311       { cd => 3, title => "e3" },
312     ],
313   },
314   { year => 1981, single_track => undef, tracks => [
315     { cd => 1, title => "m1" },
316     { cd => 1, title => "m2" },
317     { cd => 1, title => "m3" },
318     { cd => 1, title => "m4" },
319   ]},
320 );
321
322 cmp_deeply (\@hris_all, \@hri_contents, 'W00T, multi-has_many manual underdefined root prefetch with collapse works');
323
324 cmp_deeply(
325   $rs->search({}, {
326     order_by => [ 'me.year', 'tracks_2.title', 'tracks.title', 'cds.cdid', { -desc => 'name' } ],
327     rows => 4,
328     offset => 2,
329   })->all_hri,
330   [ @hri_contents[2..5] ],
331   'multi-has_many prefetch with limit works too',
332 );
333
334 # left-ordered real iterator
335 $rs = $rs->search({}, { order_by => [ 'me.year', 'me.cdid', \ 'RANDOM()' ] });
336 my @objs_iter;
337 while (my $r = $rs->next) {
338   push @objs_iter, $r;
339 }
340
341 for my $i (0 .. $#objs_iter) {
342   is ($objs_iter[$i]->year, $hris_all[$i]{year}, "Expected year on object $i" );
343   is (
344     (defined $objs_iter[$i]->single_track),
345     (defined $hris_all[$i]{single_track}),
346     "Expected single relation on object $i"
347   );
348 }
349
350 $rs = $schema->resultset('Artist')->search({}, {
351   join => 'cds',
352   columns => ['cds.title', 'cds.artist' ],
353   collapse => 1,
354   order_by => [qw( me.name cds.title )],
355 });
356
357 $rs->create({ name => "${_}_cdless" })
358   for (qw( Z A ));
359
360 cmp_deeply (
361   $rs->all_hri,
362   [
363     { cds => [] },
364     { cds => [
365       { artist => 1, title => "Equinoxe" },
366       { artist => 1, title => "Magnetic Fields" },
367       { artist => 1, title => "Oxygene" },
368       { artist => 1, title => "fuzzy_1" },
369       { artist => 1, title => "fuzzy_2" },
370       { artist => 1, title => "fuzzy_3" },
371     ] },
372     { cds => [] },
373   ],
374   'Expected HRI of 1:M with empty root selection',
375 );
376
377 done_testing;