rewrite of _collapse_result to support prefetch of multiple has_many
[dbsrgits/DBIx-Class.git] / t / prefetch / with_limit.t
1 # Test to ensure we get a consistent result set wether or not we use the
2 # prefetch option in combination rows (LIMIT).
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Exception;
8 use lib qw(t/lib);
9 use DBICTest;
10
11 plan tests => 9;
12
13 my $schema = DBICTest->init_schema();
14
15
16 my $no_prefetch = $schema->resultset('Artist')->search(
17   [   # search deliberately contrived
18     { 'artwork.cd_id' => undef },
19     { 'tracks.title' => { '!=' => 'blah-blah-1234568' }}
20   ],
21   { rows => 3, join => { cds => [qw/artwork tracks/] },
22  }
23 );
24
25 my $use_prefetch = $no_prefetch->search(
26   {},
27   {
28     prefetch => 'cds',
29     order_by => { -desc => 'name' },
30   }
31 );
32
33 is($no_prefetch->count, $use_prefetch->count, '$no_prefetch->count == $use_prefetch->count');
34 is(
35   scalar ($no_prefetch->all),
36   scalar ($use_prefetch->all),
37   "Amount of returned rows is right"
38 );
39
40 my $artist_many_cds = $schema->resultset('Artist')->search ( {}, {
41   join => 'cds',
42   group_by => 'me.artistid',
43   having => \ 'count(cds.cdid) > 1',
44 })->first;
45
46
47 $no_prefetch = $schema->resultset('Artist')->search(
48   { artistid => $artist_many_cds->id },
49   { rows => 1 }
50 );
51
52 $use_prefetch = $no_prefetch->search ({}, { prefetch => 'cds' });
53
54 my $normal_artist = $no_prefetch->single;
55 my $prefetch_artist = $use_prefetch->find({ name => $artist_many_cds->name });
56 my $prefetch2_artist = $use_prefetch->first;
57
58 is(
59   $prefetch_artist->cds->count,
60   $normal_artist->cds->count,
61   "Count of child rel with prefetch + rows => 1 is right (find)"
62 );
63 is(
64   $prefetch2_artist->cds->count,
65   $normal_artist->cds->count,
66   "Count of child rel with prefetch + rows => 1 is right (first)"
67 );
68
69 is (
70   scalar ($prefetch_artist->cds->all),
71   scalar ($normal_artist->cds->all),
72   "Amount of child rel rows with prefetch + rows => 1 is right (find)"
73 );
74 is (
75   scalar ($prefetch2_artist->cds->all),
76   scalar ($normal_artist->cds->all),
77   "Amount of child rel rows with prefetch + rows => 1 is right (first)"
78 );
79
80 throws_ok (
81   sub { $use_prefetch->single },
82   qr/resultsets prefetching has_many/,
83   'single() with multiprefetch is illegal',
84 );
85
86 my $artist = $use_prefetch->search({'cds.title' => $artist_many_cds->cds->first->title })->next;
87 is($artist->cds->count, 1, "count on search limiting prefetched has_many");
88
89 # try with double limit
90 my $artist2 = $use_prefetch->search({'cds.title' => { '!=' => $artist_many_cds->cds->first->title } })->slice (0,0)->next;
91 is($artist2->cds->count, 2, "count on search limiting prefetched has_many");