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