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