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