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