Remove TODO that could never be made to work (revert c49fcf72)
[dbsrgits/DBIx-Class.git] / t / relationship / core.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;
af439a0e 8use DBIC::SqlMakerTest;
4b8dcc58 9
a47e1233 10my $schema = DBICTest->init_schema();
a2287768 11my $sdebug = $schema->storage->debug;
5efe4c79 12
0567538f 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 {
c49fcf72 38 my $big_flop = $artist->create_related( 'cds', {
07037f89 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
cef1bdda 52 is($queries, 0, 'No SELECT made for belongs_to if key IS NULL');
53 $big_flop_cd->genre_inefficient; #should trigger a select query
54 is($queries, 1, 'SELECT made for belongs_to if key IS NULL when undef_on_null_fk disabled');
a2287768 55 $schema->storage->debug($sdebug);
c89815db 56 $schema->storage->debugcb(undef);
57}
0567538f 58
5b89a768 59my( $rs_from_list ) = $artist->search_related_rs('cds');
660cf1be 60isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
5b89a768 61
62( $rs_from_list ) = $artist->cds_rs();
660cf1be 63isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'relation_rs in list context returns rs' );
5b89a768 64
0567538f 65# count_related
66is( $artist->count_related('cds'), 4, 'count_related ok' );
67
68# set_from_related
f9db5527 69my $track = $schema->resultset("Track")->create( {
0567538f 70 trackid => 1,
71 cd => 3,
72 position => 98,
73 title => 'Hidden Track'
74} );
75$track->set_from_related( cd => $cd );
76
0818c9a7 77# has_relationship
78ok(! $track->has_relationship( 'foo' ), 'Track has no relationship "foo"');
79ok($track->has_relationship( 'disc' ), 'Track has relationship "disk"' );
80
70350518 81is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
0567538f 82
2c037e6b 83$track->set_from_related( cd => undef );
84
85ok( !defined($track->cd), 'set_from_related with undef ok');
86
35f5c265 87$track = $schema->resultset("Track")->new( {} );
88$track->cd;
8273e845 89$track->set_from_related( cd => $cd );
35f5c265 90ok ($track->cd, 'set_from_related ok after using the accessor' );
2c037e6b 91
0567538f 92# update_from_related, the same as set_from_related, but it calls update afterwards
f9db5527 93$track = $schema->resultset("Track")->create( {
0567538f 94 trackid => 2,
95 cd => 3,
365d06b7 96 title => 'Hidden Track 2'
0567538f 97} );
98$track->update_from_related( cd => $cd );
99
450e6dbf 100my $t_cd = ($schema->resultset("Track")->search({ cd => 4, title => 'Hidden Track 2' }))[0]->cd;
0567538f 101
70350518 102is( $t_cd->cdid, 4, 'update_from_related ok' );
0567538f 103
104# find_or_create_related with an existing record
105$cd = $artist->find_or_create_related( 'cds', { title => 'Big Flop' } );
106is( $cd->year, 2005, 'find_or_create_related on existing record ok' );
107
108# find_or_create_related creating a new record
109$cd = $artist->find_or_create_related( 'cds', {
110 title => 'Greatest Hits',
111 year => 2006,
112} );
113is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
e02b9964 114
0567538f 115@cds = $artist->search_related('cds');
116is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
117
87772e46 118$artist->delete_related( cds => { title => 'Greatest Hits' });
450e6dbf 119cmp_ok( $schema->resultset("CD")->search({ title => 'Greatest Hits' }), '==', 0, 'delete_related ok' );
0567538f 120
b3e1f1f5 121# find_or_new_related with an existing record
122$cd = $artist->find_or_new_related( 'cds', { title => 'Big Flop' } );
123is( $cd->year, 2005, 'find_or_new_related on existing record ok' );
124ok( $cd->in_storage, 'find_or_new_related on existing record: is in_storage' );
125
126# find_or_new_related instantiating a new record
127$cd = $artist->find_or_new_related( 'cds', {
128 title => 'Greatest Hits 2: Louder Than Ever',
129 year => 2007,
130} );
131is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
63bb9738 132is( $cd->in_storage, 0, 'find_or_new_related on a new record: not in_storage' );
b3e1f1f5 133
e02b9964 134$cd->artist(undef);
135my $newartist = $cd->find_or_new_related( 'artist', {
136 name => 'Random Boy Band Two',
137 artistid => 200,
138} );
e02b9964 139is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
140is($newartist->id, 200, 'find_or_new_related new artist id set');
141
8273e845 142lives_ok(
143 sub {
f623c6ee 144 my $new_bookmark = $schema->resultset("Bookmark")->new_result( {} );
145 my $new_related_link = $new_bookmark->new_related( 'link', {} );
146 },
147 'No back rel'
148);
149
150
4ca1fd6f 151{
a0dd8679 152 local $TODO = "relationship checking needs fixing";
87772e46 153 # try to add a bogus relationship using the wrong cols
4017fe64 154 throws_ok {
87772e46 155 DBICTest::Schema::Artist->add_relationship(
156 tracks => 'DBICTest::Schema::Track',
157 { 'foreign.cd' => 'self.cdid' }
158 );
4017fe64 159 } qr/Unknown column/, 'failed when creating a rel with invalid key, ok';
87772e46 160}
4017fe64 161
0567538f 162# another bogus relationship using no join condition
4017fe64 163throws_ok {
3712e4f4 164 DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
4017fe64 165} qr/join condition/, 'failed when creating a rel without join condition, ok';
0567538f 166
b3f358b5 167# many_to_many helper tests
f9db5527 168$cd = $schema->resultset("CD")->find(1);
7411204b 169my @producers = $cd->producers();
170is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
b3f358b5 171is( $cd->producers_sorted->next->name, 'Bob The Builder',
172 'sorted many_to_many ok' );
450e6dbf 173is( $cd->producers_sorted({producerid => 3})->next->name, 'Fred The Phenotype',
b3f358b5 174 'sorted many_to_many with search condition ok' );
7411204b 175
3a868fb2 176$cd = $schema->resultset('CD')->find(2);
b3f358b5 177my $prod_rs = $cd->producers();
178my $prod_before_count = $schema->resultset('Producer')->count;
179is( $prod_rs->count, 0, "CD doesn't yet have any producers" );
3a868fb2 180my $prod = $schema->resultset('Producer')->find(1);
181$cd->add_to_producers($prod);
3a868fb2 182is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
b3f358b5 183is( $prod_rs->first->name, 'Matt S Trout',
184 'many_to_many add_to_$rel($obj) ok' );
3a868fb2 185$cd->remove_from_producers($prod);
ac36a402 186$cd->add_to_producers($prod, {attribute => 1});
187is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj, $link_vals) count ok' );
188is( $cd->cd_to_producer->first->attribute, 1, 'many_to_many $link_vals ok');
189$cd->remove_from_producers($prod);
190$cd->set_producers([$prod], {attribute => 2});
191is( $prod_rs->count(), 1, 'many_to_many set_$rel($obj, $link_vals) count ok' );
192is( $cd->cd_to_producer->first->attribute, 2, 'many_to_many $link_vals ok');
193$cd->remove_from_producers($prod);
b3f358b5 194is( $schema->resultset('Producer')->find(1)->name, 'Matt S Trout',
195 "producer object exists after remove of link" );
196is( $prod_rs->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
303cf522 197$cd->add_to_producers({ name => 'Testy McProducer' });
b3f358b5 198is( $schema->resultset('Producer')->count, $prod_before_count+1,
199 'add_to_$rel($hash) inserted a new producer' );
303cf522 200is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($hash) count ok' );
b3f358b5 201is( $prod_rs->first->name, 'Testy McProducer',
202 'many_to_many add_to_$rel($hash) ok' );
203$cd->add_to_producers({ name => 'Jack Black' });
204is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
205$cd->set_producers($schema->resultset('Producer')->all);
8273e845 206is( $cd->producers->count(), $prod_before_count+2,
b3f358b5 207 'many_to_many set_$rel(@objs) count ok' );
208$cd->set_producers($schema->resultset('Producer')->find(1));
209is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
21c45f7b 210$cd->set_producers([$schema->resultset('Producer')->all]);
8273e845 211is( $cd->producers->count(), $prod_before_count+2,
21c45f7b 212 'many_to_many set_$rel(\@objs) count ok' );
213$cd->set_producers([$schema->resultset('Producer')->find(1)]);
214is( $cd->producers->count(), 1, 'many_to_many set_$rel([$obj]) count ok' );
303cf522 215
4017fe64 216throws_ok {
217 $cd->remove_from_producers({ fake => 'hash' })
218} qr/needs an object/, 'remove_from_$rel($hash) dies correctly';
303cf522 219
4017fe64 220throws_ok {
221 $cd->add_to_producers()
222} qr/needs an object or hashref/, 'add_to_$rel(undef) dies correctly';
303cf522 223
3bd6e3e0 224# many_to_many stresstest
225my $twokey = $schema->resultset('TwoKeys')->find(1,1);
226my $fourkey = $schema->resultset('FourKeys')->find(1,2,3,4);
227
228is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
229$twokey->add_to_fourkeys($fourkey, { autopilot => 'engaged' });
230my $got_fourkey = $twokey->fourkeys({ sensors => 'online' })->first;
231is( $twokey->fourkeys->count, 1, 'twokey has one fourkey' );
232is( $got_fourkey->$_, $fourkey->$_,
233 'fourkeys row has the correct value for column '.$_ )
234 for (qw(foo bar hello goodbye sensors));
235$twokey->remove_from_fourkeys($fourkey);
236is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
b3f358b5 237is( $twokey->fourkeys_to_twokeys->count, 0,
238 'twokey has no links to fourkey' );
239
ac36a402 240
ac8a5ba4 241my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
242is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
370f2ba2 243is($undef_artist_cd->search_related('artist')->count, 0, '0=1 search when FK does not exist and object not yet in db');
4017fe64 244lives_ok {
2c5c07ec 245 $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
4017fe64 246} 'Object created on a resultset related to not yet inserted object';
981299aa 247lives_ok{
248 $schema->resultset('Artwork')->new_result({})->cd;
249} 'undef_on_null_fk does not choke on empty conds';
250
ac8a5ba4 251my $def_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007, artist => undef });
252is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
253is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
3a868fb2 254
5efe4c79 255# test undirected many-to-many relationship (e.g. "related artists")
af439a0e 256my $undir_maps = $schema->resultset("Artist")
257 ->search ({artistid => 1})
258 ->search_related ('artist_undirected_maps');
5efe4c79 259is($undir_maps->count, 1, 'found 1 undirected map for artist 1');
af439a0e 260is_same_sql_bind (
261 $undir_maps->as_query,
262 '(
263 SELECT artist_undirected_maps.id1, artist_undirected_maps.id2
264 FROM artist me
95c73ab2 265 JOIN artist_undirected_map artist_undirected_maps
af439a0e 266 ON artist_undirected_maps.id1 = me.artistid OR artist_undirected_maps.id2 = me.artistid
267 WHERE ( artistid = ? )
268 )',
0e773352 269 [[ { sqlt_datatype => 'integer', dbic_colname => 'artistid' }
270 => 1 ]],
af439a0e 271 'expected join sql produced',
272);
5efe4c79 273
f9db5527 274$undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
5efe4c79 275is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
276
ad3d2d7c 277my $mapped_rs = $undir_maps->search_related('mapped_artists');
278
279my @art = $mapped_rs->all;
5efe4c79 280
281cmp_ok(@art, '==', 2, "Both artist returned from map");
282
ad3d2d7c 283my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
284
285cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
286
597508e8 287# check join through cascaded has_many relationships (also empty has_many rels)
b8d4bd90 288$artist = $schema->resultset("Artist")->find(1);
289my $trackset = $artist->cds->search_related('tracks');
597508e8 290is($trackset->count, 10, "Correct number of tracks for artist");
291is($trackset->all, 10, "Correct number of track objects for artist");
ad3d2d7c 292
0f57d214 293# now see about updating eveything that belongs to artist 2 to artist 3
294$artist = $schema->resultset("Artist")->find(2);
295my $nartist = $schema->resultset("Artist")->find(3);
296cmp_ok($artist->cds->count, '==', 1, "Correct orig #cds for artist");
297cmp_ok($nartist->cds->count, '==', 1, "Correct orig #cds for artist");
298$artist->cds->update({artist => $nartist->id});
299cmp_ok($artist->cds->count, '==', 0, "Correct new #cds for artist");
300cmp_ok($nartist->cds->count, '==', 2, "Correct new #cds for artist");
301
6bf6ba2f 302# check if is_foreign_key_constraint attr is set
303my $rs_normal = $schema->source('Track');
304my $relinfo = $rs_normal->relationship_info ('cd');
305cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_constraint defined for belongs_to relationships.");
306
307my $rs_overridden = $schema->source('ForceForeign');
308my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
309cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
caac1708 310
8273e845 311# check that relationships below left join relationships are forced to left joins
56b73f83 312# when traversing multiple belongs_to
313my $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => 'cd' } });
caac1708 314is($cds->count, 1, "subjoins under left joins force_left (string)");
315
56b73f83 316$cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => ['cd'] } });
caac1708 317is($cds->count, 1, "subjoins under left joins force_left (arrayref)");
318
56b73f83 319$cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => { cd => {} } } });
caac1708 320is($cds->count, 1, "subjoins under left joins force_left (hashref)");
af439a0e 321
322done_testing;