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