Introduce 'any_null_means_no_value' option to eliminate wasteful queries. The option...
[dbsrgits/DBIx-Class.git] / t / 66relationship.t
CommitLineData
70350518 1use strict;
2f926160 2use warnings;
70350518 3
4b8dcc58 4use Test::More;
2f926160 5use Test::Exception;
4b8dcc58 6use lib qw(t/lib);
7use DBICTest;
8
a47e1233 9my $schema = DBICTest->init_schema();
5efe4c79 10
c89815db 11plan tests => 73;
0567538f 12
13# has_a test
f9db5527 14my $cd = $schema->resultset("CD")->find(4);
07037f89 15my ($artist) = ($INC{'DBICTest/HelperRels'}
16 ? $cd->artist
17 : $cd->search_related('artist'));
0567538f 18is($artist->name, 'Random Boy Band', 'has_a search_related ok');
19
20# has_many test with an order_by clause defined
f9db5527 21$artist = $schema->resultset("Artist")->find(1);
07037f89 22my @cds = ($INC{'DBICTest/HelperRels'}
23 ? $artist->cds
24 : $artist->search_related('cds'));
25is( $cds[1]->title, 'Spoonful of bees', 'has_many search_related with order_by ok' );
0567538f 26
27# search_related with additional abstract query
07037f89 28@cds = ($INC{'DBICTest/HelperRels'}
29 ? $artist->cds({ title => { like => '%of%' } })
30 : $artist->search_related('cds', { title => { like => '%of%' } } )
31 );
0567538f 32is( $cds[1]->title, 'Forkful of bees', 'search_related with abstract query ok' );
33
34# creating a related object
07037f89 35if ($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
c89815db 44my $big_flop_cd = ($artist->search_related('cds'))[3];
45is( $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}
0567538f 56
5b89a768 57my( $rs_from_list ) = $artist->search_related_rs('cds');
58is( ref($rs_from_list), 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
59
60( $rs_from_list ) = $artist->cds_rs();
61is( ref($rs_from_list), 'DBIx::Class::ResultSet', 'relation_rs in list context returns rs' );
62
0567538f 63# count_related
64is( $artist->count_related('cds'), 4, 'count_related ok' );
65
66# set_from_related
f9db5527 67my $track = $schema->resultset("Track")->create( {
0567538f 68 trackid => 1,
69 cd => 3,
70 position => 98,
71 title => 'Hidden Track'
72} );
73$track->set_from_related( cd => $cd );
74
70350518 75is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
0567538f 76
2c037e6b 77$track->set_from_related( cd => undef );
78
79ok( !defined($track->cd), 'set_from_related with undef ok');
80
f77bad73 81TODO: {
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};
2c037e6b 88
0567538f 89# update_from_related, the same as set_from_related, but it calls update afterwards
f9db5527 90$track = $schema->resultset("Track")->create( {
0567538f 91 trackid => 2,
92 cd => 3,
93 position => 99,
365d06b7 94 title => 'Hidden Track 2'
0567538f 95} );
96$track->update_from_related( cd => $cd );
97
f9db5527 98my $t_cd = ($schema->resultset("Track")->search( cd => 4, position => 99 ))[0]->cd;
0567538f 99
70350518 100is( $t_cd->cdid, 4, 'update_from_related ok' );
0567538f 101
102# find_or_create_related with an existing record
103$cd = $artist->find_or_create_related( 'cds', { title => 'Big Flop' } );
104is( $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} );
111is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
e02b9964 112
0567538f 113@cds = $artist->search_related('cds');
114is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
115
87772e46 116$artist->delete_related( cds => { title => 'Greatest Hits' });
f9db5527 117cmp_ok( $schema->resultset("CD")->search( title => 'Greatest Hits' ), '==', 0, 'delete_related ok' );
0567538f 118
b3e1f1f5 119# find_or_new_related with an existing record
120$cd = $artist->find_or_new_related( 'cds', { title => 'Big Flop' } );
121is( $cd->year, 2005, 'find_or_new_related on existing record ok' );
122ok( $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} );
129is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
130ok( ! $cd->in_storage, 'find_or_new_related on a new record: not in_storage' );
131
e02b9964 132$cd->artist(undef);
133my $newartist = $cd->find_or_new_related( 'artist', {
134 name => 'Random Boy Band Two',
135 artistid => 200,
136} );
e02b9964 137is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
138is($newartist->id, 200, 'find_or_new_related new artist id set');
139
a0dd8679 140TODO: {
141 local $TODO = "relationship checking needs fixing";
87772e46 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
0567538f 152# another bogus relationship using no join condition
153eval {
3712e4f4 154 DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
0567538f 155};
156like($@, qr/join condition/, 'failed when creating a rel without join condition, ok');
157
b3f358b5 158# many_to_many helper tests
f9db5527 159$cd = $schema->resultset("CD")->find(1);
7411204b 160my @producers = $cd->producers();
161is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
b3f358b5 162is( $cd->producers_sorted->next->name, 'Bob The Builder',
163 'sorted many_to_many ok' );
164is( $cd->producers_sorted(producerid => 3)->next->name, 'Fred The Phenotype',
165 'sorted many_to_many with search condition ok' );
7411204b 166
3a868fb2 167$cd = $schema->resultset('CD')->find(2);
b3f358b5 168my $prod_rs = $cd->producers();
169my $prod_before_count = $schema->resultset('Producer')->count;
170is( $prod_rs->count, 0, "CD doesn't yet have any producers" );
3a868fb2 171my $prod = $schema->resultset('Producer')->find(1);
172$cd->add_to_producers($prod);
3a868fb2 173is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
b3f358b5 174is( $prod_rs->first->name, 'Matt S Trout',
175 'many_to_many add_to_$rel($obj) ok' );
3a868fb2 176$cd->remove_from_producers($prod);
b3f358b5 177is( $schema->resultset('Producer')->find(1)->name, 'Matt S Trout',
178 "producer object exists after remove of link" );
179is( $prod_rs->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
303cf522 180$cd->add_to_producers({ name => 'Testy McProducer' });
b3f358b5 181is( $schema->resultset('Producer')->count, $prod_before_count+1,
182 'add_to_$rel($hash) inserted a new producer' );
303cf522 183is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($hash) count ok' );
b3f358b5 184is( $prod_rs->first->name, 'Testy McProducer',
185 'many_to_many add_to_$rel($hash) ok' );
186$cd->add_to_producers({ name => 'Jack Black' });
187is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
188$cd->set_producers($schema->resultset('Producer')->all);
189is( $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));
192is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
21c45f7b 193$cd->set_producers([$schema->resultset('Producer')->all]);
194is( $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)]);
197is( $cd->producers->count(), 1, 'many_to_many set_$rel([$obj]) count ok' );
303cf522 198
199eval { $cd->remove_from_producers({ fake => 'hash' }); };
200like( $@, qr/needs an object/, 'remove_from_$rel($hash) dies correctly' );
201
202eval { $cd->add_to_producers(); };
b3f358b5 203like( $@, qr/needs an object or hashref/,
204 'add_to_$rel(undef) dies correctly' );
303cf522 205
3bd6e3e0 206# many_to_many stresstest
207my $twokey = $schema->resultset('TwoKeys')->find(1,1);
208my $fourkey = $schema->resultset('FourKeys')->find(1,2,3,4);
209
210is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
211$twokey->add_to_fourkeys($fourkey, { autopilot => 'engaged' });
212my $got_fourkey = $twokey->fourkeys({ sensors => 'online' })->first;
213is( $twokey->fourkeys->count, 1, 'twokey has one fourkey' );
214is( $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);
218is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
b3f358b5 219is( $twokey->fourkeys_to_twokeys->count, 0,
220 'twokey has no links to fourkey' );
221
ac8a5ba4 222my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
223is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
370f2ba2 224is($undef_artist_cd->search_related('artist')->count, 0, '0=1 search when FK does not exist and object not yet in db');
2c5c07ec 225eval{
226 $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
227};
228is( $@, '', "Object created on a resultset related to not yet inserted object");
229
ac8a5ba4 230my $def_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007, artist => undef });
231is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
232is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
3a868fb2 233
5efe4c79 234# test undirected many-to-many relationship (e.g. "related artists")
f9db5527 235my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
5efe4c79 236is($undir_maps->count, 1, 'found 1 undirected map for artist 1');
237
f9db5527 238$undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
5efe4c79 239is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
240
ad3d2d7c 241my $mapped_rs = $undir_maps->search_related('mapped_artists');
242
243my @art = $mapped_rs->all;
5efe4c79 244
245cmp_ok(@art, '==', 2, "Both artist returned from map");
246
ad3d2d7c 247my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
248
249cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
250
b8d4bd90 251# check join through cascaded has_many relationships
252$artist = $schema->resultset("Artist")->find(1);
253my $trackset = $artist->cds->search_related('tracks');
254# LEFT join means we also see the trackless additional album...
255cmp_ok($trackset->count, '==', 11, "Correct number of tracks for artist");
ad3d2d7c 256
0f57d214 257# now see about updating eveything that belongs to artist 2 to artist 3
258$artist = $schema->resultset("Artist")->find(2);
259my $nartist = $schema->resultset("Artist")->find(3);
260cmp_ok($artist->cds->count, '==', 1, "Correct orig #cds for artist");
261cmp_ok($nartist->cds->count, '==', 1, "Correct orig #cds for artist");
262$artist->cds->update({artist => $nartist->id});
263cmp_ok($artist->cds->count, '==', 0, "Correct new #cds for artist");
264cmp_ok($nartist->cds->count, '==', 2, "Correct new #cds for artist");
265
8c368cf3 266my $new_artist = $schema->resultset("Artist")->new_result({ 'name' => 'Depeche Mode' });
8c368cf3 267my $new_related_cd = $new_artist->new_related('cds', { 'title' => 'Leave in Silence', 'year' => 1982});
268eval {
269 $new_artist->insert;
270 $new_related_cd->insert;
271};
4295b5d4 272is ($@, '', 'Staged insertion successful');
273ok($new_artist->in_storage, 'artist inserted');
274ok($new_related_cd->in_storage, 'new_related_cd inserted');
6bf6ba2f 275
a7be8807 276TODO: {
277local $TODO = "TODOify for multicreate branch";
2f926160 278my $new_cd = $schema->resultset("CD")->new_result({});
279my $new_related_artist = $new_cd->new_related('artist', { 'name' => 'Marillion',});
280lives_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);
290ok($new_related_artist->in_storage, 'related artist inserted');
291ok($new_cd->in_storage, 'cd inserted');
292
6bf6ba2f 293# check if is_foreign_key_constraint attr is set
294my $rs_normal = $schema->source('Track');
295my $relinfo = $rs_normal->relationship_info ('cd');
296cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_constraint defined for belongs_to relationships.");
297
298my $rs_overridden = $schema->source('ForceForeign');
299my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
300cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
a7be8807 301}