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