c94758cae5819fa9450df70a59c1029212fdbca8
[dbsrgits/DBIx-Class.git] / t / relationship / custom.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8
9 my $schema = DBICTest->init_schema();
10
11
12 my $artist = $schema->resultset("Artist")->create({ name => 'Michael Jackson' });
13 foreach my $year (1975..1985) {
14   $artist->create_related('cds', { year => $year, title => 'Compilation from ' . $year });
15 }
16
17 my $artist2 = $schema->resultset("Artist")->create({ name => 'Chico Buarque' }) ;
18 foreach my $year (1975..1995) {
19   $artist2->create_related('cds', { year => $year, title => 'Compilation from ' . $year });
20 }
21
22 my @cds_80s = $artist->cds_80s;
23 is(@cds_80s, 6, '6 80s cds found');
24
25 my @cds_90s = $artist2->cds_90s;
26 is(@cds_90s, 6, '6 90s cds found even with non-optimized search');
27
28 map { ok($_->year < 1990 && $_->year > 1979) } @cds_80s;
29
30
31 # search for all artists prefetching published cds in the 80s...
32 my @all_cds_80s = $schema->resultset("Artist")->search
33   ({ 'cds_80s_noopt.cdid' => { '!=' => undef } }, { join => 'cds_80s_noopt' });
34 is(@all_cds_80s, 16, '16 cds found even with the non-optimized search');
35
36 my @last_track_ids;
37 for my $cd ($schema->resultset('CD')->search ({}, { order_by => 'cdid'})->all) {
38   push @last_track_ids, $cd->tracks
39                             ->search ({}, { order_by => { -desc => 'position'} })
40                               ->get_column ('trackid')
41                                 ->next;
42 }
43
44 my $last_tracks = $schema->resultset('Track')->search (
45   {'next_track.trackid' => undef},
46   { join => 'next_track', order_by => 'me.cd' },
47 );
48
49 is_deeply (
50   [$last_tracks->get_column ('trackid')->all],
51   [ grep { $_ } @last_track_ids ],
52   'last group-entry via self-join works',
53 );
54
55 done_testing;