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