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