* Fixed test cases of ResultSetColumn vs. +select/+as (they used to unconditionally...
[dbsrgits/DBIx-Class.git] / t / 88result_set_column.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 plan tests => 16;
12
13 my $cd;
14 my $rs = $cd = $schema->resultset("CD")->search({});
15
16 my $rs_title = $rs->get_column('title');
17 my $rs_year = $rs->get_column('year');
18 my $max_year = $rs->get_column(\'MAX (year)');
19
20 is($rs_title->next, 'Spoonful of bees', "next okay");
21 is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ],  "wantarray context okay");
22 ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
23
24 my @all = $rs_title->all;
25 cmp_ok(scalar @all, '==', 5, "five titles returned");
26
27 cmp_ok($rs_year->max, '==', 2001, "max okay for year");
28 is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
29
30 cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
31
32 # test +select/+as for single column
33 my $psrs = $schema->resultset('CD')->search({},
34     {
35         '+select'   => \'COUNT(*)',
36         '+as'       => 'count'
37     }
38 );
39 lives_ok(sub { $psrs->get_column('count')->next }, '+select/+as additional column "count" present (scalar)');
40 dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
41
42 # test +select/+as for multiple columns
43 $psrs = $schema->resultset('CD')->search({},
44     {
45         '+select'   => [ \'COUNT(*)', 'title' ],
46         '+as'       => [ 'count', 'addedtitle' ]
47     }
48 );
49 lives_ok(sub { $psrs->get_column('count')->next }, '+select/+as multiple additional columns, "count" column present');
50 lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
51
52 # test +select/+as for overriding a column
53 $psrs = $schema->resultset('CD')->search({},
54     {
55         'select'   => \"'The Final Countdown'",
56         'as'       => 'title'
57     }
58 );
59 is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
60
61 {
62   my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
63   my $rsc = $rs->get_column('year');
64   is( $rsc->{_parent_resultset}->{attrs}->{prefetch}, undef, 'prefetch wiped' );
65 }
66
67 # test sum()
68 is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
69
70 # test sum over search_related
71 my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
72 ok ($owner->books->count > 1, 'Owner Newton has multiple books');
73 is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');