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