8 use DBIC::SqlMakerTest;
10 my $schema = DBICTest->init_schema();
11 my $sdebug = $schema->storage->debug;
14 my $cd = $schema->resultset("CD")->find(4);
15 my ($artist) = $cd->search_related('artist');
16 is($artist->name, 'Random Boy Band', 'has_a search_related ok');
18 # has_many test with an order_by clause defined
19 $artist = $schema->resultset("Artist")->find(1);
20 my @cds = $artist->search_related('cds');
21 is( $cds[1]->title, 'Spoonful of bees', 'has_many search_related with order_by ok' );
23 # search_related with additional abstract query
24 @cds = $artist->search_related('cds', { title => { like => '%of%' } } );
25 is( $cds[1]->title, 'Forkful of bees', 'search_related with abstract query ok' );
27 # creating a related object
28 $artist->create_related( 'cds', {
33 my $big_flop_cd = ($artist->search_related('cds'))[3];
34 is( $big_flop_cd->title, 'Big Flop', 'create_related ok' );
36 { # make sure we are not making pointless select queries when a FK IS NULL
38 $schema->storage->debugcb(sub { $queries++; });
39 $schema->storage->debug(1);
40 $big_flop_cd->genre; #should not trigger a select query
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');
44 $schema->storage->debug($sdebug);
45 $schema->storage->debugcb(undef);
48 my( $rs_from_list ) = $artist->search_related_rs('cds');
49 isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'search_related_rs in list context returns rs' );
51 ( $rs_from_list ) = $artist->cds_rs();
52 isa_ok( $rs_from_list, 'DBIx::Class::ResultSet', 'relation_rs in list context returns rs' );
55 is( $artist->count_related('cds'), 4, 'count_related ok' );
58 my $track = $schema->resultset("Track")->create( {
62 title => 'Hidden Track'
64 $track->set_from_related( cd => $cd );
67 ok(! $track->has_relationship( 'foo' ), 'Track has no relationship "foo"');
68 ok($track->has_relationship( 'disc' ), 'Track has relationship "disk"' );
70 is($track->disc->cdid, 4, 'set_from_related ok, including alternative accessor' );
72 $track->set_from_related( cd => undef );
74 ok( !defined($track->cd), 'set_from_related with undef ok');
76 $track = $schema->resultset("Track")->new( {} );
78 $track->set_from_related( cd => $cd );
79 ok ($track->cd, 'set_from_related ok after using the accessor' );
81 # update_from_related, the same as set_from_related, but it calls update afterwards
82 $track = $schema->resultset("Track")->create( {
85 title => 'Hidden Track 2'
87 $track->update_from_related( cd => $cd );
89 my $t_cd = ($schema->resultset("Track")->search({ cd => 4, title => 'Hidden Track 2' }))[0]->cd;
91 is( $t_cd->cdid, 4, 'update_from_related ok' );
93 # find_or_create_related with an existing record
94 $cd = $artist->find_or_create_related( 'cds', { title => 'Big Flop' } );
95 is( $cd->year, 2005, 'find_or_create_related on existing record ok' );
97 # find_or_create_related creating a new record
98 $cd = $artist->find_or_create_related( 'cds', {
99 title => 'Greatest Hits',
102 is( $cd->title, 'Greatest Hits', 'find_or_create_related new record ok' );
104 @cds = $artist->search_related('cds');
105 is( ($artist->search_related('cds'))[4]->title, 'Greatest Hits', 'find_or_create_related new record search ok' );
107 $artist->delete_related( cds => { title => 'Greatest Hits' });
108 cmp_ok( $schema->resultset("CD")->search({ title => 'Greatest Hits' }), '==', 0, 'delete_related ok' );
110 # find_or_new_related with an existing record
111 $cd = $artist->find_or_new_related( 'cds', { title => 'Big Flop' } );
112 is( $cd->year, 2005, 'find_or_new_related on existing record ok' );
113 ok( $cd->in_storage, 'find_or_new_related on existing record: is in_storage' );
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',
120 is( $cd->title, 'Greatest Hits 2: Louder Than Ever', 'find_or_new_related new record ok' );
121 is( $cd->in_storage, 0, 'find_or_new_related on a new record: not in_storage' );
124 my $newartist = $cd->find_or_new_related( 'artist', {
125 name => 'Random Boy Band Two',
128 is($newartist->name, 'Random Boy Band Two', 'find_or_new_related new artist record with id');
129 is($newartist->id, 200, 'find_or_new_related new artist id set');
133 my $new_bookmark = $schema->resultset("Bookmark")->new_result( {} );
134 my $new_related_link = $new_bookmark->new_related( 'link', {} );
141 local $TODO = "relationship checking needs fixing";
142 # try to add a bogus relationship using the wrong cols
144 DBICTest::Schema::Artist->add_relationship(
145 tracks => 'DBICTest::Schema::Track',
146 { 'foreign.cd' => 'self.cdid' }
148 } qr/Unknown column/, 'failed when creating a rel with invalid key, ok';
151 # another bogus relationship using no join condition
153 DBICTest::Schema::Artist->add_relationship( tracks => 'DBICTest::Track' );
154 } qr/join condition/, 'failed when creating a rel without join condition, ok';
156 # many_to_many helper tests
157 $cd = $schema->resultset("CD")->find(1);
158 my @producers = $cd->producers();
159 is( $producers[0]->name, 'Matt S Trout', 'many_to_many ok' );
160 is( $cd->producers_sorted->next->name, 'Bob The Builder',
161 'sorted many_to_many ok' );
162 is( $cd->producers_sorted({producerid => 3})->next->name, 'Fred The Phenotype',
163 'sorted many_to_many with search condition ok' );
165 $cd = $schema->resultset('CD')->find(2);
166 my $prod_rs = $cd->producers();
167 my $prod_before_count = $schema->resultset('Producer')->count;
168 is( $prod_rs->count, 0, "CD doesn't yet have any producers" );
169 my $prod = $schema->resultset('Producer')->find(1);
170 $cd->add_to_producers($prod);
171 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
172 is( $prod_rs->first->name, 'Matt S Trout',
173 'many_to_many add_to_$rel($obj) ok' );
174 $cd->remove_from_producers($prod);
175 $cd->add_to_producers($prod, {attribute => 1});
176 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj, $link_vals) count ok' );
177 is( $cd->cd_to_producer->first->attribute, 1, 'many_to_many $link_vals ok');
178 $cd->remove_from_producers($prod);
179 $cd->set_producers([$prod], {attribute => 2});
180 is( $prod_rs->count(), 1, 'many_to_many set_$rel($obj, $link_vals) count ok' );
181 is( $cd->cd_to_producer->first->attribute, 2, 'many_to_many $link_vals ok');
182 $cd->remove_from_producers($prod);
183 is( $schema->resultset('Producer')->find(1)->name, 'Matt S Trout',
184 "producer object exists after remove of link" );
185 is( $prod_rs->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
186 $cd->add_to_producers({ name => 'Testy McProducer' });
187 is( $schema->resultset('Producer')->count, $prod_before_count+1,
188 'add_to_$rel($hash) inserted a new producer' );
189 is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($hash) count ok' );
190 is( $prod_rs->first->name, 'Testy McProducer',
191 'many_to_many add_to_$rel($hash) ok' );
192 $cd->add_to_producers({ name => 'Jack Black' });
193 is( $prod_rs->count(), 2, 'many_to_many add_to_$rel($hash) count ok' );
194 $cd->set_producers($schema->resultset('Producer')->all);
195 is( $cd->producers->count(), $prod_before_count+2,
196 'many_to_many set_$rel(@objs) count ok' );
197 $cd->set_producers($schema->resultset('Producer')->find(1));
198 is( $cd->producers->count(), 1, 'many_to_many set_$rel($obj) count ok' );
199 $cd->set_producers([$schema->resultset('Producer')->all]);
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' );
206 $cd->remove_from_producers({ fake => 'hash' })
207 } qr/needs an object/, 'remove_from_$rel($hash) dies correctly';
210 $cd->add_to_producers()
211 } qr/needs an object or hashref/, 'add_to_$rel(undef) dies correctly';
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);
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' );
230 my $undef_artist_cd = $schema->resultset("CD")->new_result({ 'title' => 'badgers', 'year' => 2007 });
231 is($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');
234 $undef_artist_cd->related_resultset('artist')->new({name => 'foo'});
235 } 'Object created on a resultset related to not yet inserted object';
237 $schema->resultset('Artwork')->new_result({})->cd;
238 } 'undef_on_null_fk does not choke on empty conds';
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');
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');
250 $undir_maps->as_query,
252 SELECT artist_undirected_maps.id1, artist_undirected_maps.id2
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 = ? )
258 [[ { sqlt_datatype => 'integer', dbic_colname => 'artistid' }
260 'expected join sql produced',
263 $undir_maps = $schema->resultset("Artist")->find(2)->artist_undirected_maps;
264 is($undir_maps->count, 1, 'found 1 undirected map for artist 2');
266 my $mapped_rs = $undir_maps->search_related('mapped_artists');
268 my @art = $mapped_rs->all;
270 cmp_ok(@art, '==', 2, "Both artist returned from map");
272 my $searched = $mapped_rs->search({'mapped_artists.artistid' => {'!=', undef}});
274 cmp_ok($searched->count, '==', 2, "Both artist returned from map after adding another condition");
276 # check join through cascaded has_many relationships (also empty has_many rels)
277 $artist = $schema->resultset("Artist")->find(1);
278 my $trackset = $artist->cds->search_related('tracks');
279 is($trackset->count, 10, "Correct number of tracks for artist");
280 is($trackset->all, 10, "Correct number of track objects for artist");
282 # now see about updating eveything that belongs to artist 2 to artist 3
283 $artist = $schema->resultset("Artist")->find(2);
284 my $nartist = $schema->resultset("Artist")->find(3);
285 cmp_ok($artist->cds->count, '==', 1, "Correct orig #cds for artist");
286 cmp_ok($nartist->cds->count, '==', 1, "Correct orig #cds for artist");
287 $artist->cds->update({artist => $nartist->id});
288 cmp_ok($artist->cds->count, '==', 0, "Correct new #cds for artist");
289 cmp_ok($nartist->cds->count, '==', 2, "Correct new #cds for artist");
291 # check if is_foreign_key_constraint attr is set
292 my $rs_normal = $schema->source('Track');
293 my $relinfo = $rs_normal->relationship_info ('cd');
294 cmp_ok($relinfo->{attrs}{is_foreign_key_constraint}, '==', 1, "is_foreign_key_constraint defined for belongs_to relationships.");
296 my $rs_overridden = $schema->source('ForceForeign');
297 my $relinfo_with_attr = $rs_overridden->relationship_info ('cd_3');
298 cmp_ok($relinfo_with_attr->{attrs}{is_foreign_key_constraint}, '==', 0, "is_foreign_key_constraint defined for belongs_to relationships with attr.");
300 # check that relationships below left join relationships are forced to left joins
301 # when traversing multiple belongs_to
302 my $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => 'cd' } });
303 is($cds->count, 1, "subjoins under left joins force_left (string)");
305 $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => ['cd'] } });
306 is($cds->count, 1, "subjoins under left joins force_left (arrayref)");
308 $cds = $schema->resultset("CD")->search({ 'me.cdid' => 5 }, { join => { single_track => { cd => {} } } });
309 is($cds->count, 1, "subjoins under left joins force_left (hashref)");