Introduce 'any_null_means_no_value' option to eliminate wasteful queries. The option...
[dbsrgits/DBIx-Class.git] / t / 66relationship.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
9 my $schema = DBICTest->init_schema();
10
11 plan tests => 73;
12
13 # has_a test
14 my $cd = $schema->resultset("CD")->find(4);
15 my ($artist) = ($INC{'DBICTest/HelperRels'}
16                   ? $cd->artist
17                   : $cd->search_related('artist'));
18 is($artist->name, 'Random Boy Band', 'has_a search_related ok');
19
20 # has_many test with an order_by clause defined
21 $artist = $schema->resultset("Artist")->find(1);
22 my @cds = ($INC{'DBICTest/HelperRels'}
23              ? $artist->cds
24              : $artist->search_related('cds'));
25 is( $cds[1]->title, 'Spoonful of bees', 'has_many search_related with order_by ok' );
26
27 # search_related with additional abstract query
28 @cds = ($INC{'DBICTest/HelperRels'}
29           ? $artist->cds({ title => { like => '%of%' } })
30           : $artist->search_related('cds', { title => { like => '%of%' } } )
31        );
32 is( $cds[1]->title, 'Forkful of bees', 'search_related with abstract query ok' );
33
34 # creating a related object
35 if ($INC{'DBICTest/HelperRels.pm'}) {
36   $artist->add_to_cds({ title => 'Big Flop', year => 2005 });
37 } else {
38   $artist->create_related( 'cds', {
39       title => 'Big Flop',
40       year => 2005,
41   } );
42 }
43
44 my $big_flop_cd = ($artist->search_related('cds'))[3];
45 is( $big_flop_cd->title, 'Big Flop', 'create_related ok' );
46
47 { # make sure we are not making pointless select queries when a FK IS NULL
48   my $queries = 0;
49   $schema->storage->debugcb(sub { $queries++; });
50   $schema->storage->debug(1);
51   $big_flop_cd->genre; #should not trigger a select query
52   is($queries, 0, 'No Select made for belongs_to if key IS NULL');
53   $schema->storage->debug(0);
54   $schema->storage->debugcb(undef);
55 }
56
57 my( $rs_from_list ) = $artist->search_related_rs('cds');
58 is( ref($rs_from_list), 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
59
60 ( $rs_from_list ) = $artist->cds_rs();
61 is( ref($rs_from_list), 'DBIx::Class::ResultSet', 'relation_rs in list context returns rs' );
62
63 # count_related
64 is( $artist->count_related('cds'), 4, 'count_related ok' );
65
66 # set_from_related
67 my $track = $schema->resultset("Track")->create( {
68   trackid => 1,
69   cd => 3,
70   position => 98,
71   title => 'Hidden Track'
72 } );
73 $track->set_from_related( cd => $cd );
74
75 is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
76
77 $track->set_from_related( cd => undef );
78
79 ok( !defined($track->cd), 'set_from_related with undef ok');
80
81 TODO: {
82     local $TODO = 'accessing $object->rel and set_from_related';
83     my $track = $schema->resultset("Track")->new( {} );
84     $track->cd;
85     $track->set_from_related( cd => $cd ); 
86     ok ($track->cd, 'set_from_related ok after using the accessor' );
87 };
88
89 # update_from_related, the same as set_from_related, but it calls update afterwards
90 $track = $schema->resultset("Track")->create( {
91   trackid => 2,
92   cd => 3,
93   position => 99,
94   title => 'Hidden Track 2'
95 } );
96 $track->update_from_related( cd => $cd );
97
98 my $t_cd = ($schema->resultset("Track")->search( cd => 4, position => 99 ))[0]->cd;
99
100 is( $t_cd->cdid, 4, 'update_from_related ok' );
101
102 # find_or_create_related with an existing record
103 $cd = $artist->find_or_create_related( 'cds', { title => 'Big Flop' } );
104 is( $cd->year, 2005, 'find_or_create_related on existing record ok' );
105
106 # find_or_create_related creating a new record
107 $cd = $artist->find_or_create_related( 'cds', {
108   title => 'Greatest Hits',
109   year => 2006,
110 } );
111 is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
112
113 @cds = $artist->search_related('cds');
114 is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
115
116 $artist->delete_related( cds => { title => 'Greatest Hits' });
117 cmp_ok( $schema->resultset("CD")->search( title => 'Greatest Hits' ), '==', 0, 'delete_related ok' );
118
119 # find_or_new_related with an existing record
120 $cd = $artist->find_or_new_related( 'cds', { title => 'Big Flop' } );
121 is( $cd->year, 2005, 'find_or_new_related on existing record ok' );
122 ok( $cd->in_storage, 'find_or_new_related on existing record: is in_storage' );
123
124 # find_or_new_related instantiating a new record
125 $cd = $artist->find_or_new_related( 'cds', {
126   title => 'Greatest Hits 2: Louder Than Ever',
127   year => 2007,
128 } );
129 is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
130 ok( ! $cd->in_storage, 'find_or_new_related on a new record: not in_storage' );
131
132 $cd->artist(undef);
133 my $newartist = $cd->find_or_new_related( 'artist', {
134   name => 'Random Boy Band Two',
135   artistid => 200,
136 } );
137 is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
138 is($newartist->id, 200, 'find_or_new_related new artist id set');
139
140 TODO: {
141   local $TODO = "relationship checking needs fixing";
142   # try to add a bogus relationship using the wrong cols
143   eval {
144       DBICTest::Schema::Artist->add_relationship(
145           tracks => 'DBICTest::Schema::Track',
146           { 'foreign.cd' => 'self.cdid' }
147       );
148   };
149   like($@, qr/Unknown column/, 'failed when creating a rel with invalid key, ok');
150 }
151   
152 # another bogus relationship using no join condition
153 eval {
154     DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
155 };
156 like($@, qr/join condition/, 'failed when creating a rel without join condition, ok');
157
158 # many_to_many helper tests
159 $cd = $schema->resultset("CD")->find(1);
160 my @producers = $cd->producers();
161 is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
162 is( $cd->producers_sorted->next->name, 'Bob The Builder',
163     'sorted many_to_many ok' );
164 is( $cd->producers_sorted(producerid => 3)->next->name, 'Fred The Phenotype',
165     'sorted many_to_many with search condition ok' );
166
167 $cd = $schema->resultset('CD')->find(2);
168 my $prod_rs = $cd->producers();
169 my $prod_before_count = $schema->resultset('Producer')->count;
170 is( $prod_rs->count, 0, "CD doesn't yet have any producers" );
171 my $prod = $schema->resultset('Producer')->find(1);
172 $cd->add_to_producers($prod);
173 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
174 is( $prod_rs->first->name, 'Matt S Trout',
175     'many_to_many add_to_$rel($obj) ok' );
176 $cd->remove_from_producers($prod);
177 is( $schema->resultset('Producer')->find(1)->name, 'Matt S Trout',
178     "producer object exists after remove of link" );
179 is( $prod_rs->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
180 $cd->add_to_producers({ name => 'Testy McProducer' });
181 is( $schema->resultset('Producer')->count, $prod_before_count+1,
182     'add_to_$rel($hash) inserted a new producer' );
183 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($hash) count ok' );
184 is( $prod_rs->first->name, 'Testy McProducer',
185     'many_to_many add_to_$rel($hash) ok' );
186 $cd->add_to_producers({ name => 'Jack Black' });
187 is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
188 $cd->set_producers($schema->resultset('Producer')->all);
189 is( $cd->producers->count(), $prod_before_count+2, 
190     'many_to_many set_$rel(@objs) count ok' );
191 $cd->set_producers($schema->resultset('Producer')->find(1));
192 is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
193 $cd->set_producers([$schema->resultset('Producer')->all]);
194 is( $cd->producers->count(), $prod_before_count+2, 
195     'many_to_many set_$rel(\@objs) count ok' );
196 $cd->set_producers([$schema->resultset('Producer')->find(1)]);
197 is( $cd->producers->count(), 1, 'many_to_many set_$rel([$obj]) count ok' );
198
199 eval { $cd->remove_from_producers({ fake => 'hash' }); };
200 like( $@, qr/needs an object/, 'remove_from_$rel($hash) dies correctly' );
201
202 eval { $cd->add_to_producers(); };
203 like( $@, qr/needs an object or hashref/,
204       'add_to_$rel(undef) dies correctly' );
205
206 # many_to_many stresstest
207 my $twokey = $schema->resultset('TwoKeys')->find(1,1);
208 my $fourkey = $schema->resultset('FourKeys')->find(1,2,3,4);
209
210 is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
211 $twokey->add_to_fourkeys($fourkey, { autopilot => 'engaged' });
212 my $got_fourkey = $twokey->fourkeys({ sensors => 'online' })->first;
213 is( $twokey->fourkeys->count, 1, 'twokey has one fourkey' );
214 is( $got_fourkey->$_, $fourkey->$_,
215     'fourkeys row has the correct value for column '.$_ )
216   for (qw(foo bar hello goodbye sensors));
217 $twokey->remove_from_fourkeys($fourkey);
218 is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
219 is( $twokey->fourkeys_to_twokeys->count, 0,
220     'twokey has no links to fourkey' );
221
222 my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
223 is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
224 is($undef_artist_cd->search_related('artist')->count, 0, '0=1 search when FK does not exist and object not yet in db');
225 eval{ 
226      $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
227 };
228 is( $@, '', "Object created on a resultset related to not yet inserted object");
229  
230 my $def_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007, artist => undef });
231 is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
232 is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
233
234 # test undirected many-to-many relationship (e.g. "related artists")
235 my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
236 is($undir_maps->count, 1, 'found 1 undirected map for artist 1');
237
238 $undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
239 is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
240
241 my $mapped_rs = $undir_maps->search_related('mapped_artists');
242
243 my @art = $mapped_rs->all;
244
245 cmp_ok(@art, '==', 2, "Both artist returned from map");
246
247 my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
248
249 cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
250
251 # check join through cascaded has_many relationships
252 $artist = $schema->resultset("Artist")->find(1);
253 my $trackset = $artist->cds->search_related('tracks');
254 # LEFT join means we also see the trackless additional album...
255 cmp_ok($trackset->count, '==', 11, "Correct number of tracks for artist");
256
257 # now see about updating eveything that belongs to artist 2 to artist 3
258 $artist = $schema->resultset("Artist")->find(2);
259 my $nartist = $schema->resultset("Artist")->find(3);
260 cmp_ok($artist->cds->count, '==', 1, "Correct orig #cds for artist");
261 cmp_ok($nartist->cds->count, '==', 1, "Correct orig #cds for artist");
262 $artist->cds->update({artist => $nartist->id});
263 cmp_ok($artist->cds->count, '==', 0, "Correct new #cds for artist");
264 cmp_ok($nartist->cds->count, '==', 2, "Correct new #cds for artist");
265
266 my $new_artist = $schema->resultset("Artist")->new_result({ 'name' => 'Depeche Mode' });
267 my $new_related_cd = $new_artist->new_related('cds', { 'title' => 'Leave in Silence', 'year' => 1982});
268 eval {
269        $new_artist->insert;
270        $new_related_cd->insert;
271 };
272 is ($@, '', 'Staged insertion successful');
273 ok($new_artist->in_storage, 'artist inserted');
274 ok($new_related_cd->in_storage, 'new_related_cd inserted');
275
276 TODO: {
277 local $TODO = "TODOify for multicreate branch";
278 my $new_cd = $schema->resultset("CD")->new_result({});
279 my $new_related_artist = $new_cd->new_related('artist', { 'name' => 'Marillion',});
280 lives_ok (
281     sub {
282        $new_related_artist->insert;
283        $new_cd->title( 'Misplaced Childhood' );
284        $new_cd->year ( 1985 );
285 #       $new_cd->artist( $new_related_artist );  # For exact backward compatibility     # not sure what this means
286        $new_cd->insert;
287     },
288     'Reversed staged insertion successful'
289 );
290 ok($new_related_artist->in_storage, 'related artist inserted');
291 ok($new_cd->in_storage, 'cd inserted');
292
293 # check if is_foreign_key_constraint attr is set
294 my $rs_normal = $schema->source('Track');
295 my $relinfo = $rs_normal->relationship_info ('cd');
296 cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_constraint defined for belongs_to relationships.");
297
298 my $rs_overridden = $schema->source('ForceForeign');
299 my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
300 cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
301 }