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