Expand (and complicate) m2m test from e98e6478
[dbsrgits/DBIx-Class-Historic.git] / t / relationship / custom.t
CommitLineData
b5c8410c 1use strict;
2use warnings;
3
4use Test::More;
5use Test::Exception;
c200d949 6use Test::Warn;
b5c8410c 7use lib qw(t/lib);
a5a7bb73 8use DBICTest ':DiffSQL';
b5c8410c 9
10my $schema = DBICTest->init_schema();
11
abf8d91e 12$schema->resultset('Artist')->delete;
13$schema->resultset('CD')->delete;
14
15my $artist = $schema->resultset("Artist")->create({ artistid => 21, name => 'Michael Jackson', rank => 20 });
16my $artist2 = $schema->resultset("Artist")->create({ artistid => 22, name => 'Chico Buarque', rank => 1 }) ;
17my $artist3 = $schema->resultset("Artist")->create({ artistid => 23, name => 'Ziraldo', rank => 1 });
18my $artist4 = $schema->resultset("Artist")->create({ artistid => 24, name => 'Paulo Caruso', rank => 20 });
e98e6478 19
20my @artworks;
b5c8410c 21
b5c8410c 22foreach my $year (1975..1985) {
e98e6478 23 my $cd = $artist->create_related('cds', { year => $year, title => 'Compilation from ' . $year });
24 push @artworks, $cd->create_related('artwork', {});
b5c8410c 25}
26
9aae3566 27foreach my $year (1975..1995) {
e98e6478 28 my $cd = $artist2->create_related('cds', { year => $year, title => 'Compilation from ' . $year });
29 push @artworks, $cd->create_related('artwork', {});
30}
31
32foreach my $artwork (@artworks) {
33 $artwork->create_related('artwork_to_artist', { artist => $_ }) for ($artist3, $artist4);
9aae3566 34}
b5c8410c 35
abf8d91e 36
7689b9e5 37my $cds_80s_rs = $artist->cds_80s;
eb3bb737 38is_same_sql_bind(
39 $cds_80s_rs->as_query,
40 '(
41 SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
42 FROM cd me
43 WHERE ( ( me.artist = ? AND ( me.year < ? AND me.year > ? ) ) )
44 )',
45 [
b4e9f590 46 [
f8193780 47 {}
b4e9f590 48 => 21
49 ],
50 [
51 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
52 => 1990
53 ],
54 [
55 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
56 => 1979
57 ],
58 ],
eb3bb737 59);
7689b9e5 60my @cds_80s = $cds_80s_rs->all;
d5a14c53 61is(@cds_80s, 6, '6 80s cds found (1980 - 1985)');
62map { ok($_->year < 1990 && $_->year > 1979) } @cds_80s;
b5c8410c 63
7689b9e5 64
eb3bb737 65my $cds_90s_rs = $artist2->cds_90s;
66is_same_sql_bind(
67 $cds_90s_rs->as_query,
68 '(
69 SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
70 FROM artist artist__row
71 JOIN cd me
72 ON ( me.artist = artist__row.artistid AND ( me.year < ? AND me.year > ? ) )
73 WHERE ( artist__row.artistid = ? )
74 )',
75 [
b4e9f590 76 [
77 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
78 => 2000
79 ],
80 [
81 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
82 => 1989
83 ],
84 [ { sqlt_datatype => 'integer', dbic_colname => 'artist__row.artistid' }
85 => 22
86 ],
eb3bb737 87 ]
88);
93508f48 89
90# re-test with ::-containing moniker name
91# (we don't have any currently, so fudge it with lots of local() )
92{
93 local $schema->source('Artist')->{source_name} = 'Ar::Tist';
94 local $artist2->{related_resultsets};
95
96 is_same_sql_bind(
97 $artist2->cds_90s->as_query,
98 '(
99 SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
100 FROM artist ar_tist__row
101 JOIN cd me
102 ON ( me.artist = ar_tist__row.artistid AND ( me.year < ? AND me.year > ? ) )
103 WHERE ( ar_tist__row.artistid = ? )
104 )',
105 [
106 [
107 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
108 => 2000
109 ],
110 [
111 { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.year' }
112 => 1989
113 ],
114 [ { sqlt_datatype => 'integer', dbic_colname => 'ar_tist__row.artistid' }
115 => 22
116 ],
117 ]
118 );
119}
120
121
7689b9e5 122my @cds_90s = $cds_90s_rs->all;
d5a14c53 123is(@cds_90s, 6, '6 90s cds found (1990 - 1995) even with non-optimized search');
124map { ok($_->year < 2000 && $_->year > 1989) } @cds_90s;
b5c8410c 125
eb3bb737 126lives_ok {
127 my @cds_90s_95 = $artist2->cds_90s->search({ 'me.year' => 1995 });
128 is(@cds_90s_95, 1, '1 90s (95) cds found even with non-optimized search');
129 map { ok($_->year == 1995) } @cds_90s_95;
130} 'should preserve chain-head "me" alias (API-consistency)';
7689b9e5 131
d5a14c53 132# search for all artists prefetching published cds in the 80s...
d5a14c53 133my @all_artists_with_80_cds = $schema->resultset("Artist")->search
134 ({ 'cds_80s.cdid' => { '!=' => undef } }, { join => 'cds_80s', distinct => 1 });
135
136is_deeply(
137 [ sort ( map { $_->year } map { $_->cds_80s->all } @all_artists_with_80_cds ) ],
138 [ sort (1980..1989, 1980..1985) ],
139 '16 correct cds found'
140);
141
abf8d91e 142lives_ok {
143
144my @all_artists_with_80_cds_pref = $schema->resultset("Artist")->search
145 ({ 'cds_80s.cdid' => { '!=' => undef } }, { prefetch => 'cds_80s' });
146
147is_deeply(
148 [ sort ( map { $_->year } map { $_->cds_80s->all } @all_artists_with_80_cds_pref ) ],
149 [ sort (1980..1989, 1980..1985) ],
150 '16 correct cds found'
151);
152
153} 'prefetchy-fetchy-fetch';
abf8d91e 154
8c7c8398 155# create_related a plain cd via the equoivalent coderef cond, with no extra conditions
156lives_ok {
157 $artist->create_related('cds_cref_cond', { title => 'related creation via coderef cond', year => '2010' } );
158} 'created_related with simple condition works';
abf8d91e 159
d5a14c53 160# try to create_related a 80s cd
161throws_ok {
162 $artist->create_related('cds_80s', { title => 'related creation 1' });
209a2064 163} qr/\QUnable to complete value inferrence - custom relationship 'cds_80s' on source 'Artist' returns conditions instead of values for column(s): 'year'/,
78b948c3 164'Create failed - complex cond';
d5a14c53 165
166# now supply an explicit arg overwriting the ambiguous cond
8c7c8398 167my $cd_2020 = $artist->create_related('cds_80s', { title => 'related creation 2', year => '2020' });
168my $id_2020 = $cd_2020->id;
d5a14c53 169is(
170 $schema->resultset('CD')->find($id_2020)->title,
171 'related creation 2',
172 '2020 CD created correctly'
173);
174
175# try a default year from a specific rel
176my $id_1984 = $artist->create_related('cds_84', { title => 'related creation 3' })->id;
177is(
178 $schema->resultset('CD')->find($id_1984)->title,
179 'related creation 3',
180 '1984 CD created correctly'
181);
182
183# try a specific everything via a non-simplified rel
184throws_ok {
185 $artist->create_related('cds_90s', { title => 'related_creation 4', year => '2038' });
209a2064 186} qr/\QRelationship 'cds_90s' on source 'Artist' does not resolve to a join-free condition fragment/,
78b948c3 187'Create failed - non-simplified rel';
b5c8410c 188
d5a14c53 189# Do a self-join last-entry search
c8d7a1d1 190my @last_tracks;
b5c8410c 191for my $cd ($schema->resultset('CD')->search ({}, { order_by => 'cdid'})->all) {
c8d7a1d1 192 push @last_tracks, $cd->tracks
193 ->search ({}, { order_by => { -desc => 'position'} })
194 ->next || ();
b5c8410c 195}
196
c8d7a1d1 197my $last_tracks_rs = $schema->resultset('Track')->search (
bdf6d515 198 {'next_tracks.trackid' => undef},
199 { join => 'next_tracks', order_by => 'me.cd' },
b5c8410c 200);
201
202is_deeply (
c8d7a1d1 203 [$last_tracks_rs->get_column ('trackid')->all],
204 [ map { $_->trackid } @last_tracks ],
b5c8410c 205 'last group-entry via self-join works',
206);
207
fe4118b1 208is_deeply (
209 [map { $_->last_track->id } grep { $_->last_track } $schema->resultset('CD')->search ({}, { order_by => 'cdid', prefetch => 'last_track'})->all],
210 [ map { $_->trackid } @last_tracks ],
211 'last_track via insane subquery condition works',
212);
213
214is_deeply (
215 [map { $_->last_track->id } grep { $_->last_track } $schema->resultset('CD')->search ({}, { order_by => 'cdid'})->all],
216 [ map { $_->trackid } @last_tracks ],
217 'last_track via insane subquery condition works, even without prefetch',
218);
219
e6f5efab 220
e98e6478 221my $artwork = $schema->resultset('Artwork')->search({},{ order_by => 'cd_id' })->first;
222my @artists = $artwork->artists->all;
223is(scalar @artists, 2, 'the two artists are associated');
224
225my @artwork_artists = $artwork->artwork_to_artist->all;
226foreach (@artwork_artists) {
227 lives_ok {
228 my $artista = $_->artist;
2f7d81b4 229 my $artistb = $_->artist_limited_rank;
e98e6478 230 ok($artista->rank < 10 ? $artistb : 1, 'belongs_to with custom rel works.');
2f7d81b4 231 my $artistc = $_->artist_limited_rank_opaque;
e98e6478 232 ok($artista->rank < 10 ? $artistc : 1, 'belongs_to with custom rel works even in non-simplified.');
233 } 'belongs_to works with custom rels';
234}
235
e6f5efab 236is(
237 $schema->resultset('Artwork')
238 ->related_resultset( 'artwork_to_artist_via_opaque_customcond' )
239 ->related_resultset( 'artist' )
240 ->search({}, { collapse => 1 })
241 ->count,
242 2,
243 'Custom rel works correctly',
244);
e98e6478 245
e6f5efab 246is (
247 scalar $artwork->all_artists_via_opaque_customcond->all,
248 2,
249 'Expected two m2m associated artist objects via opaque costom cond'
250);
e98e6478 251
e6f5efab 252for (qw( artist_limited_rank artist_limited_rank_opaque )) {
253 is(
254 $schema->resultset('Artwork')
255 ->related_resultset( 'artwork_to_artist_via_opaque_customcond' )
256 ->related_resultset( $_ )
257 ->search({}, { collapse => 1 })
258 ->count,
259 1,
260 'Condition over double custom rel works correctly',
261 );
262
263 is (
264 scalar $artwork->$_->all,
265 1,
266 'Expected one m2m associated artist object via opaque custom cond + conditional far cond'
267 );
268}
e98e6478 269
270
c8d7a1d1 271# Make a single for each last_track
272my @singles = map {
273 $_->create_related('cd_single', {
274 title => $_->title . ' (the single)',
275 artist => $artist,
276 year => 1999,
277 }) } @last_tracks
278;
279
280# See if chaining works
281is_deeply (
282 [ map { $_->title } $last_tracks_rs->search_related('cd_single')->all ],
283 [ map { $_->title } @singles ],
284 'Retrieved singles in proper order'
285);
286
287# See if prefetch works
288is_deeply (
289 [ map { $_->cd_single->title } $last_tracks_rs->search({}, { prefetch => 'cd_single' })->all ],
290 [ map { $_->title } @singles ],
291 'Prefetched singles in proper order'
292);
293
e884e5d9 294# test set_from_related/find_related with a belongs_to custom condition
295my $preexisting_cd = $schema->resultset('CD')->find(1);
296
297my $cd_single_track = $schema->resultset('CD')->create({
298 artist => $artist,
299 title => 'one one one',
300 year => 2001,
301 tracks => [{ title => 'uno uno uno' }]
302});
303
304my $single_track = $cd_single_track->tracks->next;
305
7df2b5df 306is(
307 $single_track->cd_cref_cond->title,
308 $cd_single_track->title,
309 'Got back the expected single-track cd title',
310);
311
e884e5d9 312is_deeply
313 { $schema->resultset('Track')->find({ cd_cref_cond => { cdid => $cd_single_track->id } })->get_columns },
314 { $single_track->get_columns },
315 'Proper find with related via coderef cond',
316;
317
c200d949 318warnings_exist {
319 is_same_sql_bind(
320 $single_track->deliberately_broken_all_cd_tracks->as_query,
321 '(
322 SELECT me.trackid, me.cd, me.position, me.title, me.last_updated_on, me.last_updated_at
323 FROM track track__row
324 JOIN track me
325 ON me.cd = ?
326 WHERE track__row.trackid = ?
327 )',
328 [
329 [{ dbic_colname => "me.cd", sqlt_datatype => "integer" }
330 => "track__row.cd" ],
331 [{ dbic_colname => "track__row.trackid", sqlt_datatype => "integer" }
332 => 19 ],
333 ],
334 'Expected nonsensical JOIN cond',
335 ),
336} qr/\Qrelationship 'deliberately_broken_all_cd_tracks' on source 'Track' specifies equality of column 'cd' and the *VALUE* 'cd' (you did not use the { -ident => ... } operator)/,
337 'Warning on 99.9999% malformed custom cond'
338;
339
e884e5d9 340$single_track->set_from_related( cd_cref_cond => undef );
341ok $single_track->is_column_changed('cd');
342is $single_track->get_column('cd'), undef, 'UNset from related via coderef cond';
343is $single_track->cd, undef, 'UNset related object via coderef cond';
344
345$single_track->discard_changes;
346
347$single_track->set_from_related( cd_cref_cond => $preexisting_cd );
348ok $single_track->is_column_changed('cd');
349is $single_track->get_column('cd'), 1, 'set from related via coderef cond';
350is_deeply
351 { $single_track->cd->get_columns },
352 { $preexisting_cd->get_columns },
8c7c8398 353 'set from related via coderef cond inflates properly',
e884e5d9 354;
8c7c8398 355
7967dcec 356throws_ok {
357 local $schema->source('Track')->relationship_info('cd_cref_cond')->{cond} = sub { 1,2,3 };
358 $schema->resultset('Track')->find({ cd_cref_cond => {} });
359} qr/\QA custom condition coderef can return at most 2 conditions, but relationship 'cd_cref_cond' on source 'Track' returned extra values: 3/;
360
b5c8410c 361done_testing;