Bring out the big-paranoia-harness - make describe_env infallible
[dbsrgits/DBIx-Class.git] / t / 88result_set_column.t
CommitLineData
c0329273 1BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
70350518 3use strict;
4e55c3ae 4use warnings;
70350518 5
6use Test::More;
4e55c3ae 7use Test::Warn;
5d1fc7dc 8use Test::Exception;
1b658919 9
10# MASSIVE FIXME - there is a hole in ::RSC / as_subselect_rs
11# losing the order. Needs a rework/extract of the realiaser,
12# and that's a whole another bag of dicks
13BEGIN { $ENV{DBIC_SHUFFLE_UNORDERED_RESULTSETS} = 0 }
14
c0329273 15
a5a7bb73 16use DBICTest ':DiffSQL';
70350518 17
a47e1233 18my $schema = DBICTest->init_schema();
2bb7b40b 19
ee12e25a 20my $rs = $schema->resultset("CD");
21
22cmp_ok (
23 $rs->count,
fb88ca2c 24 '>',
ee12e25a 25 $rs->search ({}, {columns => ['year'], distinct => 1})->count,
26 'At least one year is the same in rs'
27);
2bb7b40b 28
29my $rs_title = $rs->get_column('title');
30my $rs_year = $rs->get_column('year');
20ea4813 31my $max_year = $rs->get_column(\'MAX (year)');
2bb7b40b 32
fb88ca2c 33my @all_titles = $rs_title->all;
34cmp_ok(scalar @all_titles, '==', 5, "five titles returned");
35
36my @nexted_titles;
37while (my $r = $rs_title->next) {
38 push @nexted_titles, $r;
39}
40
41is_deeply (\@all_titles, \@nexted_titles, 'next works');
42
5d62876f 43is_deeply( [ sort $rs_year->func('DISTINCT') ], [ 1997, 1998, 1999, 2001 ], "wantarray context okay");
20ea4813 44ok ($max_year->next == $rs_year->max, q/get_column (\'FUNC') ok/);
5d62876f 45
2bb7b40b 46cmp_ok($rs_year->max, '==', 2001, "max okay for year");
47is($rs_title->min, 'Caterwaulin\' Blues', "min okay for title");
48
49cmp_ok($rs_year->sum, '==', 9996, "three artists returned");
50
b74b15b0 51{
52 my $rso_year = $rs->search({}, { order_by => 'cdid' })->get_column('year');
53 is($rso_year->next, 1999, "reset okay");
66521001 54
b74b15b0 55 is($rso_year->first, 1999, "first okay");
66521001 56
b74b15b0 57 warnings_exist (sub {
58 is($rso_year->single, 1999, "single okay");
59 }, qr/Query returned more than one row/, 'single warned');
60}
4e55c3ae 61
ee12e25a 62
63# test distinct propagation
64is_deeply (
6f723769 65 [sort $rs->search ({}, { distinct => 1 })->get_column ('year')->all],
66 [sort $rs_year->func('distinct')],
ee12e25a 67 'distinct => 1 is passed through properly',
68);
69
eb58c082 70# test illogical distinct
71my $dist_rs = $rs->search ({}, {
72 columns => ['year'],
73 distinct => 1,
74 order_by => { -desc => [qw( cdid year )] },
75});
76
77is_same_sql_bind(
78 $dist_rs->as_query,
79 '(
80 SELECT me.year
81 FROM cd me
82 GROUP BY me.year
83 ORDER BY MAX(cdid) DESC, year DESC
84 )',
85 [],
86 'Correct SQL on external-ordered distinct',
87);
88
89is_same_sql_bind(
90 $dist_rs->count_rs->as_query,
91 '(
92 SELECT COUNT( * )
93 FROM (
94 SELECT me.year
95 FROM cd me
96 GROUP BY me.year
97 ) me
98 )',
99 [],
100 'Correct SQL on count of external-orderdd distinct',
101);
102
103is (
104 $dist_rs->count_rs->next,
105 4,
106 'Correct rs-count',
107);
108
109is (
110 $dist_rs->count,
111 4,
112 'Correct direct count',
113);
114
5d1fc7dc 115# test +select/+as for single column
ae515736 116my $psrs = $schema->resultset('CD')->search({},
117 {
472d7df3 118 '+select' => \'MAX(year)',
119 '+as' => 'last_year'
ae515736 120 }
121);
472d7df3 122lives_ok(sub { $psrs->get_column('last_year')->next }, '+select/+as additional column "last_year" present (scalar)');
5d1fc7dc 123dies_ok(sub { $psrs->get_column('noSuchColumn')->next }, '+select/+as nonexistent column throws exception');
ae515736 124
66e33361 125# test +select/+as for overriding a column
126$psrs = $schema->resultset('CD')->search({},
127 {
128 'select' => \"'The Final Countdown'",
129 'as' => 'title'
130 }
131);
132is($psrs->get_column('title')->next, 'The Final Countdown', '+select/+as overridden column "title"');
133
134
5d1fc7dc 135# test +select/+as for multiple columns
ae515736 136$psrs = $schema->resultset('CD')->search({},
137 {
472d7df3 138 '+select' => [ \'LENGTH(title) AS title_length', 'title' ],
139 '+as' => [ 'tlength', 'addedtitle' ]
ae515736 140 }
141);
472d7df3 142lives_ok(sub { $psrs->get_column('tlength')->next }, '+select/+as multiple additional columns, "tlength" column present');
5d1fc7dc 143lives_ok(sub { $psrs->get_column('addedtitle')->next }, '+select/+as multiple additional columns, "addedtitle" column present');
144
66e33361 145# test that +select/+as specs do not leak
146is_same_sql_bind (
147 $psrs->get_column('year')->as_query,
148 '(SELECT me.year FROM cd me)',
149 [],
150 'Correct SQL for get_column/as'
5d1fc7dc 151);
66e33361 152
153is_same_sql_bind (
154 $psrs->get_column('addedtitle')->as_query,
155 '(SELECT me.title FROM cd me)',
156 [],
157 'Correct SQL for get_column/+as col'
158);
159
160is_same_sql_bind (
472d7df3 161 $psrs->get_column('tlength')->as_query,
162 '(SELECT LENGTH(title) AS title_length FROM cd me)',
66e33361 163 [],
164 'Correct SQL for get_column/+as func'
165);
166
472d7df3 167# test that order_by over a function forces a subquery
168lives_ok ( sub {
169 is_deeply (
170 [ $psrs->search ({}, { order_by => { -desc => 'title_length' } })->get_column ('title')->all ],
171 [
172 "Generic Manufactured Singles",
173 "Come Be Depressed With Us",
174 "Caterwaulin' Blues",
175 "Spoonful of bees",
176 "Forkful of bees",
177 ],
178 'Subquery count induced by aliased ordering function',
179 );
180});
181
182# test for prefetch not leaking
3f6cc7e4 183{
184 my $rs = $schema->resultset("CD")->search({}, { prefetch => 'artist' });
185 my $rsc = $rs->get_column('year');
186 is( $rsc->{_parent_resultset}->{attrs}->{prefetch}, undef, 'prefetch wiped' );
187}
cda5e082 188
189# test sum()
190is ($schema->resultset('BooksInLibrary')->get_column ('price')->sum, 125, 'Sum of a resultset works correctly');
191
192# test sum over search_related
193my $owner = $schema->resultset('Owners')->find ({ name => 'Newton' });
194ok ($owner->books->count > 1, 'Owner Newton has multiple books');
195is ($owner->search_related ('books')->get_column ('price')->sum, 60, 'Correctly calculated price of all owned books');
d8dbe471 196
197
198# make sure joined/prefetched get_column of a PK dtrt
d8dbe471 199$rs->reset;
200my $j_rs = $rs->search ({}, { join => 'tracks' })->get_column ('cdid');
201is_deeply (
44976045 202 [ sort $j_rs->all ],
203 [ sort map { my $c = $rs->next; ( ($c->id) x $c->tracks->count ) } (1 .. $rs->count) ],
d8dbe471 204 'join properly explodes amount of rows from get_column',
205);
206
207$rs->reset;
208my $p_rs = $rs->search ({}, { prefetch => 'tracks' })->get_column ('cdid');
209is_deeply (
fb88ca2c 210 [ sort $p_rs->all ],
211 [ sort $rs->get_column ('cdid')->all ],
d8dbe471 212 'prefetch properly collapses amount of rows from get_column',
213);
b7c79955 214
908aa1bb 215$rs->reset;
216my $pob_rs = $rs->search({}, {
217 select => ['me.title', 'tracks.title'],
218 prefetch => 'tracks',
219 order_by => [{-asc => ['position']}],
220 group_by => ['me.title', 'tracks.title'],
221});
222is_same_sql_bind (
223 $pob_rs->get_column("me.title")->as_query,
224 '(SELECT me.title FROM (SELECT me.title, tracks.title FROM cd me LEFT JOIN track tracks ON tracks.cd = me.cdid GROUP BY me.title, tracks.title ORDER BY position ASC) me)',
225 [],
226 'Correct SQL for prefetch/order_by/group_by'
227);
228
aca094b4 229# test aggregate on a function (create an extra track on one cd)
3214abc7 230{
231 my $tr_rs = $schema->resultset("Track");
232 $tr_rs->create({ cd => 2, title => 'dealbreaker' });
233
234 is(
235 $tr_rs->get_column('cd')->max,
236 5,
237 "Correct: Max cd in Track is 5"
238 );
239
240 my $track_counts_per_cd_via_group_by = $tr_rs->search({}, {
241 columns => [ 'cd', { cnt => { count => 'trackid', -as => 'cnt' } } ],
242 group_by => 'cd',
243 })->get_column('cnt');
244
245 is ($track_counts_per_cd_via_group_by->max, 4, 'Correct max tracks per cd');
246 is ($track_counts_per_cd_via_group_by->min, 3, 'Correct min tracks per cd');
247 is (
248 sprintf('%0.1f', $track_counts_per_cd_via_group_by->func('avg') ),
249 '3.2',
250 'Correct avg tracks per cd'
251 );
252}
253
aca094b4 254# test exotic scenarious (create a track-less cd)
255# "How many CDs (not tracks) have been released per year where a given CD has at least one track and the artist isn't evancarroll?"
256{
257
258 $schema->resultset('CD')->create({ artist => 1, title => 'dealbroker no tracks', year => 2001 });
259
885c3dbd 260 my $yp1 = \[ 'year + ?', 1 ];
261
aca094b4 262 my $rs = $schema->resultset ('CD')->search (
263 { 'artist.name' => { '!=', 'evancarrol' }, 'tracks.trackid' => { '!=', undef } },
264 {
265 order_by => 'me.year',
266 join => [qw(artist tracks)],
885c3dbd 267 columns => [
268 'year',
269 { cnt => { count => 'me.cdid' } },
270 { year_plus_one => $yp1 },
271 ],
aca094b4 272 },
273 );
274
275 my $rstypes = {
885c3dbd 276 'explicitly grouped' => $rs->search_rs({}, { group_by => [ 'year', $yp1 ] } ),
aca094b4 277 'implicitly grouped' => $rs->search_rs({}, { distinct => 1 }),
278 };
279
280 for my $type (keys %$rstypes) {
281 is ($rstypes->{$type}->count, 4, "correct cd count with $type column");
282
283 is_deeply (
284 [ $rstypes->{$type}->get_column ('year')->all ],
285 [qw(1997 1998 1999 2001)],
286 "Getting $type column works",
287 );
288 }
289
290 # Why do we test this - we want to make sure that the selector *will* actually make
291 # it to the group_by as per the distinct => 1 contract. Before 0.08251 this situation
292 # would silently drop the group_by entirely, likely ending up with nonsensival results
293 # With the current behavior the user will at least get a nice fat exception from the
294 # RDBMS (or maybe the RDBMS will even decide to handle the situation sensibly...)
885c3dbd 295 for (
296 [ cnt => 'COUNT( me.cdid )' ],
297 [ year_plus_one => 'year + ?' => [ {} => 1 ] ],
298 ) {
299 my ($col, $sel_grp_sql, @sel_grp_bind) = @$_;
300
301 warnings_exist { is_same_sql_bind(
302 $rstypes->{'implicitly grouped'}->get_column($col)->as_query,
303 "(
304 SELECT $sel_grp_sql
305 FROM cd me
306 JOIN artist artist
307 ON artist.artistid = me.artist
308 LEFT JOIN track tracks
309 ON tracks.cd = me.cdid
310 WHERE artist.name != ? AND tracks.trackid IS NOT NULL
311 GROUP BY $sel_grp_sql
312 ORDER BY MIN(me.year)
313 )",
314 [
315 @sel_grp_bind,
316 [ { dbic_colname => 'artist.name', sqlt_datatype => 'varchar', sqlt_size => 100 }
317 => 'evancarrol' ],
318 @sel_grp_bind,
319 ],
320 'Expected (though nonsensical) SQL generated on rscol-with-distinct-over-function',
321 ) } qr/
322 \QUse of distinct => 1 while selecting anything other than a column \E
323 \Qdeclared on the primary ResultSource is deprecated (you selected '$col')\E
324 /x, 'deprecation warning';
325 }
aca094b4 326
327 {
328 local $TODO = 'multiplying join leaks through to the count aggregate... this may never actually work';
329 is_deeply (
330 [ $rstypes->{'explicitly grouped'}->get_column ('cnt')->all ],
331 [qw(1 1 1 2)],
332 "Get aggregate over group works",
333 );
334 }
335}
336
b7c79955 337done_testing;