Merge 'sybase_insert_bulk' into 'sybase_support'
[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
9 my $schema = DBICTest->init_schema();
10 my $sdebug = $schema->storage->debug;
11
12 plan tests => 79;
13
14 # has_a test
15 my $cd = $schema->resultset("CD")->find(4);
16 my ($artist) = ($INC{'DBICTest/HelperRels'}
17                   ? $cd->artist
18                   : $cd->search_related('artist'));
19 is($artist->name, 'Random Boy Band', 'has_a search_related ok');
20
21 # has_many test with an order_by clause defined
22 $artist = $schema->resultset("Artist")->find(1);
23 my @cds = ($INC{'DBICTest/HelperRels'}
24              ? $artist->cds
25              : $artist->search_related('cds'));
26 is( $cds[1]->title, 'Spoonful of bees', 'has_many search_related with order_by ok' );
27
28 # search_related with additional abstract query
29 @cds = ($INC{'DBICTest/HelperRels'}
30           ? $artist->cds({ title => { like => '%of%' } })
31           : $artist->search_related('cds', { title => { like => '%of%' } } )
32        );
33 is( $cds[1]->title, 'Forkful of bees', 'search_related with abstract query ok' );
34
35 # creating a related object
36 if ($INC{'DBICTest/HelperRels.pm'}) {
37   $artist->add_to_cds({ title => 'Big Flop', year => 2005 });
38 } else {
39   my $big_flop = $artist->create_related( 'cds', {
40       title => 'Big Flop',
41       year => 2005,
42   } );
43
44  TODO: {
45     local $TODO = "Can't fix right now" if $DBIx::Class::VERSION < 0.09;
46     lives_ok { $big_flop->genre} "Don't throw exception when col is not loaded after insert";
47   };
48 }
49
50 my $big_flop_cd = ($artist->search_related('cds'))[3];
51 is( $big_flop_cd->title, 'Big Flop', 'create_related ok' );
52
53 { # make sure we are not making pointless select queries when a FK IS NULL
54   my $queries = 0;
55   $schema->storage->debugcb(sub { $queries++; });
56   $schema->storage->debug(1);
57   $big_flop_cd->genre; #should not trigger a select query
58   is($queries, 0, 'No SELECT made for belongs_to if key IS NULL');
59   $big_flop_cd->genre_inefficient; #should trigger a select query
60   is($queries, 1, 'SELECT made for belongs_to if key IS NULL when undef_on_null_fk disabled');
61   $schema->storage->debug($sdebug);
62   $schema->storage->debugcb(undef);
63 }
64
65 my( $rs_from_list ) = $artist->search_related_rs('cds');
66 isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
67
68 ( $rs_from_list ) = $artist->cds_rs();
69 isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'relation_rs in list context returns rs' );
70
71 # count_related
72 is( $artist->count_related('cds'), 4, 'count_related ok' );
73
74 # set_from_related
75 my $track = $schema->resultset("Track")->create( {
76   trackid => 1,
77   cd => 3,
78   position => 98,
79   title => 'Hidden Track'
80 } );
81 $track->set_from_related( cd => $cd );
82
83 is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
84
85 $track->set_from_related( cd => undef );
86
87 ok( !defined($track->cd), 'set_from_related with undef ok');
88
89 TODO: {
90     local $TODO = 'accessing $object->rel and set_from_related';
91     my $track = $schema->resultset("Track")->new( {} );
92     $track->cd;
93     $track->set_from_related( cd => $cd ); 
94     ok ($track->cd, 'set_from_related ok after using the accessor' );
95 };
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 ok( ! $cd->in_storage, '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   eval {
160       DBICTest::Schema::Artist->add_relationship(
161           tracks => 'DBICTest::Schema::Track',
162           { 'foreign.cd' => 'self.cdid' }
163       );
164   };
165   like($@, qr/Unknown column/, 'failed when creating a rel with invalid key, ok');
166 }
167   
168 # another bogus relationship using no join condition
169 eval {
170     DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
171 };
172 like($@, qr/join condition/, 'failed when creating a rel without join condition, ok');
173
174 # many_to_many helper tests
175 $cd = $schema->resultset("CD")->find(1);
176 my @producers = $cd->producers();
177 is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
178 is( $cd->producers_sorted->next->name, 'Bob The Builder',
179     'sorted many_to_many ok' );
180 is( $cd->producers_sorted(producerid => 3)->next->name, 'Fred The Phenotype',
181     'sorted many_to_many with search condition ok' );
182
183 $cd = $schema->resultset('CD')->find(2);
184 my $prod_rs = $cd->producers();
185 my $prod_before_count = $schema->resultset('Producer')->count;
186 is( $prod_rs->count, 0, "CD doesn't yet have any producers" );
187 my $prod = $schema->resultset('Producer')->find(1);
188 $cd->add_to_producers($prod);
189 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
190 is( $prod_rs->first->name, 'Matt S Trout',
191     'many_to_many add_to_$rel($obj) ok' );
192 $cd->remove_from_producers($prod);
193 $cd->add_to_producers($prod, {attribute => 1});
194 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj, $link_vals) count ok' );
195 is( $cd->cd_to_producer->first->attribute, 1, 'many_to_many $link_vals ok');
196 $cd->remove_from_producers($prod);
197 $cd->set_producers([$prod], {attribute => 2});
198 is( $prod_rs->count(), 1, 'many_to_many set_$rel($obj, $link_vals) count ok' );
199 is( $cd->cd_to_producer->first->attribute, 2, 'many_to_many $link_vals ok');
200 $cd->remove_from_producers($prod);
201 is( $schema->resultset('Producer')->find(1)->name, 'Matt S Trout',
202     "producer object exists after remove of link" );
203 is( $prod_rs->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
204 $cd->add_to_producers({ name => 'Testy McProducer' });
205 is( $schema->resultset('Producer')->count, $prod_before_count+1,
206     'add_to_$rel($hash) inserted a new producer' );
207 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($hash) count ok' );
208 is( $prod_rs->first->name, 'Testy McProducer',
209     'many_to_many add_to_$rel($hash) ok' );
210 $cd->add_to_producers({ name => 'Jack Black' });
211 is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
212 $cd->set_producers($schema->resultset('Producer')->all);
213 is( $cd->producers->count(), $prod_before_count+2, 
214     'many_to_many set_$rel(@objs) count ok' );
215 $cd->set_producers($schema->resultset('Producer')->find(1));
216 is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
217 $cd->set_producers([$schema->resultset('Producer')->all]);
218 is( $cd->producers->count(), $prod_before_count+2, 
219     'many_to_many set_$rel(\@objs) count ok' );
220 $cd->set_producers([$schema->resultset('Producer')->find(1)]);
221 is( $cd->producers->count(), 1, 'many_to_many set_$rel([$obj]) count ok' );
222
223 eval { $cd->remove_from_producers({ fake => 'hash' }); };
224 like( $@, qr/needs an object/, 'remove_from_$rel($hash) dies correctly' );
225
226 eval { $cd->add_to_producers(); };
227 like( $@, qr/needs an object or hashref/,
228       'add_to_$rel(undef) dies correctly' );
229
230 # many_to_many stresstest
231 my $twokey = $schema->resultset('TwoKeys')->find(1,1);
232 my $fourkey = $schema->resultset('FourKeys')->find(1,2,3,4);
233
234 is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
235 $twokey->add_to_fourkeys($fourkey, { autopilot => 'engaged' });
236 my $got_fourkey = $twokey->fourkeys({ sensors => 'online' })->first;
237 is( $twokey->fourkeys->count, 1, 'twokey has one fourkey' );
238 is( $got_fourkey->$_, $fourkey->$_,
239     'fourkeys row has the correct value for column '.$_ )
240   for (qw(foo bar hello goodbye sensors));
241 $twokey->remove_from_fourkeys($fourkey);
242 is( $twokey->fourkeys->count, 0, 'twokey has no fourkeys' );
243 is( $twokey->fourkeys_to_twokeys->count, 0,
244     'twokey has no links to fourkey' );
245
246
247 my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
248 is($undef_artist_cd->has_column_loaded('artist'), '', 'FK not loaded');
249 is($undef_artist_cd->search_related('artist')->count, 0, '0=1 search when FK does not exist and object not yet in db');
250 eval{ 
251      $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
252 };
253 is( $@, '', "Object created on a resultset related to not yet inserted object");
254 lives_ok{
255   $schema->resultset('Artwork')->new_result({})->cd;
256 } 'undef_on_null_fk does not choke on empty conds';
257
258 my $def_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007, artist => undef });
259 is($def_artist_cd->has_column_loaded('artist'), 1, 'FK loaded');
260 is($def_artist_cd->search_related('artist')->count, 0, 'closed search on null FK');
261
262 # test undirected many-to-many relationship (e.g. "related artists")
263 my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
264 is($undir_maps->count, 1, 'found 1 undirected map for artist 1');
265
266 $undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
267 is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
268
269 my $mapped_rs = $undir_maps->search_related('mapped_artists');
270
271 my @art = $mapped_rs->all;
272
273 cmp_ok(@art, '==', 2, "Both artist returned from map");
274
275 my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
276
277 cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
278
279 # check join through cascaded has_many relationships (also empty has_many rels)
280 $artist = $schema->resultset("Artist")->find(1);
281 my $trackset = $artist->cds->search_related('tracks');
282 is($trackset->count, 10, "Correct number of tracks for artist");
283 is($trackset->all, 10, "Correct number of track objects for artist");
284
285 # now see about updating eveything that belongs to artist 2 to artist 3
286 $artist = $schema->resultset("Artist")->find(2);
287 my $nartist = $schema->resultset("Artist")->find(3);
288 cmp_ok($artist->cds->count, '==', 1, "Correct orig #cds for artist");
289 cmp_ok($nartist->cds->count, '==', 1, "Correct orig #cds for artist");
290 $artist->cds->update({artist => $nartist->id});
291 cmp_ok($artist->cds->count, '==', 0, "Correct new #cds for artist");
292 cmp_ok($nartist->cds->count, '==', 2, "Correct new #cds for artist");
293
294 # check if is_foreign_key_constraint attr is set
295 my $rs_normal = $schema->source('Track');
296 my $relinfo = $rs_normal->relationship_info ('cd');
297 cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_constraint defined for belongs_to relationships.");
298
299 my $rs_overridden = $schema->source('ForceForeign');
300 my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
301 cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
302
303 # check that relationships below left join relationships are forced to left joins 
304 # when traversing multiple belongs_to
305 my $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => 'cd' } });
306 is($cds->count, 1, "subjoins under left joins force_left (string)");
307
308 $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => ['cd'] } });
309 is($cds->count, 1, "subjoins under left joins force_left (arrayref)");
310
311 $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => { cd => {} } } });
312 is($cds->count, 1, "subjoins under left joins force_left (hashref)");