52221f9a4ac49ad11a51421e9d673067e7cdb04f
[dbsrgits/DBIx-Class.git] / t / 88result_set_column.t
1 use strict;
2 use warnings;  
3
4 use Test::More;
5 use lib qw(t/lib);
6 use DBICTest;
7
8 my $schema = DBICTest->init_schema();
9
10 plan tests => 14;
11
12 my $cd;
13 my $rs = $cd = $schema->resultset("CD")->search({});
14
15 my $rs_title = $rs->get_column('title');
16 my $rs_year = $rs->get_column('year');
17 my $max_year = $rs->get_column(\'MAX (year)');
18
19 is($rs_title->next, 'Spoonful of bees', "next okay");
20 is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ],  "wantarray context okay");
21 ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
22
23 my @all = $rs_title->all;
24 cmp_ok(scalar @all, '==', 5, "five titles returned");
25
26 cmp_ok($rs_year->max, '==', 2001, "max okay for year");
27 is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
28
29 cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
30
31 my $psrs = $schema->resultset('CD')->search({},
32     {
33         '+select'   => \'COUNT(*)',
34         '+as'       => 'count'
35     }
36 );
37 ok(defined($psrs->get_column('count')), '+select/+as count');
38
39 $psrs = $schema->resultset('CD')->search({},
40     {
41         '+select'   => [ \'COUNT(*)', 'title' ],
42         '+as'       => [ 'count', 'addedtitle' ]
43     }
44 );
45 ok(defined($psrs->get_column('count')), '+select/+as arrayref count');
46 ok(defined($psrs->get_column('addedtitle')), '+select/+as title');
47
48 {
49   my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
50   my $rsc = $rs->get_column('year');
51   is( $rsc->{_parent_resultset}->{attrs}->{prefetch}, undef, 'prefetch wiped' );
52 }
53
54 # test sum()
55 is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
56
57 # test sum over search_related
58 my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
59 ok ($owner->books->count > 1, 'Owner Newton has multiple books');
60 is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');