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