rewrite of _collapse_result to support prefetch of multiple has_many
[dbsrgits/DBIx-Class.git] / t / prefetch / multiple_hasmany.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 IO::File;
9
10 my $schema = DBICTest->init_schema();
11 my $sdebug = $schema->storage->debug;
12
13 #( 1 -> M + M )
14 my $cd_rs = $schema->resultset('CD')->search( { 'me.title' => 'Forkful of bees' } );
15 my $pr_cd_rs = $cd_rs->search( {}, { prefetch => [qw/tracks tags/], } );
16
17 my $tracks_rs    = $cd_rs->first->tracks;
18 my $tracks_count = $tracks_rs->count;
19
20 my ( $pr_tracks_rs, $pr_tracks_count );
21
22 my $queries = 0;
23 $schema->storage->debugcb( sub { $queries++ } );
24 $schema->storage->debug(1);
25
26 my $o_mm_warn;
27 {
28     local $SIG{__WARN__} = sub { $o_mm_warn = shift };
29     $pr_tracks_rs = $pr_cd_rs->first->tracks;
30 };
31 $pr_tracks_count = $pr_tracks_rs->count;
32
33 ok( !$o_mm_warn,
34 'no warning on attempt to prefetch several same level has_many\'s (1 -> M + M)'
35 );
36
37 is( $queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query' );
38 $schema->storage->debugcb(undef);
39 $schema->storage->debug($sdebug);
40
41 is( $pr_tracks_count, $tracks_count,
42 'equal count of prefetched relations over several same level has_many\'s (1 -> M + M)'
43 );
44 is( $pr_tracks_rs->all, $tracks_rs->all,
45 'equal amount of objects returned with and without prefetch over several same level has_many\'s (1 -> M + M)'
46 );
47
48 #( M -> 1 -> M + M )
49 my $note_rs =
50   $schema->resultset('LinerNotes')->search( { notes => 'Buy Whiskey!' } );
51 my $pr_note_rs =
52   $note_rs->search( {}, { prefetch => { cd => [qw/tracks tags/] }, } );
53
54 my $tags_rs    = $note_rs->first->cd->tags;
55 my $tags_count = $tags_rs->count;
56
57 my ( $pr_tags_rs, $pr_tags_count );
58
59 $queries = 0;
60 $schema->storage->debugcb( sub { $queries++ } );
61 $schema->storage->debug(1);
62
63 my $m_o_mm_warn;
64 {
65     local $SIG{__WARN__} = sub { $m_o_mm_warn = shift };
66     $pr_tags_rs = $pr_note_rs->first->cd->tags;
67 };
68 $pr_tags_count = $pr_tags_rs->count;
69
70 ok( !$m_o_mm_warn,
71 'no warning on attempt to prefetch several same level has_many\'s (M -> 1 -> M + M)'
72 );
73
74 is( $queries, 1, 'prefetch one->(has_many,has_many) ran exactly 1 query' );
75 $schema->storage->debugcb(undef);
76 $schema->storage->debug($sdebug);
77
78 is( $pr_tags_count, $tags_count,
79 'equal count of prefetched relations over several same level has_many\'s (M -> 1 -> M + M)'
80 );
81 is( $pr_tags_rs->all, $tags_rs->all,
82 'equal amount of objects with and without prefetch over several same level has_many\'s (M -> 1 -> M + M)'
83 );
84
85 done_testing;