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