Explicitly test that prefetched rels get inflated by HRI
[dbsrgits/DBIx-Class.git] / t / inflate / hri.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 use DBIx::Class::_Util 'modver_gt_or_eq_and_lt';
9 use base();
10 BEGIN {
11   plan skip_all => 'base.pm 2.20 (only present in perl 5.19.7) is known to break this test'
12     if modver_gt_or_eq_and_lt( 'base', '2.19_01', '2.21' );
13 }
14
15 use Test::Exception;
16
17 use DBICTest;
18 my $schema = DBICTest->init_schema();
19
20 # Under some versions of SQLite if the $rs is left hanging around it will lock
21 # So we create a scope here cos I'm lazy
22 {
23     my $rs = $schema->resultset('CD')->search ({}, {
24         order_by => 'cdid',
25     });
26
27     my $orig_resclass = $rs->result_class;
28     eval "package DBICTest::CDSubclass; use base '$orig_resclass'";
29
30 # override on a specific $rs object, should not chain
31     $rs->result_class ('DBICTest::CDSubclass');
32
33     my $cd = $rs->find ({cdid => 1});
34     is (ref $cd, 'DBICTest::CDSubclass', 'result_class override propagates to find');
35
36     $cd = $rs->search({ cdid => 1 })->single;
37     is (ref $cd, $orig_resclass, 'result_class override does not propagate over seach+single');
38
39     $cd = $rs->search()->find ({ cdid => 1 });
40     is (ref $cd, $orig_resclass, 'result_class override does not propagate over seach+find');
41
42 # set as attr - should propagate
43     my $hri_rs = $rs->search ({}, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' });
44     is ($rs->result_class, 'DBICTest::CDSubclass', 'original class unchanged');
45     is ($hri_rs->result_class, 'DBIx::Class::ResultClass::HashRefInflator', 'result_class accessor pre-set via attribute');
46
47     my $datahashref1 = $hri_rs->next;
48     is_deeply(
49       [ sort keys %$datahashref1 ],
50       [ sort $rs->result_source->columns ],
51       'returned correct columns',
52     );
53     $hri_rs->reset;
54
55     $cd = $hri_rs->find ({cdid => 1});
56     is_deeply ( $cd, $datahashref1, 'first/find return the same thing (result_class attr propagates)');
57
58     $cd = $hri_rs->search({ cdid => 1 })->single;
59     is_deeply ( $cd, $datahashref1, 'first/search+single return the same thing (result_class attr propagates)');
60
61     $hri_rs->result_class ('DBIx::Class::Row'); # something bogus
62     is(
63         $hri_rs->search->result_class, 'DBIx::Class::ResultClass::HashRefInflator',
64         'result_class set using accessor does not propagate over unused search'
65     );
66
67 # test result class auto-loading
68     throws_ok (
69       sub { $rs->result_class ('nonexsitant_bogus_class') },
70       qr/Can't locate nonexsitant_bogus_class.pm/,
71       'Attempt to load on accessor override',
72     );
73     is ($rs->result_class, 'DBICTest::CDSubclass', 'class unchanged');
74
75     throws_ok (
76       sub { $rs->search ({}, { result_class => 'nonexsitant_bogus_class' }) },
77       qr/Can't locate nonexsitant_bogus_class.pm/,
78       'Attempt to load on accessor override',
79     );
80     is ($rs->result_class, 'DBICTest::CDSubclass', 'class unchanged');
81 }
82
83 sub check_cols_of {
84     my ($dbic_obj, $datahashref, $prefetch, $prefix) = @_;
85
86     $prefetch ||= [];
87     $prefix ||= '';
88     my %prefetch; @prefetch{@$prefetch} = ();
89
90     foreach my $col (keys %$datahashref) {
91         # plain column
92         if (not ref ($datahashref->{$col}) ) {
93             is ($datahashref->{$col}, $dbic_obj->get_column($col), "value for $prefix$col");
94         }
95         # related table entry (belongs_to)
96         elsif (ref ($datahashref->{$col}) eq 'HASH') {
97             delete $prefetch{$col};
98             check_cols_of($dbic_obj->$col, $datahashref->{$col}, [], "$col.");
99         }
100         # multiple related entries (has_many)
101         elsif (ref ($datahashref->{$col}) eq 'ARRAY') {
102             delete $prefetch{$col};
103             my @dbic_reltable = $dbic_obj->$col;
104             my @hashref_reltable = @{$datahashref->{$col}};
105
106             is (scalar @hashref_reltable, scalar @dbic_reltable, "number of related $col");
107
108             # for my $index (0..scalar @hashref_reltable) {
109             for my $index (0..scalar @dbic_reltable) {
110                 my $dbic_reltable_obj       = $dbic_reltable[$index];
111                 my $hashref_reltable_entry  = $hashref_reltable[$index];
112
113                 check_cols_of($dbic_reltable_obj, $hashref_reltable_entry, [], "$col\[$index\].");
114             }
115         }
116     }
117     if (@$prefetch) {
118         is 0+(keys %prefetch), 0, "prefetched " . join ", ", @$prefetch
119           or diag "missed: " . join ", ", keys %prefetch;
120     }
121 }
122
123 # create a cd without tracks for testing empty has_many relationship
124 $schema->resultset('CD')->create({ title => 'Silence is golden', artist => 3, year => 2006 });
125
126 # order_by to ensure both resultsets have the rows in the same order
127 # also check result_class-as-an-attribute syntax
128 my $rs_dbic = $schema->resultset('CD')->search(undef,
129     {
130         prefetch    => [ qw/ artist tracks / ],
131         order_by    => [ 'me.cdid', 'tracks.position' ],
132     }
133 );
134 my $rs_hashrefinf = $schema->resultset('CD')->search(undef,
135     {
136         prefetch    => [ qw/ artist tracks / ],
137         order_by    => [ 'me.cdid', 'tracks.position' ],
138         result_class => 'DBIx::Class::ResultClass::HashRefInflator',
139     }
140 );
141
142 my @dbic        = $rs_dbic->all;
143 my @hashrefinf  = $rs_hashrefinf->all;
144
145 for my $index (0 .. $#hashrefinf) {
146     my $dbic_obj    = $dbic[$index];
147     my $datahashref = $hashrefinf[$index];
148
149     check_cols_of($dbic_obj, $datahashref, [qw(artist tracks)]);
150 }
151
152 # sometimes for ultra-mega-speed you want to fetch columns in esoteric ways
153 # check the inflator over a non-fetching join
154 $rs_dbic = $schema->resultset ('Artist')->search ({ 'me.artistid' => 1}, {
155     prefetch => { cds => 'tracks' },
156     order_by => [qw/cds.cdid tracks.trackid/],
157 });
158
159 $rs_hashrefinf = $schema->resultset ('Artist')->search ({ 'me.artistid' => 1}, {
160     join     => { cds => 'tracks' },
161     select   => [qw/name   tracks.title      tracks.cd       /],
162     as       => [qw/name   cds.tracks.title  cds.tracks.cd   /],
163     order_by => [qw/cds.cdid tracks.trackid/],
164     result_class => 'DBIx::Class::ResultClass::HashRefInflator',
165 });
166
167 @dbic = map { $_->tracks->all } ($rs_dbic->first->cds->all);
168 @hashrefinf  = $rs_hashrefinf->all;
169
170 is (scalar @dbic, scalar @hashrefinf, 'Equal number of tracks fetched');
171
172 for my $index (0 .. $#hashrefinf) {
173     my $track       = $dbic[$index];
174     my $datahashref = $hashrefinf[$index];
175
176     is ($track->cd->artist->name, $datahashref->{name}, 'Brought back correct artist');
177     for my $col (keys %{$datahashref->{cds}{tracks}}) {
178         is ($track->get_column ($col), $datahashref->{cds}{tracks}{$col}, "Correct track '$col'");
179     }
180 }
181
182 # check for same query as above but using extended columns syntax
183 $rs_hashrefinf = $schema->resultset ('Artist')->search ({ 'me.artistid' => 1}, {
184     join     => { cds => 'tracks' },
185     columns  => {name => 'name', 'cds.tracks.title' => 'tracks.title', 'cds.tracks.cd' => 'tracks.cd'},
186     order_by => [qw/cds.cdid tracks.trackid/],
187 });
188 $rs_hashrefinf->result_class('DBIx::Class::ResultClass::HashRefInflator');
189 is_deeply [$rs_hashrefinf->all], \@hashrefinf, 'Check query using extended columns syntax';
190
191 # check nested prefetching of has_many relationships which return nothing
192 my $artist = $schema->resultset ('Artist')->create ({ name => 'unsuccessful artist without CDs'});
193 $artist->discard_changes;
194 my $rs_artists = $schema->resultset ('Artist')->search ({ 'me.artistid' => $artist->id}, {
195     prefetch => { cds => 'tracks' }, result_class => 'DBIx::Class::ResultClass::HashRefInflator',
196 });
197 is_deeply(
198   [$rs_artists->all],
199   [{ $artist->get_columns, cds => [] }],
200   'nested has_many prefetch without entries'
201 );
202
203 done_testing;
204